Re: strptime and microseconds

2007-10-19 Thread mathieu
On Oct 18, 10:54 pm, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> On 18 oct, 13:46, mathieu <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Oct 18, 6:36 pm, mathieu <[EMAIL PROTECTED]> wrote:
> > > >   I am trying to use strptime to parse my microseconds but I was not
> > > > able the documentation for it. The only list I found was:
> > Ok final version is simply:
>
> > s1 = "20070619"
> > s2 = "115344.51"
> > s3 = "115446.123456"
>
> > ms2 = eval(s2) % 1
> > mms2 = int(ms2 * 100 + 0.5)
> > ms3 = eval(s3) % 1
> > mms3 = int(ms3 * 100 + 0.5)
>
> > s = s1 + s2
> > d1 = datetime(*strptime(s[:14], "%Y%m%d%H%M%S")[0:6])
> > d1 = d1.replace(microsecond = mms2)
>
> What about this:
>
> py> import datetime
> py> s1 = "20070619 115344.025"
> py> p1, p2 = s1.split(".", 1)
> py> d1 = datetime.datetime.strptime(p1, "%Y%m%d %H%M%S")

python2.3:
from time import strptime

> py> ms = int(p2.ljust(6,'0')[:6])

ljust padds with space only in python 2.3. But thanks anyway your
solution is much cleaner !

-Mathieu

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What Data is Available With a Pickled Object Over a Socket?

2007-10-19 Thread Hendrik van Rooyen
 "milan_sanremo" wrote:


> 
> pickledMailbag = cPickle.dump(mb, HIGHEST_PROTOCOL)
> 

If you are going to send it over a socket - is it not better to use
dumps instead of dump?

- Hendrik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-19 Thread Hrvoje Niksic
Abandoned <[EMAIL PROTECTED]> writes:

>> Use a different column type for cache2's column, one more appropriate
>> for storing binary characters (perhaps BYTEA for Postgres).  Don't
>> forget to also use a bind variable, something like:
>>
>> cursor.execute("INSERT INTO cache2 VALUES (?)", a)
>>
>> Using "INSERT ... ('%s')" % (a) won't work, since the huge binary
>> string in a can contain arbitrary characters, including the single
>> quote.
>
> I tryed:
> cursor.execute("INSERT INTO cache2 VALUES (?)", a)

Why are you ignoring the first sentence: "Use a different column type
for cache2's column, ..."?  The use of bind variables in INSERT will
work only *after* you do the rest of the work.
-- 
http://mail.python.org/mailman/listinfo/python-list


how to iterate over sequence and non-sequence ?

2007-10-19 Thread stef mientki
hello,

I generate dynamically a sequence of values,
but this "sequence" could also have length 1 or even length 0.

So I get some line in the form of:
  line = '(2,3,4)'
  line = ''
  line = '(2)'
(in fact these are not constant numbers, but all kind of integer 
variables, coming from all over the program, selected from a tree, that 
shows all "reachable" variables)

So in fact I get the value from an exec statement, like this
  exec 'signals = ' + line

Now I want to iterate over "signals", which works perfect if there are 2 
or more signals,
but it fails when I have none or just 1 signal.
for value in signals :
do something

As this meant for real-time signals, I want it fast, so (I think) I 
can't afford extensive testing.

Any smart solution there ?

thanks,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-19 Thread Bruno Desthuilliers
Peter Otten a écrit :
(snip)
> Before you go on with your odd caching schemes -- is the database properly
> indexed? Something like
> 
> CREATE UNIQUE INDEX mytable_id1_id2 ON mytable (id-1, id-2);
> 
> (actual syntax may differ) might speed up the lookup operation
> enough that you can do without caching.

Im my arms(tm) ! At least some sensible advice...

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: python logging module and custom handler specified in config file

2007-10-19 Thread Frank Aune
On Thursday 18 October 2007 19:26:59 Vinay Sajip wrote:
> The values in the config file are interpreted in the context of the
> logging module's namespace. Hence, one way of achieving what you want
> is putting any custom handlers in
> a module of your own, and providing a binding in the logging module's
> namespace. 

What if you want to datestamp filenames for filehandlers, say with todays date 
for example?

[handler_file]
class=FileHandler
level=NOTSET
formatter=normal
args=('filename.log', 'w')

Say you want filenames to be on format filename-MMDD.log 

Thanks,
Frank
-- 
http://mail.python.org/mailman/listinfo/python-list


dynamic invoke

2007-10-19 Thread lukasz . f24
Hello,

Is there any way (other then eval) to invoke a method by passing
method name in a string.
It's very simple in php:
$oFoo = new Foo();
$dynamiMethod = "bar";
$oFoo->$dynamiMethod();

Unfortunately I can't find a good solution to do the same thing in
python. Does it have some build-in function to do it?

Kind Regards,

Lukasz.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-19 Thread Hrvoje Niksic
Hrvoje Niksic <[EMAIL PROTECTED]> writes:

> If you're generating the string from Python, use cPickle instead.
> Much faster:
[...]
 t0 = time.time(); d2 = eval(s); t1 = time.time(); t1-t0
> 1.5457899570465088
 t0 = time.time(); d2 = pickle.loads(s); t1 = time.time(); t1-t0
> 0.060307979583740234

It just occurred to me, for simple data structures like the ones we're
discussing here (dicts of ints), marshal should also be considered.
marshal is the module used for generating and loading .pyc files and,
while it doesn't support all the bells and whistles of pickle, it's
very fast:

>>> t0 = time.time(); d2 = marshal.loads(s); t1 = time.time(); t1-t0
0.029728889465332031

Benchmarks made with the timeit module confirm this difference.

Marshal has the added advantage of using much less space than the
(binary) pickle -- the example dictionary provided above pickled to a
string of 2667791 bytes, while marshal produced a string of 172
bytes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: image resize question

2007-10-19 Thread Tim Arnold
"Matimus" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Oct 18, 11:56 am, "Tim Arnold" <[EMAIL PROTECTED]> wrote:
>> Hi, I'm using the Image module to resize PNG images from 300 to 100dpi 
>> for
>> use in HTML pages, but I'm losing some vertical and horizontal lines in 
>> the
>> images (usually images of x-y plots).
>>
>> Here's what I do:
>> import Image
>> def imgResize(self,filename):
>> img = Image.open(filename)
>> dpi = img.info.get('dpi')
>> if dpi and 295 < int(dpi[0]) < 305:
>> wd = img.size[0]/3.0 #convert from 300dpi to 100dpi
>> ht = img.size[1]/3.0
>> newimg= img.resize((int(wd),int(ht)))
>> newimg.save(filename)
>>
>> imgResize('myimage.png')
>>
>> Can someone point me to a better way so I don't lose the reference lines 
>> in
>> the images?
>> thanks,
>> --Tim Arnold
>
> Resize accepts a second parameter that is used to determine what kind
> of downsampling filter to use (http://www.pythonware.com/library/pil/
> handbook/image.htm). The default is Image.NEAREST, which just samples
> the nearest pixel and results in the type of data loss you are seeing.
> If you want something better try one of the following and see which
> works best for you: Image.BILINEAR, Image.BICUBIC or Image.ANTIALIAS.
>
> example:
> ...
>newimg = img.resize((int(wd),int(ht)),Image.ANTIALIAS)
> ...
>
> Matt

Thank you! The ANTIALIAS filter works great. With any of the others, I still 
lost my reference lines.
--Tim


-- 
http://mail.python.org/mailman/listinfo/python-list


deepcopy debugging

2007-10-19 Thread Robin Becker
I'm using deepcopy in some code which eventually ends up by crash witht he 
following rather long winded error. I'm not directly using _hashlib.HASH, but I 
suppose something else along the way could be. Is there some nice way to make 
copy/deepcopy give more information when this error happens? I know what the 
top 
level object is, but presumably it's something further down that's causing the 
problem.

.

   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 291, in _deepcopy_inst
 state = deepcopy(state, memo)
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 254, in _deepcopy_dict
 y[deepcopy(key, memo)] = deepcopy(value, memo)
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 234, in _deepcopy_tuple
 y.append(deepcopy(a, memo))
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 227, in _deepcopy_list
 y.append(deepcopy(a, memo))
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 291, in _deepcopy_inst
 state = deepcopy(state, memo)
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 254, in _deepcopy_dict
 y[deepcopy(key, memo)] = deepcopy(value, memo)
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 234, in _deepcopy_tuple
 y.append(deepcopy(a, memo))
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 234, in _deepcopy_tuple
 y.append(deepcopy(a, memo))
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 291, in _deepcopy_inst
 state = deepcopy(state, memo)
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 254, in _deepcopy_dict
 y[deepcopy(key, memo)] = deepcopy(value, memo)
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 291, in _deepcopy_inst
 state = deepcopy(state, memo)
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 254, in _deepcopy_dict
 y[deepcopy(key, memo)] = deepcopy(value, memo)
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 291, in _deepcopy_inst
 state = deepcopy(state, memo)
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 254, in _deepcopy_dict
 y[deepcopy(key, memo)] = deepcopy(value, memo)
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 291, in _deepcopy_inst
 state = deepcopy(state, memo)
   File "C:\Python\lib\copy.py", line 162, in deepcopy
 y = copier(x, memo)
   File "C:\Python\lib\copy.py", line 254, in _deepcopy_dict
 y[deepcopy(key, memo)] = deepcopy(value, memo)
   File "C:\Python\lib\copy.py", line 189, in deepcopy
 y = _reconstruct(x, rv, 1, memo)
   File "C:\Python\lib\copy.py", line 322, in _reconstruct
 y = callable(*args)
   File "C:\Python\lib\copy_reg.py", line 92, in __newobj__
 return cls.__new__(cls, *args)
TypeError: object.__new__(_hashlib.HASH) is not safe, use 
_hashlib.HASH.__new__()
-- 
Robin Becker

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to iterate over sequence and non-sequence ?

2007-10-19 Thread stef
Paul Hankin wrote:
> On Oct 19, 12:24 am, stef mientki <[EMAIL PROTECTED]> wrote:
>   
>> I generate dynamically a sequence of values,
>> but this "sequence" could also have length 1 or even length 0.
>>
>> So I get some line in the form of:
>>   line = '(2,3,4)'
>>   line = ''
>>   line = '(2)'
>> (in fact these are not constant numbers, but all kind of integer
>> variables, coming from all over the program, selected from a tree, that
>> shows all "reachable" variables)
>>
>> So in fact I get the value from an exec statement, like this
>>   exec 'signals = ' + line
>>
>> Now I want to iterate over "signals", which works perfect if there are 2
>> or more signals,
>> but it fails when I have none or just 1 signal.
>> for value in signals :
>> do something
>>
>> As this meant for real-time signals, I want it fast, so (I think) I
>> can't afford extensive testing.
>>
>> Any smart solution there ?
>> 
>
> First: don't collect data into strings - python has many container
> types which you can use.
>   
Well I'm not collecting data, I'm collecting pointers to data.
This program simulates a user written program in JAL.
As Python doesn't support pointers, instead I collect names.
The names are derived from an analysis of the user program under test,
so the danger some of you are referring to, is not there,
or at least is not that simple.
Besides it's a local application where the goal is to let a user test 
his program (and hardware),
so if the user want to hack, he can better type directly "format c:\".

> Next, your strings look like they're supposed to contain tuples. In
> fact, tuples are a bit awkward sometimes because you have to use
> '(a,') for a tuple with one element - (2) isn't a tuple of length one,
> it's the same as 2. Either cope with this special case, or use lists.
> Either way, you'll have to use () or [] for an empty sequence.
>   
Of course, thanks Paul,
if I change tuple to list, everything works ok, even with empty lists.

cheers,
Stef Mientki
> --
> Paul Hankin
>
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Noob questions about Python

2007-10-19 Thread Grant Edwards
On 2007-10-19, Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
> "Arnaud Delobelle"  wrote:
>
>> In binary 2 is 10.  When you multiply by 10, you shift all your digits
>> left by 1 place.
>> When you multiply by 10**n (which is 1 followed by n zeroes), you
>> shift all your digits left by n places.
>
> I read somewhere:
>
> Only 1 person in 1000 understands binary.
> The other 111 don't have a clue.

There are only 10 kinds of people: those who understand binary
and those who don't.

-- 
Grant Edwards   grante Yow! Will this never-ending
  at   series of PLEASURABLE
   visi.comEVENTS never cease?
-- 
http://mail.python.org/mailman/listinfo/python-list


write whitespace/tab to a text file

2007-10-19 Thread dirkheld
Hi,

I would l like to write some data to a text file. I want to write the
data with whitespace or tabs in between so that I create tabular
columns like in a spreadsheet. How can I do this in python.
(btw, I'm new to python)

names = ['John','Steve','asimov','fred','jim']
## output I would like in txt file : John Steve
asimov  fred jim

f=open('/User/home/Documents/programming/python/test.txt','w')
for x in range(len(names)):
f.write(tags[x])
f.close()

-- 
http://mail.python.org/mailman/listinfo/python-list


How to use module audit-lib ?

2007-10-19 Thread Sébastien Weber
Hello,

I've installed the python-audit-lib module but there's no documentation.
Does someone know how to use it ?

Thank's in advance,

SW
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What Data is Available With a Pickled Object Over a Socket?

2007-10-19 Thread Lawrence Oluyede
milan_sanremo <[EMAIL PROTECTED]> wrote:
> I've read the library entry for pickle a couple of times, and I'm
> still not
> sure what data is maintained when an item is pickled and sent over a
> socket.

I would not do that if I were you:


Unless you don't care about security

-- 
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand 
something when his salary depends on not
understanding it" - Upton Sinclair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: write whitespace/tab to a text file

2007-10-19 Thread Grant Edwards
On 2007-10-19, marc wyburn <[EMAIL PROTECTED]> wrote:

>> I would l like to write some data to a text file. I want to write the
>> data with whitespace or tabs in between so that I create tabular
>> columns like in a spreadsheet. How can I do this in python.
>> (btw, I'm new to python)
>>
>> names = ['John','Steve','asimov','fred','jim']
>> ## output I would like in txt file : John Steve
>> asimov  fred jim
>>
>> f=open('/User/home/Documents/programming/python/test.txt','w')
>> for x in range(len(names)):
>> f.write(tags[x])
>> f.close()
>
> I'm not sure exactly but you'll probably need to find out what the
> ASCII code is for a tab.

You don't need to know the ASCII code.  Just use "\t":

print "%s\t%s\t%s" % (1,"two",3)

If you fixed column spacing with spaces instead of tabs:

print "%-8s%-8s%-8s" % (1,"two",3)

-- 
Grant Edwards   grante Yow! HAIR TONICS, please!!
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to tell if a script has been run by Pythonw.exe instead of Python.exe?

2007-10-19 Thread Metalone
Thanks to all, I learned something in each post.
When using py2exe to build an executable sys.executable does not
provide the name of the python interpreter but the name of the
executable generated by py2exe.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DIAGNOSIS: Racism moves back to Denmark from South Africa

2007-10-19 Thread mich

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> INCISIVE ANALYSIS: The dismantlement of Apartheid Regime in South
> Africa sent the racist Dutch Afrikaners back to Denmark where they are
> spreading their racist ideology -- The Apartheid "Christianity" :


The Dutch went back to Denmark? 


-- 
http://mail.python.org/mailman/listinfo/python-list


Using Python with SciTE editor

2007-10-19 Thread bobmon
Hello,

I have a problem running Python programs from within SciTE, under
Linux --- the input( ) function fails with

"IOError: [Errno 9] Bad file descriptor"

The same program will run happily in SciTE, under Windows --- gets the
input, goes off and calculates wondrous things --- but somehow, in
Linux, I'm not set up right.

This is true using Fedora Core, and Kunbuntu (KDE in both cases, if
that matters).

I'm guessing that I need to fix one of my ".properties" configuration
files, but I have no idea what to fix.

Please help -  please, please, pleasepleasePleasePLEASEPLEASE

-bob,mon!

p.s. I know I've seen this delat with somewhere, but I can't find it.
Any help will be GREATLY appreciated!  TIA.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use module audit-lib ?

2007-10-19 Thread Sébastien Weber
Le Fri, 19 Oct 2007 21:49:59 +0200, Jarek Zgoda a écrit :

> Sébastien Weber napisał(a):
> 
>> I've installed the python-audit-lib module but there's no
>> documentation. Does someone know how to use it ?
> 
> I don't know this package, but why did you install it? Maybe somebody in
> Überwald knows its usage?

Hello,
I've installed it to monitor some file's use : who/what makes what on a 
file ? It's a wrapper for the audit fonction which is new in the kernel 
2.6 and which allows you to know how a file is used by who. A command-
line utility named "auditctl" exists, but I want something written in 
Python - to make an simple end-user application.
It seems like nobody has ever written smoething with that module... 

(Sorry for my english, I'm french).

SW
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Problem with format string / MySQL cursor

2007-10-19 Thread Gabriel Genellina
En Fri, 19 Oct 2007 05:32:04 -0300, Dennis Lee Bieber  
<[EMAIL PROTECTED]> escribió:

> On Thu, 18 Oct 2007 13:40:53 -0700, Florian Lindner
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:

>> That works! Thanks! But a weird error message for this solution...
>
>   Not really... The MySQLdb adapter converts all parameters to
> properly delimited STRINGS (I don't know of any SQL system that passes
> /binary/ numerics). But MySQLdb also uses Python % formatting to then

I'd say the opposite: only poorly implemented systems convert numeric  
arguments to text.
*Real* bound variables are passed as pointers. The SQL sentence can be  
prepared and re-used with different sets of values several times, without  
having to re-parse it again and again.
If the MySQLdb adapter actually converts and inserts the arguments itself  
into the supplied SQL sentence, generating a new string for each call,  
this advantage -and many others- are cancelled, defeating the purpose of  
bound variables.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ConfigParser preserving file ordering

2007-10-19 Thread Gabriel Genellina
En Fri, 19 Oct 2007 10:16:00 -0300, Andrew Durdin <[EMAIL PROTECTED]>  
escribió:

> As for updating ConfigParser -- like most other changes, it probably
> needs a champion.

ConfigParser is so dumb that should be burned to death and rebuilt from  
the ashes.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python script for mobile platforms -- suggested?

2007-10-19 Thread Robert Dailey
On 8/14/07, Jay Loden <[EMAIL PROTECTED]> wrote:
>
> XML is first and foremost a machine-parseable language, and a human-readable 
> one second ;) I don't think this is particularly hard to read, but then I 
> work with XML configuration files on a daily basis at work, so I may just be 
> a terrible person to ask...
>
> I'm not sure I agree that you're not using XML as it was intended; you're 
> mixing data and presentation, but it's still a document containing data. 
> That's what XHTML is, and what the XML document definitions like OOXML are 
> all about. Anyway, that's neither here nor there. My question would be a much 
> simpler "why is this XML?".
>
> XML makes sense when you need a structured document, and sometimes that makes 
> sense for configuration options or defining a structure, but it's not clear 
> why you'd need it here. Is this something you're intending to make editable 
> by the end user? If you're willing to replace it with Python scripts instead 
> of XML documents, it sounds like maybe you're not worried about letting users 
> edit the menus. If so, why not code the menus direct into the main C++ code? 
> This would be faster, unless you need to frequently edit these menus.
>
> I think the best thing to do would be to take a step back and ask what it is 
> that you're trying to do as the end result. What are your requirements; can 
> you expect that Python will be installed already? Is the choice between 
> parsing XML once with C++ or having to ship a Python interpreter with 
> associated overhead? Once you have a set of requirements and determine what's 
> most important to you it should make it easier to pick a solution. For 
> instance, on a mobile device, you might simply not have the spare cycles that 
> embedding a python interpreter would require versus a lightweight lib like 
> TinyXML. Similarly, you'd have to ask yourself if the data is always static, 
> or if you have a need for dynamic content (i.e. embedded scripting) within 
> the menu definition.
>
> -Jay
>

Well, Ideally the python script would have a series of callback
methods that are triggered when specific predefined events occur in
that menu. For example, when the user presses the LEFT key, a callback
should be executed in the python script to perform various tasks. So
you'd do something like:

def OnKeyLeft():
# Do something here...
pass

However, I think the root of the problem is that I'm editing text
files directly to modify the look and feel of menus. Ideally, I'd have
a tool that allows a user to visually create a menu by interactively
creating controls and assigning them properties through a GUI
interface. However, in my specific case I was unable to make a tool
due to time restrictions.

I could, at the very least, use wxPython to make this tool, which
would output menu definitions in XML (which will be non-human readable
or editable), or perhaps even binary for quicker parsing by the game.
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem with shelve/gdbm

2007-10-19 Thread Douglas Applegate
Hi-

I am having a problem with shelve. The problem I think is really with  
gdbm. I'll write out a file using shelve/gdbm on an amd64 machine and  
then I'll try to read it in on a i386 machine. The result is a 'gdbm  
fatal: read error.' Reversing directions results in the same problem.  
Below are two small programs that get at the heart of the problem:

#test.py##
#!/usr/bin/env python
import gdbm
print gdbm
storage = gdbm.open('test.pstor', 'c')

storage['test'] = 'a'

storage.close()


#test2.py#
#!/usr/bin/env python
import gdbm
print gdbm
storage = gdbm.open('test.pstor', 'r')

print storage['test']

storage.close()

#
The result of running test2 is as follows:


Traceback (most recent call last):
   File "./test2.py", line 4, in 
 storage = gdbm.open('test.pstor', 'r')
gdbm fatal: read error



It isn't much to go on, but has anybody else had this problem?


Cheers,
Doug
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange behaviour with reversed()

2007-10-19 Thread Duncan Booth
Andreas Kraemer <[EMAIL PROTECTED]> wrote:

>> The only other behaviours I would regard as intuitive for iteration over
>> a mutating sequence would be to throw an exception either for mutating
>> the sequence while the iterator exists or for using the iterator after a
>> mutation.
> 
> Maybe it would have been slightly more intuitive if reversed() had
> been implemented like this,
> 
> def Reversed(seq):
>   for i in xrange(len(seq)-1,-1,-1):
> yield seq[i]
> 
> so that the length of the sequence is determined when the iteration
> starts, not when the iterator is created?

Perhaps, but either way it comes down to "don't modify the sequence while 
iterating".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class vs type

2007-10-19 Thread Gabriel Genellina
En Fri, 19 Oct 2007 20:14:03 -0300, Colin J. Williams <[EMAIL PROTECTED]>  
escribió:

> The Python 3.0 doc, under Class, has:

> Programmer’s note: Variables defined in [...]
> For new-style classes, descriptors can
> be used to create instance variables
> with different implementation details.
>
> Presumably, it is intended that every
> class implicitly inherits from object?

For Python 3.0, yes. Where did you read the above text? The 3.0 docs at
http://docs.python.org/dev/3.0/reference/compound_stmts.html#class-definitions
are already updated and don't menction "new-style classes" at all.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Last iteration?

2007-10-19 Thread Gabriel Genellina
En Fri, 19 Oct 2007 19:12:49 -0300, Michael J. Fromberger  
<[EMAIL PROTECTED]> escribió:

> Before I affront you with implementation details, here's an example:
>
> | from __future__ import with_statement
>
> | with last_of(enumerate(file('/etc/passwd', 'rU'))) as fp:
> | for pos, line in fp:
> | if fp.marked():
> | print "Last line, #%d = %s" % (pos + 1, line.strip())
>
> In short, last_of comprises a trivial context manager that knows how to
> iterate over its input, and can also indicate that certain elements are
> "marked".  In this case, only the last element is marked.

The name is very unfortunate. I'd expect that last_of(something) would  
return its last element, not an iterator.
Even with a different name, I don't like that marked() (a method of the  
iterator) should be related to the current element being iterated.

> We could also make the truth value of the context manager indicate the
> marking, as illustrated here:
>
> | with last_of("alphabet soup") as final:
> | for c in final:
> | if final:
> | print "Last character: %s" % c
>
> This is bit artificial, perhaps, but effective enough.  Of course, there

Again, why should the trueness of final be related to the current element  
being iterated?

> is really no reason you have to use "with," since we don't really care
> what happens when the object goes out of scope:  You could just as
> easily write:
>
> | end = last_of(xrange(25))
> | for x in end:
> |   if end:
> | print "Last element: %s" % x

Again, why the truth value of "end" is related to the current "x" element?

> But you could also handle nested context, using "with".  Happily, the
> machinery to do all this is both simple and easily generalized to other
> sorts of "marking" tasks.  For example, we could just as well do
> something special with all the elements that are accepted by a predicate
> function, e.g.,
>
> | def isinteger(obj):
> | return isinstance(obj, (int, long))
>
> | with matching(["a", 1, "b", 2, "c"], isinteger) as m:
> | for elt in m:
> | if m.marked():
> | print '#%s' % elt,
> | else:
> | print '(%s)' % elt,
> |
> | print

I think you are abusing context managers *a*lot*!
Even accepting such evil thing as matching(...), the above code could be  
equally written as:

m = matching(...)
for elt in m:
   ...

Anyway, a simple generator that yields (elt, function(elt)) would be  
enough...

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


SQLObject - Connect to established DB with non-int 'id' field

2007-10-19 Thread Sean DiZazzo
Hi all,

I am just beginning with TurboGears and have run into a problem with
SQLObject.

I'm trying to connect to an established mysql DB, and use TurboGears
to display results from the DB only.  The problem is that the DB
already has an 'id' field that is a string as opposed to an int.
SQLObject complains because it wants to use the id field for it's own
purposes.

How can I use TurboGears to get data out of this DB?

Thanks in advance.

~Sean

-- 
http://mail.python.org/mailman/listinfo/python-list


More friends more money,get friends while get paid

2007-10-19 Thread my god
More friends more money,get friends while get paid
http://groups.google.com/group/all-good-things/web/get-friends-while-get-paid

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __main__ : What is this?

2007-10-19 Thread Massimo Di Pierro
if the .py file is imported as a module that condition is false else
(if the .py file is executed) that condition is true

On Oct 19, 2007, at 6:29 PM, Robert Dailey wrote:

> Hi,
>
> I've read various portions of the Python 2.5 documentation in an
> attempt to figure out exactly what the following condition represents:
>
> if __name__ == "__main__":
> main()
>
> However, I was not able to determine what it is actually checking for.
> Could someone point me in the way of a tutorial or explain this for
> me? Thanks.
> --
> http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


__main__ : What is this?

2007-10-19 Thread Robert Dailey
Hi,

I've read various portions of the Python 2.5 documentation in an
attempt to figure out exactly what the following condition represents:

if __name__ == "__main__":
main()

However, I was not able to determine what it is actually checking for.
Could someone point me in the way of a tutorial or explain this for
me? Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class vs type

2007-10-19 Thread Colin J. Williams
Terry Reedy wrote:
> "Colin J. Williams" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> | Doesn't Python 3 provide an opportunity
> | to move away from discussions about
> | new_style vs old-style?  This an
> | opportunity to treat old-style as a
> | historical artefact, not requiring
> | current explanation.
> 
> Yes, there will not be 'old-style' classes in Py3 and 3.0 doc will not 
> mention them..  But we are actually at 2.5 and there will be 2.6, 2.7, 2.8? 
> that still have them. 
> 
> 
> 
Terry,

Thanks for clarifying the intent.

The Python 3.0 doc, under Class, has:
Programmer’s note: Variables defined in 
the class definition are class 
variables; they are shared by all 
instances. To define instance variables, 
they must be given a value in the 
__init__() method or in another method. 
Both class and instance variables are 
accessible through the notation 
“self.name“, and an instance variable 
hides a class variable with the same 
name when accessed in this way. Class 
variables with immutable values can be 
used as defaults for instance variables. 
For new-style classes, descriptors can 
be used to create instance variables 
with different implementation details.

Presumably, it is intended that every 
class implicitly inherits from object?

Colin W.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DIAGNOSIS: Racism moves back to Denmark from South Africa

2007-10-19 Thread Jarek Zgoda
mich napisał(a):

>> INCISIVE ANALYSIS: The dismantlement of Apartheid Regime in South
>> Africa sent the racist Dutch Afrikaners back to Denmark where they are
>> spreading their racist ideology -- The Apartheid "Christianity" :
> 
> The Dutch went back to Denmark? 

Let them thank God they didn't sent Poles there. The rivers would flow
with blood. Leaving blood flowing is their well-known national sport.

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running another python interpreter

2007-10-19 Thread Gabriel Genellina

--- Simon Pickles <[EMAIL PROTECTED]> escribió:

> os.spawnl(os.P_NOWAIT, sys.executable,
> sys.executable, "gateway.py")
>... works but both process output to the same
> interpreter window. Is there a way to run another
> interpreter window containing gateway.py?

Use the subprocess module, passing CREATE_NEW_CONSOLE into creationflags:

subprocess.call([sys.executable, "gateway.py", "other", "arguments"],
 creationflags = subprocess.CREATE_NEW_CONSOLE)

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Pyrex 0.9.6.3

2007-10-19 Thread Greg Ewing
[EMAIL PROTECTED] wrote:

> Also, I noticed that if I try to download the testing framework, it
> gives me a 404.

That one is fixed now, if you want to try again.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C++ version of the C Python API?

2007-10-19 Thread Joe Riopel
On 10/19/07, Robert Dailey <[EMAIL PROTECTED]> wrote:
> Is there a C++ version of the C Python API packaged with python 2.5?
> It would be nice to have a OOP approach to embedding python in C++. It
> would also be a bonus if this C++ Python API cleaned up a lot of the
> messy code involved in embedding python.

C++ is object orientated? I heard it was, but I don't buy it.
-- 
http://mail.python.org/mailman/listinfo/python-list


where do I need to "tab"?

2007-10-19 Thread [EMAIL PROTECTED]
hi

I'm following the python's translation of SICP:
http://codepoetics.com/wiki/index.php?title=Topics:SICP_in_other_languages:Python:Chapter_1
...
a = 3
b = a + 1
print a + b + (a * b)
print (a == b)
print b if ((b > a) and (b < (a * b))) else a

everything was fine till this point, and I got:
print b if ((b > a) and (b < (a * b))) else a
 ^
SyntaxError: invalid syntax

Is there a good rule that I quickly memorize as to "when to tab"?
Thanks.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __main__ : What is this?

2007-10-19 Thread Gabriel Genellina
En Fri, 19 Oct 2007 21:26:22 -0300, Matimus <[EMAIL PROTECTED]> escribió:

> The common pattern:
>
> if __name__ == "__main__":
>   # do stuff
>
> IMHO better written:
>
> if "__main__" == __name__:
> # do stuff

I'm intrigued why do you feel the second alternative is better.
Which is your native language? In English (and Spanish, and many others  
but still not in the majority) the usual ordering is "subject-verb-object"  
or SVO, which matches the first alternative: "If the name is __main__, do  
this..."
As all the languages I know (not so many!) are SVO, I can't think of any  
equivalent of the second form [that I could say it's better than the first]

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where do I need to "tab"?

2007-10-19 Thread Basilisk96
Tab is not the issue here. By my powers of deduction, I can see that
you are running this code in Python version previous to 2.5, because
the construct "true_clause if condition else false_clause" did not
exist until 2.5. It's a neat little construct, I highly recommend you
upgrade now :)

-Basilisk96

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __main__ : What is this?

2007-10-19 Thread Gabriel Genellina
En Fri, 19 Oct 2007 20:29:03 -0300, Robert Dailey <[EMAIL PROTECTED]>  
escribió:

> I've read various portions of the Python 2.5 documentation in an
> attempt to figure out exactly what the following condition represents:
>
> if __name__ == "__main__":
> main()
>
> However, I was not able to determine what it is actually checking for.
> Could someone point me in the way of a tutorial or explain this for
> me? Thanks.

You won't find it (easily) on the 2.5 docs, but it's covered in the  
upcoming 2.6 tutorial:
http://docs.python.org/dev/tutorial/modules.html#executing-modules-as-scripts

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __main__ : What is this?

2007-10-19 Thread Matimus
> I've read various portions of the Python 2.5 documentation in an
> attempt to figure out exactly what the following condition represents:
>
> if __name__ == "__main__":
> main()
>
> However, I was not able to determine what it is actually checking for.
> Could someone point me in the way of a tutorial or explain this for
> me? Thanks.

__name__ is an attribute on a module that shows the standard name for
that module:

>>> import sys
>>> sys.__name__
'sys'

The name stays constant even if you do something funny during import:

>>> import os as something_else
>>> something_else.__name__
'os'

When using the interpreter or running a python script code will be
executed in a standard module called "__main__".

>>> __name__
'__main__'

In fact, you can even import __main__ if you want:

>>> import __main__
>>> __main__.__name__
'__main__'
>>> a = 100
>>> __main__.a
100

The common pattern:

if __name__ == "__main__":
  # do stuff

IMHO better written:

if "__main__" == __name__:
# do stuff

Allows a module to selectively run code only if it is being run as a
program. That code will not run if it is imported as a module, because
in that condition __name__ will return the name of the file (sans .py)
that the code is in. I've never tried naming a file __main__.py and
importing it, my guess is that you shouldn't do that :).

Matt

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __main__ : What is this?

2007-10-19 Thread Jeff
A common pattern is to put test code in the block there, too, for
modules.

Re comparison ordering, perhaps it's as in PHP, where string literals
should always go before a variable in a comparison in case evaluating
the variable causes an error :)

Mas, ese orden nunca uso yo ;).

On Oct 19, 10:25 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Fri, 19 Oct 2007 21:26:22 -0300, Matimus <[EMAIL PROTECTED]> escribió:
>
> > The common pattern:
>
> > if __name__ == "__main__":
> >   # do stuff
>
> > IMHO better written:
>
> > if "__main__" == __name__:
> > # do stuff
>
> I'm intrigued why do you feel the second alternative is better.
> Which is your native language? In English (and Spanish, and many others  
> but still not in the majority) the usual ordering is "subject-verb-object"  
> or SVO, which matches the first alternative: "If the name is __main__, do  
> this..."
> As all the languages I know (not so many!) are SVO, I can't think of any  
> equivalent of the second form [that I could say it's better than the first]
>
> --
> Gabriel Genellina


-- 
http://mail.python.org/mailman/listinfo/python-list

Distributed RVS, Darcs, tech love

2007-10-19 Thread Xah Lee
When i first heard about distributed revision control system about 2
years ago, i heard of Darcs, which is written in Haskell. I was hugely
excited, thinking about the functional programing i love, and the no-
side effect pure system i idolize, and the technology of human animal
i rapture in daily.

I have no serious actual need to use a revision system (RVS) in recent
years, so i never really tried Darcs (nor using any RVS). I just
thought the new-fangled distributed tech in combination of Haskell was
great.

About few months ago, i was updating a 6-year old page i wrote on unix
tools: ( http://xahlee.org/UnixResource_dir/usoft.html ) and i was
trying to update myself on the current state of art of revision
systems. I read Wikipedia this passage:

http://en.wikipedia.org/wiki/Darcs

« Darcs currently has a number of significant bugs (see e.g. [1]). The
most severe of them is "the Conflict bug" - an exponential blowup in
time needed to perform conflict resolution during merges, reaching
into the hours and days for "large" repositories. A redesign of the
repository format and wide-ranging changes in the codebase are planned
in order to fix this bug, and work on this is planned to start in
Spring 2007 [2].  »

This somewhat bursted my bubble, as there always was some doubt in the
back of my mind about just how Darcs is not just a fantasy-ware
trumpeted by a bunch of functional tech geekers. (i heard of Darcs in
irc emacs and haskell channels, who are often student and hobbiests
programers)

Also, in my light research, it was to my surprise, that Darcs is not
the only distributed systems, and perhaps not the first one neither,
contrary to my impressions. In fact, today there are quite a LOT
distributed revision systems, actually as a norm. When one looks into
these, such as Git ( http://en.wikipedia.org/wiki/Git_(software) ) one
finds that some of them are already in practical industrial use for
large projects, as opposed to Darcs's academic/hobbist kind of
community.

In addition to these findings, one additional that greatly pissed me
off entirely about Darcs, is the intro of the author (David Roundy)'s
essay about his (questionable-sounding) “theory of patches” used in
Darcs. ( http://darcs.net/manual/node8.html#Patch )

Here's the 2 passages:

«I think a little background on the author is in order. I am a
physicist, and think like a physicist. The proofs and theorems given
here are what I would call ``physicist'' proofs and theorems, which is
to say that while the proofs may not be rigorous, they are practical,
and the theorems are intended to give physical insight. It would be
great to have a mathematician work on this, but I am not a
mathematician, and don't care for math.»

«From the beginning of this theory, which originated as the result of
a series of email discussions with Tom Lord, I have looked at patches
as being analogous to the operators of quantum mechanics. I include in
this appendix footnotes explaining the theory of patches in terms of
the theory of quantum mechanics. I know that for most people this
won't help at all, but many of my friends (and as I write this all
three of darcs' users) are physicists, and this will be helpful to
them. To non-physicists, perhaps it will provide some insight into how
at least this physicist thinks.»

I love math. I respect Math. I'm nothing but a menial servant to
Mathematics. Who the fuck is this David guy, who proclaims that he's
no mathematician, then proceed to tell us he dosen't fucking care
about math? Then, he went on about HIS personal fucking zeal for
physics, in particular injecting the highly quacky “quantum mechanics”
with impunity.

  Xah
  [EMAIL PROTECTED]
∑ http://xahlee.org/

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Noob: Loops and the 'else' construct

2007-10-19 Thread MRAB
On Oct 19, 4:11 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus <[EMAIL PROTECTED]>
> escribió:
>
> > I have just come across a site that discusses Python's 'for' and
> > 'while' loops as having an (optional) 'else' structure.
>
> > At first glance I interpreted it as being a bit like the 'default'
> > structure in PHP's switch block... But the switch block isn't a loop,
> > so, I am now confused as to the reason for using 'else' with the for
> > and while loops...
>
> > A few quick tests basically show that statements in the else structure
> > are executed at the fulfillment of the loop's expression (ie, no
> > break).
>
> A `while` loop tests a condition: if it evaluates to true, keep cycling;
> if it is false, stop. The `else` clause is executed when the condition is
> false, as in any `if` statement. If you exit the loop by using `break`,
> the `else` part is not executed (because you didn't get out of the loop by
> determining the condition falseness)
>
> You can think of a `for` loop as meaning `while there are remaining
> elements to be iterated, keep cycling` and the `else` clause applies when
> there are no more elements. A `break` statement does not trigger the else
> clause because the iteration was not exhausted.
>
> Once you get the idea, it's very simple.
>
It's useful when you want to search for an item and to do something if
you don't find it, eg:

for i in items:
if is_wanted(i):
print "Found it"
break
else:
print "Didn't find ir"

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: where do I need to "tab"?

2007-10-19 Thread Gabriel Genellina
En Fri, 19 Oct 2007 23:24:30 -0300, Scott David Daniels  
<[EMAIL PROTECTED]> escribió:

> [EMAIL PROTECTED] wrote:
>> I'm following the python's translation of SICP:
>> http://codepoetics.com/wiki/index.php?title=Topics:SICP_in_other_languages:Python:Chapter_1
>> ...
> OK, you have a mix of Python 3,0 and current (2.5.1) Python.

All examples are OK for 2.5

>> a = 3
>> b = a + 1
> Fine in all
>> print a + b + (a * b)
> Fine in all but 3.0
> For 3.0, print becomes a function:
>  print(a + b + (a * b))
>> print (a == b)
> Fine in all
>> print b if ((b > a) and (b < (a * b))) else a
> Fine in 2.6, which isn't really out yet.

And in 2.5 too, like all the other examples. I wouldn't menction 3.0 yet.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: traceback over C API and PyObject_CallObject

2007-10-19 Thread Gabriel Genellina
En Fri, 19 Oct 2007 13:53:03 -0300, Sami Vaisanen <[EMAIL PROTECTED]>  
escribió:

> Hello group,
>
> I'm trying to get the Python exception information (message and  
> traceback)
> stored into a string in my C++ code. However all i get back is the string
> "None".

This is what you get (actually "None\n") when there is no error set.

> All the checks pass and all pointers get a value from the python
> API calls. I've also tried with a different function such as
> PyObject_CallFunctionObjArgs but the result is the same.

Since you already know the three components (type, value, trace), I'd use  
traceback.format_exception instead (and remove the PyErr_Restore call -  
I'm unsure if it works the way you expect it).
In this case you have to pass three arguments, so yes, use  
PyObject_CallFunctionObjArgs (remember the final NULL). Beware:  
format_exception returns a formatted list, not a string. You have to  
concatenate all the elements (either using ''.join or repeteadly calling  
PyString_Concat)

> void get_python_exception(string& message, string& traceback)
> {
> GIL g;
>PyObject* type  = NULL;
> PyObject* value = NULL;
> PyObject* trace = NULL;
>PyErr_Fetch(&type, &value, &trace);
>py_ref ref_type(type);
> py_ref ref_value(value);
> py_ref ref_trace(trace);
>py_ref name(PyString_FromString("traceback"));
> py_ref module(PyImport_Import(name.get()));
> if (module)
> {
> py_ref fun(PyObject_GetAttrString(module.get(), "format_exc"));
> if (fun)
> {
> PyErr_Restore(type, value, trace);
> ref_type.release();
> ref_value.release();
> ref_trace.release();
>py_ref ret(PyObject_CallObject(fun.get(), NULL));
> if (ret && PyString_Check(ret.get()))
> {
> char* str = PyString_AsString(ret.get());
> message = str;
> traceback = "traceback not available";
> return;
> }
> }
> }
> message   = "message not available";
> traceback = "traceback not available";
> }




-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Last iteration?

2007-10-19 Thread Michael J. Fromberger
In article <[EMAIL PROTECTED]>,
 Raymond Hettinger <[EMAIL PROTECTED]> wrote:

> [Diez B. Roggisch]
> > > out:) But I wanted a general purpose based solution to be available that
> > > doesn't count on len() working on an arbitrary iterable.
> 
> [Peter Otten]
> > You show signs of a severe case of morbus itertools.
> > I, too, am affected and have not yet fully recovered...
> 
> Maybe you guys were secretly yearning for a magical last element
> detector used like this: [...]


Although there have already been some nice solutions to this problem, 
but I'd like to propose another, which mildly abuses some of the newer 
features of Python  It is perhaps not as concise as the previous 
solutions, nor do I claim it's better; but I thought I'd share it as an 
alternative approach.

Before I affront you with implementation details, here's an example:

| from __future__ import with_statement

| with last_of(enumerate(file('/etc/passwd', 'rU'))) as fp:
| for pos, line in fp:
| if fp.marked():
| print "Last line, #%d = %s" % (pos + 1, line.strip())

In short, last_of comprises a trivial context manager that knows how to 
iterate over its input, and can also indicate that certain elements are 
"marked".  In this case, only the last element is marked.

We could also make the truth value of the context manager indicate the 
marking, as illustrated here:

| with last_of("alphabet soup") as final:
| for c in final:
| if final:
| print "Last character: %s" % c

This is bit artificial, perhaps, but effective enough.  Of course, there 
is really no reason you have to use "with," since we don't really care 
what happens when the object goes out of scope:  You could just as 
easily write:

| end = last_of(xrange(25))
| for x in end:
|   if end:
| print "Last element: %s" % x

But you could also handle nested context, using "with".  Happily, the 
machinery to do all this is both simple and easily generalized to other 
sorts of "marking" tasks.  For example, we could just as well do 
something special with all the elements that are accepted by a predicate 
function, e.g.,

| def isinteger(obj):
| return isinstance(obj, (int, long))

| with matching(["a", 1, "b", 2, "c"], isinteger) as m:
| for elt in m:
| if m.marked():
| print '#%s' % elt,
| else:
| print '(%s)' % elt,
|
| print

Now that you've seen the examples, here is an implementation.  The 
"marker" class is an abstract base that does most of the work, with the 
"last_of" and "matching" examples implemented as subclasses:

| class marker (object):
| """Generate a trivial context manager that flags certain elements
| in a sequence or iterable.
| 
| Usage sample:
|   with marker(ITERABLE) as foo:
| for elt in foo:
|   if foo.marked():
|  print 'this is a marked element'
|   else:
|  print 'this is an unmarked element'
| 
| Subclass overrides:
|  .next()   -- return the next unconsumed element from the input.
|  .marked() -- return True iff the last element returned is marked.
| 
| By default, no elements are marked.
| """
| def __init__(self, seq):
| self._seq = iter(seq)
| try:
| self._fst = self._seq.next()
| except StopIteration:
| self.next = self._empty
| 
| def _empty(self):
| raise StopIteration
| 
| def _iter(self):
| while True:
| yield self.next()
| 
| def next(self):
| out = self._fst
| try:
| self._fst = self._seq.next()
| except StopIteration:
| self.next = self._empty
| 
| return out
| 
| def marked(self):
| return False
| 
| def __iter__(self):
| return iter(self._iter())
| 
| def __nonzero__(self):
| return self.marked()
| 
| def __enter__(self):
| return self
| 
| def __exit__(self, *args):
| pass

A bit verbose, but uncomplicated apart from the subtlety in handling the 
end case.  Here's last_of, implemented as a subclass:

| class last_of (marker):
| def __init__(self, seq):
| super(last_of, self).__init__(seq)
| self._end = False
| 
| def next(self):
| out = super(last_of, self).next()
| if self.next == self._empty:
| self._end = True
| 
| return out
| 
| def marked(self):
| return self._end

And finally, matching:

| class matching (marker):
| def __init__(self, seq, func):
| super(matching, self).__init__(seq)
| self._func = func
| self._mark = False
| 
| def next(self):
| out = super(matching, self).next()
| self._mark = self._func(out)
| return out
| 
| def marked(self):
| return self._mark

Generally speaking, you should only have to override .next() and 
.marked() to make a useful subclass of mark

Re: Distributed RVS, Darcs, tech love

2007-10-19 Thread Byung-Hee HWANG
On Fri, 2007-10-19 at 20:28 -0700, Xah Lee wrote:
> When i first heard about distributed revision control system about 2
> years ago, i heard of Darcs, which is written in Haskell. I was hugely
> excited, thinking about the functional programing i love, and the no-
> side effect pure system i idolize, and the technology of human animal
> i rapture in daily.
> 
> I have no serious actual need to use a revision system (RVS) in recent
> years, so i never really tried Darcs (nor using any RVS). I just
> thought the new-fangled distributed tech in combination of Haskell was
> great.
> 
> About few months ago, i was updating a 6-year old page i wrote on unix
> tools: ( http://xahlee.org/UnixResource_dir/usoft.html ) and i was
> trying to update myself on the current state of art of revision
> systems. I read Wikipedia this passage:
> 
> http://en.wikipedia.org/wiki/Darcs
> 
> « Darcs currently has a number of significant bugs (see e.g. [1]). The
> most severe of them is "the Conflict bug" - an exponential blowup in
> time needed to perform conflict resolution during merges, reaching
> into the hours and days for "large" repositories. A redesign of the
> repository format and wide-ranging changes in the codebase are planned
> in order to fix this bug, and work on this is planned to start in
> Spring 2007 [2].  »
> 
> This somewhat bursted my bubble, as there always was some doubt in the
> back of my mind about just how Darcs is not just a fantasy-ware
> trumpeted by a bunch of functional tech geekers. (i heard of Darcs in
> irc emacs and haskell channels, who are often student and hobbiests
> programers)
> 
> Also, in my light research, it was to my surprise, that Darcs is not
> the only distributed systems, and perhaps not the first one neither,
> contrary to my impressions. In fact, today there are quite a LOT
> distributed revision systems, actually as a norm. When one looks into
> these, such as Git ( http://en.wikipedia.org/wiki/Git_(software) ) one
> finds that some of them are already in practical industrial use for
> large projects, as opposed to Darcs's academic/hobbist kind of
> community.
> 
> In addition to these findings, one additional that greatly pissed me
> off entirely about Darcs, is the intro of the author (David Roundy)'s
> essay about his (questionable-sounding) “theory of patches” used in
> Darcs. ( http://darcs.net/manual/node8.html#Patch )
> 
> Here's the 2 passages:
> 
> «I think a little background on the author is in order. I am a
> physicist, and think like a physicist. The proofs and theorems given
> here are what I would call ``physicist'' proofs and theorems, which is
> to say that while the proofs may not be rigorous, they are practical,
> and the theorems are intended to give physical insight. It would be
> great to have a mathematician work on this, but I am not a
> mathematician, and don't care for math.»
> 
> «From the beginning of this theory, which originated as the result of
> a series of email discussions with Tom Lord, I have looked at patches
> as being analogous to the operators of quantum mechanics. I include in
> this appendix footnotes explaining the theory of patches in terms of
> the theory of quantum mechanics. I know that for most people this
> won't help at all, but many of my friends (and as I write this all
> three of darcs' users) are physicists, and this will be helpful to
> them. To non-physicists, perhaps it will provide some insight into how
> at least this physicist thinks.»
> 
> I love math. I respect Math. I'm nothing but a menial servant to
> Mathematics. Who the fuck is this David guy, who proclaims that he's
> no mathematician, then proceed to tell us he dosen't fucking care
> about math? Then, he went on about HIS personal fucking zeal for
> physics, in particular injecting the highly quacky “quantum mechanics”
> with impunity.

I'm gonna like your writings with all respect. Actually your writings
has the quiet force. See you often ;;

-- 
Byung-Hee HWANG <[EMAIL PROTECTED]> * আমি তোমাকে ভালোবাসি
InZealBomb, Kyungpook National University, KOREA

"OK. Then I have to kill him."
-- Michael Corleone, "Chapter 11", page 146
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: DIAGNOSIS: Racism moves back to Denmark from South Africa

2007-10-19 Thread Maarten Bergvelt
On 2007-10-19, mich <[EMAIL PROTECTED]> wrote:
>
><[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>>
>> INCISIVE ANALYSIS: The dismantlement of Apartheid Regime in South
>> Africa sent the racist Dutch Afrikaners back to Denmark where they are
>> spreading their racist ideology -- The Apartheid "Christianity" :
>
>
> The Dutch went back to Denmark? 

Sure, Copenhagen is the capital of the Netherlands, any American
school child knows that.

-- 
Maarten Bergvelt
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Organizing Sequential Data (TimeStamps) Overthinking?

2007-10-19 Thread Gabriel Genellina
En Fri, 19 Oct 2007 16:17:41 -0300, Raymond Hettinger <[EMAIL PROTECTED]>  
escribió:

> Try heapq.nsmallest().

En Fri, 19 Oct 2007 16:20:29 -0300, Raymond Hettinger <[EMAIL PROTECTED]>  
escribió:

> Try heapq.nsmallest().

En Fri, 19 Oct 2007 17:22:13 -0300, Raymond Hettinger <[EMAIL PROTECTED]>  
escribió:

> Try heapq.nsmallest().


“Just the place for a Snark!” the Bellman cried,
As he landed his crew with care;
Supporting each man on the top of the tide
By a finger entwined in his hair.
“Just the place for a Snark! I have said it twice:
That alone should encourage the crew.
Just the place for a Snark! I have said it thrice:
What I tell you three times is true.”

THE HUNTING OF THE SNARK
an Agony in Eight Fits
by Lewis Carroll

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how to iterate over sequence and non-sequence ?

2007-10-19 Thread Bruno Desthuilliers
stef mientki a écrit :
> Steven D'Aprano wrote:
> 
>> On Fri, 19 Oct 2007 16:19:32 +0200, stef wrote:
>>
>>  
>>
>>> Well I'm not collecting data, I'm collecting pointers to data.
>>> 
>>
>>
>> I beg to differ, you're collecting data. How that data is to be 
>> interpreted (a string, a number, a pointer...) is a separate issue.
>>
>>
>>  
>>
>>> This
>>> program simulates a user written program in JAL. As Python doesn't
>>> support pointers, instead I collect names.
>>> 
>>
>>
>> This doesn't make any sense to me. If your user-written program is 
>> supplying pointers (that is, memory addresses like 0x15A8), how do you 
>> get a name from the memory address?
>>
>>
>> If you are trying to emulate pointer-manipulation, then the usual way 
>> to simulate a pointer is with an integer offset into an array:
>>
>> # initialise your memory space to all zeroes:
>> memory = [chr(0)]*1024*64  # 64K of memory space, enough for anyone
>> NULL = 0
>> pointer = 45
>> memory[pointer:pointer + 5] = 'HELLO'
>> pointer += 6
>> memory[pointer:pointer + 5] = 'WORLD'
>>
>>
>>   
> 
> If there is a better way, I'ld like to hear it.
> I understand that execute is dangerous.
> 
> I don't have pointers, I've just names (at least I think).
> Let me explain a little bit more,
> I want to simulate / debug a user program,
> the user program might look like this:
> 
>   x = 5
>   for i in xrange(10):
>   x = x + 1
> 
> So now I want to follow the changes in "x" and "i",
> therefor in the background I change the user program a little bit, like 
> this
> 
> def user_program():
>   x = 5; _debug(2)
>   global x,i
>   _debug (3)
>   for i in xrange(10):
>   _debug (3)
>   x = x + 1; _debug (4)

You do know that Python exposes all of it's compilation / AST / whatever 
machinery, don't you ? IOW, you can take a textual program, compile it 
to a code object, play with the AST, add debug hooks, etc... Perhaps you 
should spend a little more time studying the modules index ?
-- 
http://mail.python.org/mailman/listinfo/python-list


C++ version of the C Python API?

2007-10-19 Thread Robert Dailey
Hi,

Is there a C++ version of the C Python API packaged with python 2.5?
It would be nice to have a OOP approach to embedding python in C++. It
would also be a bonus if this C++ Python API cleaned up a lot of the
messy code involved in embedding python.

Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange behaviour with reversed()

2007-10-19 Thread Andreas Kraemer
On Oct 19, 1:49 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Andreas Kraemer <[EMAIL PROTECTED]> wrote:
> >> The only other behaviours I would regard as intuitive for iteration over
> >> a mutating sequence would be to throw an exception either for mutating
> >> the sequence while the iterator exists or for using the iterator after a
> >> mutation.
>
> > Maybe it would have been slightly more intuitive if reversed() had
> > been implemented like this,
>
> > def Reversed(seq):
> >   for i in xrange(len(seq)-1,-1,-1):
> > yield seq[i]
>
> > so that the length of the sequence is determined when the iteration
> > starts, not when the iterator is created?
>
> Perhaps, but either way it comes down to "don't modify the sequence while
> iterating".

Definitely agreed.

-- 
http://mail.python.org/mailman/listinfo/python-list


Need some help with my first Twisted program

2007-10-19 Thread McCann, Brian
I posted this to the Twisted list...figured I'd try here too.

I'm looking for what is probably an simple solution I can't figure out
on my own.  I'm writing an SSH server based on the example on the web
(using conch).  I'm trying to figure out how to detect when the client
exists (for example, when I just close out PuTTY), but I can't get this
to work right.  Looking through the API docs I found "connectionLost()",
which I put in my protocol class (EchoProtocol in the example), but it's
never getting called.  Here's my connectionLost def:

def connectionLost(self,reason):
print "lost:%s" %reason
self.serialServerSocket.close()
self.alive = False
self.serialSocketReadThread.join()

Can someone please tell me what I'm doing wrong?

Thanks,
--Brian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: documenting excepetions in Python

2007-10-19 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> In python, how do I know what exceptions a method

s/method/callable/

A method is only a thin wrapper around a function, and functions are 
just one kind of callable object (classes are another, and you can 
define your own...)

> could raise?

Practically speaking, you can't. Since an unhandled exception bubbles up 
the call stack, there's no reliable way to know what exception could 
happen when calling a function. Now there are quite a lot of 
'exceptions' you can expect in some situations - like IOError when 
dealing with files, etc.

>  Do I
> need to look at the source?

Would be impractical. Trying to spot each and every exception that could 
happen in a real-world call stack is a waste of time IMHO. Just deal 
with the ones that:
1/ could obviously happen here (like : a missing key in a dict, a 
non-(existing|readable|writable) file, etc,
2/ you can handle at this level

Else, just learn to live with the fact that shit happens.

>  I don't see this info in the API docs for
> any of the APIs I'm using.

Indeed. Most of the time, it would be just meaningless.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Organizing Sequential Data (TimeStamps) Overthinking?

2007-10-19 Thread Raymond Hettinger
On Oct 19, 11:26 am, xkenneth <[EMAIL PROTECTED]> wrote:
> All,
>
>Just a quick question. I want to be able to have a data structure
> that organizes data (timestamps I'm working with) sequentially, so
> that i can easily retrieve the first x amount of timeStamps without
> iterating over a list. My thought was to use a binary tree, am i
> overthinking the problem to try and implement this structure inside of
> python? I was also hoping this would already be done for me.

Try heapq.nsmallest().


Raymond


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use module audit-lib ?

2007-10-19 Thread Jarek Zgoda
Sébastien Weber napisał(a):

> I've installed the python-audit-lib module but there's no documentation.
> Does someone know how to use it ?

I don't know this package, but why did you install it? Maybe somebody in
Überwald knows its usage?

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Organizing Sequential Data (TimeStamps) Overthinking?

2007-10-19 Thread Raymond Hettinger
On Oct 19, 11:26 am, xkenneth <[EMAIL PROTECTED]> wrote:
> All,
>
>Just a quick question. I want to be able to have a data structure
> that organizes data (timestamps I'm working with) sequentially, so
> that i can easily retrieve the first x amount of timeStamps without
> iterating over a list. My thought was to use a binary tree, am i
> overthinking the problem to try and implement this structure inside of
> python? I was also hoping this would already be done for me.

Try heapq.nsmallest().


Raymond


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Organizing Sequential Data (TimeStamps) Overthinking?

2007-10-19 Thread Raymond Hettinger
On Oct 19, 11:26 am, xkenneth <[EMAIL PROTECTED]> wrote:
> All,
>
>Just a quick question. I want to be able to have a data structure
> that organizes data (timestamps I'm working with) sequentially, so
> that i can easily retrieve the first x amount of timeStamps without
> iterating over a list. My thought was to use a binary tree, am i
> overthinking the problem to try and implement this structure inside of
> python? I was also hoping this would already be done for me.

Try heapq.nsmallest().


Raymond


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: vote for Python - PLEASE

2007-10-19 Thread Steven D'Aprano
On Fri, 19 Oct 2007 15:45:42 +, Grant Edwards wrote:

> Even though Python is way ahead, you've probably ruined it for us.  I
> suspect the folks at MySQL will ignore or discount the results when they
> find out you've solicited fradulent votes from the Python community.

It's an Internet poll. By definition, the results are meaningless.


-- 
Steven.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class vs type

2007-10-19 Thread Steven D'Aprano
On Fri, 19 Oct 2007 12:21:25 -0400, Colin J. Williams wrote:

> In this case, why do we continue to use the word class to generate a
> type?

Because type is a callable, and class is convenient syntactic sugar.

class Parrot(object):
def speak(self, msg):
return "Polly sez %s" % msg


is much more convenient than:

import new
Parrot = type('Parrot', (object,), 
{'speak': lambda self, msg: 'Polly sez %s' % msg})

particularly for large classes with many methods.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class vs type

2007-10-19 Thread Terry Reedy

"Colin J. Williams" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Doesn't Python 3 provide an opportunity
| to move away from discussions about
| new_style vs old-style?  This an
| opportunity to treat old-style as a
| historical artefact, not requiring
| current explanation.

Yes, there will not be 'old-style' classes in Py3 and 3.0 doc will not 
mention them..  But we are actually at 2.5 and there will be 2.6, 2.7, 2.8? 
that still have them. 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to tell if a script has been run by Pythonw.exe instead of Python.exe?

2007-10-19 Thread Thomas Heller
Metalone schrieb:
> Thanks to all, I learned something in each post.
> When using py2exe to build an executable sys.executable does not
> provide the name of the python interpreter but the name of the
> executable generated by py2exe.
> 

When running the executable built with py2exe you might be interested
in the variable sys.frozen; they are set to the string 'console' or 'windows', 
IIRC.

Thomas

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Memory Problems in Windows 2003 Server

2007-10-19 Thread AMD
Thanks Marc,

I just tried shelve but it is very slow :(
I haven't tried the dbs yet.

Andre

Marc 'BlackJack' Rintsch a écrit :
> On Mon, 15 Oct 2007 11:31:59 +0200, amdescombes wrote:
> 
>> Are there any classes that implement disk based dictionaries?
> 
> Take a look at the `shelve` module from the standard library.
> 
> Or object databases like ZODB or Durus.
> 
> Ciao,
>   Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Organizing Sequential Data (TimeStamps) Overthinking?

2007-10-19 Thread Larry Bates
xkenneth wrote:
> All,
> 
>Just a quick question. I want to be able to have a data structure
> that organizes data (timestamps I'm working with) sequentially, so
> that i can easily retrieve the first x amount of timeStamps without
> iterating over a list. My thought was to use a binary tree, am i
> overthinking the problem to try and implement this structure inside of
> python? I was also hoping this would already be done for me.
> 
> Regards,
> Ken
> 
Sounds a little like premature optimization here.  It depends on how many 
timestamps you are talking about.  Certainly if you have a lot (millions),
you should implement binary search, but I would write code first and if it is 
too slow, fix that part.

-Larry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Control Log File Size

2007-10-19 Thread Matt McCredie
> I've got an application running on linux which writes log files using the
> python logging module. I'm looking for some help and advice to cap the size
> which the file will grow too, something reasonably like 2Mb would be great.
>
>
>
> What is the best way to handle this kind of thing? Can this be done using a
> setting in the logging module? Or is it something I'll have to get the FS to
> handle for me?

Check out the RotatingFileHandler: http://docs.python.org/lib/node413.html

It is part of the logging module and should do what you want.

Examples of using alternative handlers are here:

http://docs.python.org/lib/multiple-destinations.html

Matt
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Millisecond timestamp function?

2007-10-19 Thread Joshua J. Kugler
On Friday 19 October 2007 05:44, Dmitri O.Kondratiev wrote:

> What Python module / function can be used to get millisecond timestamps?
> time.time() returns the time as a floating point number expressed in
> seconds since the epoch, in UTC.
> 
> Thanks!

See the module datetime.

The datetime object can return down the to microsecond.

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2007, 10, 19, 9, 13, 53, 289075)

j

-- 
Joshua Kugler
Lead System Admin -- Senior Programmer
http://www.eeinternet.com
PGP Key: http://pgp.mit.edu/  ID 0xDB26D7CE

-- 
http://mail.python.org/mailman/listinfo/python-list

traceback over C API and PyObject_CallObject

2007-10-19 Thread Sami Vaisanen
Hello group,

I'm trying to get the Python exception information (message and traceback)
stored into a string in my C++ code. However all i get back is the string
"None". All the checks pass and all pointers get a value from the python
API calls. I've also tried with a different function such as
PyObject_CallFunctionObjArgs but the result is the same.

Thanks

void get_python_exception(string& message, string& traceback)
{
GIL g;
 
PyObject* type  = NULL;
PyObject* value = NULL;
PyObject* trace = NULL;
 
PyErr_Fetch(&type, &value, &trace);
 
py_ref ref_type(type);
py_ref ref_value(value);
py_ref ref_trace(trace);
 
py_ref name(PyString_FromString("traceback"));
py_ref module(PyImport_Import(name.get()));
if (module)
{
py_ref fun(PyObject_GetAttrString(module.get(), "format_exc"));
if (fun)
{
PyErr_Restore(type, value, trace);
ref_type.release();
ref_value.release();
ref_trace.release();
 
py_ref ret(PyObject_CallObject(fun.get(), NULL));
if (ret && PyString_Check(ret.get()))
{
char* str = PyString_AsString(ret.get());
message = str;
traceback = "traceback not available";
return;
}
}
}
message   = "message not available";
traceback = "traceback not available";
}


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: write whitespace/tab to a text file

2007-10-19 Thread marc wyburn
On Oct 19, 3:33 pm, dirkheld <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I would l like to write some data to a text file. I want to write the
> data with whitespace or tabs in between so that I create tabular
> columns like in a spreadsheet. How can I do this in python.
> (btw, I'm new to python)
>
> names = ['John','Steve','asimov','fred','jim']
> ## output I would like in txt file : John Steve
> asimov  fred jim
>
> f=open('/User/home/Documents/programming/python/test.txt','w')
> for x in range(len(names)):
> f.write(tags[x])
> f.close()

I'm not sure exactly but you'll probably need to find out what the
ASCII code is for a tab.  Personally I would just write data straight
into Excel using the win32 extensions.  I'm sure the same can be
achieved with OO on a Linux box.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to iterate over sequence and non-sequence ?

2007-10-19 Thread stef mientki
Steven D'Aprano wrote:
> On Fri, 19 Oct 2007 16:19:32 +0200, stef wrote:
>
>   
>> Well I'm not collecting data, I'm collecting pointers to data.
>> 
>
> I beg to differ, you're collecting data. How that data is to be 
> interpreted (a string, a number, a pointer...) is a separate issue.
>
>
>   
>> This
>> program simulates a user written program in JAL. As Python doesn't
>> support pointers, instead I collect names.
>> 
>
> This doesn't make any sense to me. If your user-written program is 
> supplying pointers (that is, memory addresses like 0x15A8), how do you 
> get a name from the memory address?
>
>
> If you are trying to emulate pointer-manipulation, then the usual way to 
> simulate a pointer is with an integer offset into an array:
>
> # initialise your memory space to all zeroes:
> memory = [chr(0)]*1024*64  # 64K of memory space, enough for anyone
> NULL = 0
> pointer = 45
> memory[pointer:pointer + 5] = 'HELLO'
> pointer += 6
> memory[pointer:pointer + 5] = 'WORLD'
>
>
>   
If there is a better way, I'ld like to hear it.
I understand that execute is dangerous.

I don't have pointers, I've just names (at least I think).
Let me explain a little bit more,
I want to simulate / debug a user program,
the user program might look like this:

   x = 5
   for i in xrange(10):
   x = x + 1

So now I want to follow the changes in "x" and "i",
therefor in the background I change the user program a little bit, like 
this

def user_program():
   x = 5; _debug(2)
   global x,i
   _debug (3)
   for i in xrange(10):
   _debug (3)
   x = x + 1; _debug (4)

And this modified user program is now called by the main program.
Now in the _debug procedure I can set breakpoints and watch x and i.
But as in this case both a and i are simple integers,
I can not reference them and I need to get their values through their 
names,
and thus a execute statement.

I couldn't come up with a better solution ;-)
(There may be no restrictions laid upon the user program, and indeed 
name clashing is an accepted risk).

cheers,
Stef




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class vs type

2007-10-19 Thread Colin J. Williams
Hrvoje Niksic wrote:
> "Colin J. Williams" <[EMAIL PROTECTED]> writes:
> 
>> In Python Types and Objects, Shalabh Chaturvedi says (in the Python
>> 3.0 documentation - New Style Classes)
>>
>> "The term class is traditionally used to imply an object created by
>> the class statement. However, classes are now synonymous with
>> types. Built-in types are usually not referred to as classes. This
>> book prefers using the term type for both built-in and user created
>> types."
>>
>> Do we need two different words to describe what is essentially the
>> same thing?
> 
> We don't, not anymore, which is why the author chooses the word "type"
> for both in the last sentence.
In this case, why do we continue to use 
the word class to generate a type?
> 
> But, as the author correctly explains, class and type used to not be
> the same thing.  Classes were created with 'class', and they were
> fundamentally different from C types created in extension modules.
> All instances of old-style classes are of type 'instance', which is
> why they have the __class__ attribute, so you can find their actual
> class.  (Functions like "isinstance" contain hacks to support
> old-style classes.)  New-style classes elevate Python-level classes to
> types equal to the built-in ones, which is why the word "type" is now
> sufficient for both.
Doesn't Python 3 provide an opportunity 
to move away from discussions about
new_style vs old-style?  This an 
opportunity to treat old-style as a
historical artefact, not requiring 
current explanation.

Colin W.

-- 
http://mail.python.org/mailman/listinfo/python-list


write whitespace/tab to a text file

2007-10-19 Thread dirkheld
Hi,

I would l like to write some data to a text file. I want to write the
data with whitespace or tabs in between so that I create tabular
columns like in a spreadsheet. How can I do this in python.
(btw, I'm new to python)

names = ['John','Steve','asimov','fred','jim']
## output I would like in txt file : John Steve
asimov  fred jim

f=open('/User/home/Documents/programming/python/test.txt','w')
for x in range(len(names)):
f.write(tags[x])
f.close()

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: documenting excepetions in Python

2007-10-19 Thread Nikita the Spider
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] wrote:

> In python, how do I know what exceptions a method could raise?  Do I
> need to look at the source?  I don't see this info in the API docs for
> any of the APIs I'm using.

Hi Dale,
Usually the docs for a method will list the likely exceptions, but 
there's no way to know the full list of possible exceptions except by 
testing, testing, testing. Obviously, there's always a chance that 
there's a test you didn't think of and therefore an exception 
unaccounted for. I think this is a less-than-ideal aspect of Python but 
I don't have a suggestion on how to improve it.

Good luck

-- 
Philip
http://NikitaTheSpider.com/
Whole-site HTML validation, link checking and more
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: vote for Python - PLEASE

2007-10-19 Thread Grant Edwards
On 2007-10-18, Monty Taylor <[EMAIL PROTECTED]> wrote:

> MySQL has put up a poll on http://dev.mysql.com asking what your primary 
> programming language is. Even if you don't use MySQL - please go stick 
> in a vote for Python. I'm constantly telling folks that Python needs 
> more love, but PHP and Java are kicking our butts...
>
> (I know the world would be a better place if the poll were honest, but 
> I'd rather that people got the message that they should do more python 
> development work!)

What makes you think that faking a poll will send that message?

Even though Python is way ahead, you've probably ruined it for
us.  I suspect the folks at MySQL will ignore or discount the
results when they find out you've solicited fradulent votes
from the Python community.

-- 
Grant Edwards   grante Yow! I just got my PRINCE
  at   bumper sticker ... But now
   visi.comI can't remember WHO he
   is ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: vote for Python - PLEASE

2007-10-19 Thread Bjoern Schliessmann
Monty Taylor wrote:

> MySQL has put up a poll on http://dev.mysql.com asking what your
> primary programming language is. Even if you don't use MySQL -
> please go stick in a vote for Python. I'm constantly telling folks
> that Python needs more love, but PHP and Java are kicking our
> butts...

If the MySQL developers base their support decision on a
non-representative web vote, I'll really use a different project if
I needed one ...

Regards,


Björn

-- 
BOFH excuse #297:

Too many interrupts

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please Help !!!

2007-10-19 Thread kyosohma
On Oct 17, 4:32 am, Heiko Schlierkamp <[EMAIL PROTECTED]
africa.com.na> wrote:
> I need to update the virus program every day with the new dat file from
> mcafee
> I would like to us a Bat file to go to the web page and download the dat
> file automatically to a specific Directory, that I have created, but my
> problem lays in that the bat file will open the file to be downloaded but
> the bat file does not confirm the save button so that it start to download
> the file, that I still need to do manual. Please advice me with what still
> need to be done!!
> Your help will be very appreciated!!!
>
> I have added the file so you can see what it does exactly!!
>
> > Heiko Schlierkamp
> > SENSE OF AFRICA - Namibia
> > E-mail: [EMAIL PROTECTED]
> > Website:www.sense-of-africa.com
> > Tel: +264 61 275300
> > Fax: +264 61 263417
> > PO Box 2058, Windhoek, Namibia
>
>  <>
>
>  Superdat.rar
> 1KDownload

Besides all the other answers, why not just have McAfee do it? Hello?
McAfee is a mature product that should auto-download and auto-update
itself, if set up properly.

Mike

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to iterate over sequence and non-sequence ?

2007-10-19 Thread Steven D'Aprano
On Fri, 19 Oct 2007 16:19:32 +0200, stef wrote:

> Well I'm not collecting data, I'm collecting pointers to data.

I beg to differ, you're collecting data. How that data is to be 
interpreted (a string, a number, a pointer...) is a separate issue.


> This
> program simulates a user written program in JAL. As Python doesn't
> support pointers, instead I collect names.

This doesn't make any sense to me. If your user-written program is 
supplying pointers (that is, memory addresses like 0x15A8), how do you 
get a name from the memory address?


If you are trying to emulate pointer-manipulation, then the usual way to 
simulate a pointer is with an integer offset into an array:

# initialise your memory space to all zeroes:
memory = [chr(0)]*1024*64  # 64K of memory space, enough for anyone
NULL = 0
pointer = 45
memory[pointer:pointer + 5] = 'HELLO'
pointer += 6
memory[pointer:pointer + 5] = 'WORLD'


> The names are derived from an
> analysis of the user program under test, so the danger some of you are
> referring to, is not there, or at least is not that simple.

What about accidental clashes between your program's names and the names 
you are collecting? Are you sure there are no corner cases where 
something you pass to exec can interact badly with your code?

The thing is, exec is stomping through your program's namespace with 
great big steel-capped boots, crushing anything that gets in the way. 
Even if it is safe in your specific example, it is still bad practice, or 
at least risky practice. Code gets reused, copied, and one day a piece of 
code you wrote for the JAL project ends up running on a webserver and now 
you have a serious security hole.

(Every security hole ever started off with a programmer thinking "This is 
perfectly safe to do".)

But more importantly, what makes you think that exec is going to be 
faster and more efficient than the alternatives? By my simple test, I 
find exec to be about a hundred times slower than directly executing the 
same code:

>>> timeit.Timer("a = 1").timeit()
0.26714611053466797
>>> timeit.Timer("exec s", "s = 'a = 1'").timeit()
25.963317155838013


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: write whitespace/tab to a text file

2007-10-19 Thread Sébastien Weber
Le Fri, 19 Oct 2007 07:33:29 -0700, dirkheld a écrit :

> Hi,
> 
> I would l like to write some data to a text file. I want to write the
> data with whitespace or tabs in between so that I create tabular columns
> like in a spreadsheet. How can I do this in python. (btw, I'm new to
> python)
> 
> names = ['John','Steve','asimov','fred','jim'] ## output I would like in
> txt file : John Steve asimov  fred jim
> 
> f=open('/User/home/Documents/programming/python/test.txt','w')
>   for x in range(len(names)):
>   f.write(tags[x])
>   f.close()
Maybe :

names = ["Sebastien", "Ana", "Elodie", "Mohamed", "Antoniavna"]
maxlen = max(len(n) for n in names)
linetowrite = ""
for n in names:
linetowrite += n.ljust(maxlen + 3, ' ')
f = open('test.txt', 'w')
f.writelines(linetowrite.strip(' ') + '\n')
f.close()
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: write whitespace/tab to a text file

2007-10-19 Thread Tim Chase
> I would l like to write some data to a text file. I want to write the
> data with whitespace or tabs in between so that I create tabular
> columns like in a spreadsheet. How can I do this in python.
> (btw, I'm new to python)
> 
> names = ['John','Steve','asimov','fred','jim']
> ## output I would like in txt file : John Steve
> asimov  fred jim
> 
> f=open('/User/home/Documents/programming/python/test.txt','w')
>   for x in range(len(names)):
>   f.write(tags[x])
>   f.close()
> 

The idiomatic way to do this would be something like

 f = open('/path/to/file.txt', 'w')
 f.write('\t'.join(names))
 f.write('\n')
 f.close()

the .join() method on a string joins the contents of a list with
the string on which it's called (in this case, "\t" which is a tab).

-tkc



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please Help !!!

2007-10-19 Thread Tim Golden
marc wyburn wrote:
> On Oct 17, 10:32 am, Heiko Schlierkamp <[EMAIL PROTECTED]
> africa.com.na> wrote:
>> I need to update the virus program every day with the new dat file from
>> mcafee
>> I would like to us a Bat file to go to the web page and download the dat
>> file automatically to a specific Directory, that I have created, but my
>> problem lays in that the bat file will open the file to be downloaded but
>> the bat file does not confirm the save button so that it start to download
>> the file, that I still need to do manual. Please advice me with what still
>> need to be done!!
>> Your help will be very appreciated!!!
>>
>> I have added the file so you can see what it does exactly!!
>>
>>> Heiko Schlierkamp
>>> SENSE OF AFRICA - Namibia
>>> E-mail: [EMAIL PROTECTED]
>>> Website:www.sense-of-africa.com
>>> Tel: +264 61 275300
>>> Fax: +264 61 263417
>>> PO Box 2058, Windhoek, Namibia
>>  <>
>>
>>  Superdat.rar
>> 1KDownload
> 
> I'm not going to open that file I'm afraid and I doubt many others
> will either. You are using Python I assume.  Have a look at the urllib
> module and the urlretrieve function.

Or, for a non-Python solution, simply use wget (or some other
command-line downloading program):

   http://users.ugent.be/~bpuype/wget/

TJG
-- 
http://mail.python.org/mailman/listinfo/python-list


SWIG-PYTHON -> Problem in header file inclusion

2007-10-19 Thread abarun22
Hi
I am facing a problem while including a C header file in the SWIG
interface file.  However the problem does not occur when i directly
copy the contents of header file in the same place.

My interface file read as follows.
/*  interface file dep.i  */
%module dep
%{
#include "dep.h"
%}
%inline %{
extern int  ReadDep (char* fname, DONfic* don, int nb2, int nb4);
%}

And my header file consists of the structure DONfic as shown below.
/* Header file dep.h */
typedef struct _DONfic {
intnb_dep, nb_inc_dep, ncasec_dep;
intmax_dep;
} DONfic;

>From python i tried to access the C structure as a python class as
shown below.
/* File pydep.py*/
>> import dep
>>...
>> d = dep.DONfic()
Gives the following error message

Traceback (most recent call last):
  File "pydep.py", line 5, in ?
d = dep.DONfic()
AttributeError: 'module' object has no attribute 'DONfic'
The problem is that i cannot get access to the structure if i directly
include the file "dep.h". On the other hand if i copy the contents of
the header file and paste it directly in to the header section of the
SWIG interface file it works.
It works for the following interface file .
%module dep
%{
typedef struct _DONfic {
intnb_dep, nb_inc_dep, ncasec_dep;
intmax_dep;
} DONfic;
%}
%inline %{
extern int  ReadDep (char* fname, DONfic* don, int nb2, int nb4);
%}


I tried out lot of options and does n't seems to work. Any suggestions
or ideas are most welcome.

-- 
http://mail.python.org/mailman/listinfo/python-list


Control Log File Size

2007-10-19 Thread Robert Rawlins - Think Blue
Hello Chaps,

 

I've got an application running on linux which writes log files using the
python logging module. I'm looking for some help and advice to cap the size
which the file will grow too, something reasonably like 2Mb would be great.

 

What is the best way to handle this kind of thing? Can this be done using a
setting in the logging module? Or is it something I'll have to get the FS to
handle for me?

 

Thanks chaps,

 

Rob

-- 
http://mail.python.org/mailman/listinfo/python-list

Millisecond timestamp function?

2007-10-19 Thread Dmitri O.Kondratiev
What Python module / function can be used to get millisecond timestamps?
time.time() returns the time as a floating point number expressed in seconds
since the epoch, in UTC.

Thanks!
-- 
Dmitri O. Kondratiev
[EMAIL PROTECTED]
http://www.geocities.com/dkondr
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: ConfigParser preserving file ordering

2007-10-19 Thread Andrew Durdin
On 10/19/07, Frank Aune <[EMAIL PROTECTED]> wrote:
>
> Yes, but as I said I need functionality present in the standard-library, so
> sub-classing ConfigParser is the last option really.

Any particular reason you're limited to the standard library?

I've used iniparse  before as a
drop-in replacement for ConfigParser that preserves ordering and
comments, and only falling back to ConfigParser if iniparse wasn't
present; like this:

try:
from iniparse.compat import *
except ImportError:
from ConfigParser import *

As for updating ConfigParser -- like most other changes, it probably
needs a champion.

Andrew
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class vs type

2007-10-19 Thread Hrvoje Niksic
"Colin J. Williams" <[EMAIL PROTECTED]> writes:

> In Python Types and Objects, Shalabh Chaturvedi says (in the Python
> 3.0 documentation - New Style Classes)
>
> "The term class is traditionally used to imply an object created by
> the class statement. However, classes are now synonymous with
> types. Built-in types are usually not referred to as classes. This
> book prefers using the term type for both built-in and user created
> types."
>
> Do we need two different words to describe what is essentially the
> same thing?

We don't, not anymore, which is why the author chooses the word "type"
for both in the last sentence.

But, as the author correctly explains, class and type used to not be
the same thing.  Classes were created with 'class', and they were
fundamentally different from C types created in extension modules.
All instances of old-style classes are of type 'instance', which is
why they have the __class__ attribute, so you can find their actual
class.  (Functions like "isinstance" contain hacks to support
old-style classes.)  New-style classes elevate Python-level classes to
types equal to the built-in ones, which is why the word "type" is now
sufficient for both.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Enso or Launchy like UI from Python

2007-10-19 Thread kyosohma
On Oct 19, 3:45 am, zooey <[EMAIL PROTECTED]> wrote:
> Hi there,
>
> I want to make transparent/launcher-like window application using python.
>
> (similar as Enso, Launchy, etc. I know Enso written in python.)
>
> Is there any open source project like it or any example?
>
> Thanks,
>
>   Aaron.
>
> --
> View this message in 
> context:http://www.nabble.com/Enso-or-Launchy-like-UI-from-Python-tf4651810.h...
> Sent from the Python - python-list mailing list archive at Nabble.com.

I know wxPython has the ability to make any of its windows semi-
transparent or completely transparent and I would assume that the
other major Python GUI toolkits can do so as well.

All you'd really need to do is use glob.glob to get the shortcuts from
whatever directories you want and then do auto-complete when the user
tries to type a name. I think the subprocess module would probably be
your best bet for launching the applications.

Mike

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to iterate over sequence and non-sequence ?

2007-10-19 Thread Duncan Booth
Nils <[EMAIL PROTECTED]> wrote:

> why not:
 for i in eval('(1,2,3)'):
> ... print i
> 1
> 2
> 3
> 

For the exact same reason Steven already gave you: one day someone will 
give you bad data.

For eval you need to use slightly more complicated expressions. e.g. 
"__import__('os').system('rm # -rf /')"
will be sufficient to mess you up.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Noob questions about Python

2007-10-19 Thread Hendrik van Rooyen
"Arnaud Delobelle"  wrote:

> In binary 2 is 10.  When you multiply by 10, you shift all your digits
> left by 1 place.
> When you multiply by 10**n (which is 1 followed by n zeroes), you
> shift all your digits left by n places.

I read somewhere:

Only 1 person in 1000 understands binary.
The other 111 don't have a clue.

- Hendrik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Noob: Loops and the 'else' construct

2007-10-19 Thread Dustan
On Oct 19, 3:12 am, Thorsten Kampe <[EMAIL PROTECTED]> wrote:
> So a for/else loop is exactly the same thing as a for loop with the
> else clause outside the loop (except for "break")?

Am I missing something here? It sounds to me like you just described
two identical constructs.

> Guess that's why I
> never used that...
>
> Thorsten


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to iterate over sequence and non-sequence ?

2007-10-19 Thread Nils
On Oct 19, 10:58 am, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> On Fri, 19 Oct 2007 01:24:09 +0200, stef mientki wrote:
> > hello,
>
> > I generate dynamically a sequence of values, but this "sequence" could
> > also have length 1 or even length 0.
>
> > So I get some line in the form of:
> >   line = '(2,3,4)'
> >   line = ''
> >   line = '(2)'
> > (in fact these are not constant numbers, but all kind of integer
> > variables, coming from all over the program, selected from a tree, that
> > shows all "reachable" variables)
>
> > So in fact I get the value from an exec statement, like this
> >   exec 'signals = ' + line
>
> And then, one day, somebody who doesn't like you will add the following
> to your input data:
>
> "0; import os; os.system('rm # -rf /')"
>
> [ Kids: don't try this at home! Seriously, running that command will be
> bad for your computer's health. Or at least it would, if I hadn't put a
> spike in it. ]
>
> Don't use exec in production code unless you know what you're doing. In
> fact, don't use exec in production code.
>
> > Now I want to iterate over "signals", which works perfect if there are 2
> > or more signals,
> > but it fails when I have none or just 1 signal.
> > for value in signals :
> > do something
>
> No, I would say it already failed before it even got there.
>
> >>> line = ''
> >>> exec 'signals = ' + line
>
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 1
> signals =
> ^
> SyntaxError: unexpected EOF while parsing
>
> This is the right way to deal with your data:
>
> input_data = """  (2, 3  , 4)
>
>   (2)
> (3,4,5)
> ( 1, 2,3)
> """
>
> for line in input_data.split('\n'):
> line = line.strip().strip('()')
> values = line.split(',')
> for value in values:
> value = value.strip()
> if value:
> print(value)
>
> > As this meant for real-time signals, I want it fast, so (I think) I
> > can't afford extensive testing.
>
> Don't guess, test it and see if it is fast enough. Some speed ups:
>
> If you're reading from a file, you can just say: "for line in file:"
> instead of slurping the whole lot into one enormous string, then
> splitting over newlines.
>
> If you can guarantee that there is no extra whitespace in the file, you
> can change the line
>
> line = line.strip().strip('()')
>
> to the following:
>
> line = line.strip('\n()')
>
> and save a smidgen of time per loop. Likewise, drop the "value =
> value.strip()" in the inner loop.
>
> --
> Steven.

why not:
>>> for i in eval('(1,2,3)'):
... print i
1
2
3

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dynamic invoke

2007-10-19 Thread Diez B. Roggisch
 [EMAIL PROTECTED] wrote:

> On 19 Oct, 11:45, Jarek Zgoda <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] napisa³(a):
>>
>> > Is there any way (other then eval) to invoke a method by passing
>> > method name in a string.
>> > It's very simple in php:
>> > $oFoo = new Foo();
>> > $dynamiMethod = "bar";
>> > $oFoo->$dynamiMethod();
>>
>> > Unfortunately I can't find a good solution to do the same thing in
>> > python. Does it have some build-in function to do it?
>>
>> foo = getattr(module_or_object, 'function_name')
>> foo()
>>
>> --
>> Jarek Zgoda
>> Skype: jzgoda | GTalk: [EMAIL PROTECTED] | voice: +48228430101
>>
>> "We read Knuth so you don't have to." (Tim Peters)
> 
> Superb!
> I was lookig for something like this. Belive me or not but i spent
> lots of time looking for this simple solution :)

The above clearly is a solution to your problem. I just wonder if you _need_
it. PHP doesn't have the concept of a function reference. So you need to
store/use names.

But in Python you can do this:

def foo():
print "foo"

callback = foo
callback()

As trivial this code is, it illustrates one thing: passing around functions
is as easy as passing around other values. So maybe you don't need a
function name. Only a suggestion to ponder about though, it might be that
your usecase is not suited for the above.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list

a good website for softwares,sports,movies and music ,sex etc.

2007-10-19 Thread panguohua
www.space666.com



nice

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to tell if a script has been run by Pythonw.exe instead of Python.exe?

2007-10-19 Thread BlueBird
On Oct 18, 11:56 pm, Metalone <[EMAIL PROTECTED]> wrote:
> In particular I want to know how to tell if reading and writing to the
> console can occur.
> Something like
> sys.isConsolePresent()

For a different problem, I have the following code. It might help:

def isrealfile(file):
"""
Test if file is on the os filesystem. This is necessary on windows,
when
starting python with pythonw.exe because in that case, the
stdout and stderr
are not real file and will create IOError when being flushed or when
more
than 4096 bytes are written.
"""
if not hasattr(file, 'fileno'): return False
try: tmp = os.dup(file.fileno())
except: return False
else: os.close(tmp); return True

class NullStream:
"""
A file like class that writes nothing
"""
def close(self): pass
def flush(self): pass
def write(self, str): pass
def writelines(self, sequence): pass

if not isrealfile(sys.stdout):
   sys.stdout = NullStream()

if not isrealfile(sys.stderr):
   sys.stderr = NullStream()


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Noob questions about Python

2007-10-19 Thread A.T.Hofkamp
On 2007-10-19, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> On Oct 19, 1:44 am, MRAB <[EMAIL PROTECTED]> wrote:
>> On Oct 18, 7:05 am, Michele Simionato <[EMAIL PROTECTED]>
>>
>> if number == 0:
>> return "0"
>>
>
> Hey,
>
> Isn't
> if not number:
>   return "0"
>
> faster?

Depends on who is parsing it.

If a computer, possibly a few micro-seconds (if the Python byte-code generator
doesn't optimize it away).

If a human, then it is slower by at least a second.


Since I prefer to optimize on my time rather than CPU time, I'd prefer the
first version

Albert
-- 
http://mail.python.org/mailman/listinfo/python-list


CGI Server that supports redirects

2007-10-19 Thread Thomas Guettler
Hi,

CGIHTTPServer does not support redirects[1]

Is there an other python-only way to get a web server
running wich can execute python code?

Since I already use flup[2]. I think there is not much
missing to get it serving as http server.

Has anyone hints?


[1] http://docs.python.org/lib/module-CGIHTTPServer.html
[2]http://trac.saddi.com/flup

-- 
Thomas Güttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/
E-Mail: guettli (*) thomas-guettler + de
Spam Catcher: [EMAIL PROTECTED]

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-19 Thread Peter Otten
Abandoned wrote:

> I'm very confused :(
> I try to explain main problem...

That's always a good first step; try to remember that when you start
your next thread.

> I have a table like this:
> id-1 | id-2 | value
> 23 24   34
> 56 68   66
> 56 98   32455
> 55 62   655
> 56 28   123
>  ( 3 millions elements)
> 
> I select where id=56 and 100.000 rows are selecting but this took 2
> second. (very big for my project)
> I try cache to speed up this select operation..
> And create a cache table:
> id-1 | all
> 56{68:66, 98:32455, 62:655}
> 
> When i select where id 56 i select 1 row and its took 0.09 second but
> i must convert text to dictionary..

Before you go on with your odd caching schemes -- is the database properly
indexed? Something like

CREATE UNIQUE INDEX mytable_id1_id2 ON mytable (id-1, id-2);

(actual syntax may differ) might speed up the lookup operation
enough that you can do without caching.

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Enso or Launchy like UI from Python

2007-10-19 Thread zooey


Hi there,

I want to make transparent/launcher-like window application using python.

(similar as Enso, Launchy, etc. I know Enso written in python.)

Is there any open source project like it or any example? 


Thanks,

  Aaron.

  
-- 
View this message in context: 
http://www.nabble.com/Enso-or-Launchy-like-UI-from-Python-tf4651810.html#a13290522
Sent from the Python - python-list mailing list archive at Nabble.com.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Noob: Loops and the 'else' construct

2007-10-19 Thread Thorsten Kampe
* Gabriel Genellina (Fri, 19 Oct 2007 00:11:18 -0300)
> En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus <[EMAIL PROTECTED]>  
> escribió:
> > I have just come across a site that discusses Python's 'for' and
> > 'while' loops as having an (optional) 'else' structure.
> >
> > At first glance I interpreted it as being a bit like the 'default'
> > structure in PHP's switch block... But the switch block isn't a loop,
> > so, I am now confused as to the reason for using 'else' with the for
> > and while loops...
> >
> > A few quick tests basically show that statements in the else structure
> > are executed at the fulfillment of the loop's expression (ie, no
> > break).
> 
> A `while` loop tests a condition: if it evaluates to true, keep cycling;  
> if it is false, stop. The `else` clause is executed when the condition is  
> false, as in any `if` statement. If you exit the loop by using `break`,  
> the `else` part is not executed (because you didn't get out of the loop by  
> determining the condition falseness)

So a for/else loop is exactly the same thing as a for loop with the 
else clause outside the loop (except for "break")? Guess that's why I 
never used that...

Thorsten
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: problem with Python class creating

2007-10-19 Thread dmitrey
Thanks all for these detailed explanations.
On Oct 18, 10:48 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> dmitrey a écrit :
> Not unless these classes define their own initializers. But that's
> another problem
>
> > and there are lots of
> > those ones)
>
> > class MyClass:
> > def __init__(self):
> > iterfcn = lambda *args: ooIter(self)
>
> The real problem is that you create one anonymous function *per instance*.
No, it's not a problem - it's desired behaviour.
Regards, Dmitrey

-- 
http://mail.python.org/mailman/listinfo/python-list

Please Help !!!

2007-10-19 Thread Heiko Schlierkamp
I need to update the virus program every day with the new dat file from
mcafee
I would like to us a Bat file to go to the web page and download the dat
file automatically to a specific Directory, that I have created, but my
problem lays in that the bat file will open the file to be downloaded but
the bat file does not confirm the save button so that it start to download
the file, that I still need to do manual. Please advice me with what still
need to be done!!
Your help will be very appreciated!!!

I have added the file so you can see what it does exactly!!

> Heiko Schlierkamp
> SENSE OF AFRICA - Namibia 
> E-mail: [EMAIL PROTECTED] 
> Website: www.sense-of-africa.com 
> Tel: +264 61 275300  
> Fax: +264 61 263417 
> PO Box 2058, Windhoek, Namibia 
 <> 


Superdat.rar
Description: Binary data
-- 
http://mail.python.org/mailman/listinfo/python-list

  1   2   >