blank lines representation in python

2006-05-02 Thread micklee74
hi
what is the correct way to represent blank lines in python (while
iterating a file) without regexp? I know one way is to use
re.search((line,r'^$') to grab a blank line, but i wanna try not to use
regexp...
is it
1) if line == ''": dosomething()  (this also means EOF right? )
2) if line is None: dosomething()
3) if not line: dosomething()
thanks

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


string.find first before location

2006-05-02 Thread Gary Wessle
Hi

I have a string like this

text = "abc abc and Here and there"
I want to grab the first "abc" before "Here"

import string
string.find(text, "Here") # 

I am having a problem with the next step.

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


Re: string.find first before location

2006-05-02 Thread Ravi Teja
text[:text.find('Here')].rfind('abc')

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


Re: blank lines representation in python

2006-05-02 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> what is the correct way to represent blank lines in python (while
> iterating a file) without regexp? I know one way is to use
> re.search((line,r'^$') to grab a blank line, but i wanna try not to use
> regexp...
> is it
> 1) if line == ''": dosomething()  (this also means EOF right? )
> 2) if line is None: dosomething()
> 3) if not line: dosomething()
> thanks

if line == "\n": # look for a single newline
dosomething()

or

if not line:
... end of file ...
elif not line.strip(): # look for lines with nothing but whitespace
dosomething()





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


Re: strip newlines and blanks

2006-05-02 Thread Peter Otten
[EMAIL PROTECTED] wrote:

Mick, you should be a bit more patient. Allow for some time for an answer to
arrive. Minor edits of your question don't warrant a repost.

> i have a file test.dat eg
> 
> abcdefgh
> ijklmn
>  <-newline
> opqrs
> tuvwxyz
> 
> 
> I wish to print the contents of the file such that it appears:
> abcdefgh
> ijklmn
> opqrs
> tuvwxyz
> 
> here is what i did:
> f = open("test.dat")
> while 1:
> line = f.readline().rstrip("\n")
> if line == '':
> break
> print line
> 
> but it always give me first 2 lines, ie
> abcdefgh
> ijklmn
> 
> What can i do to make it print all w/o the newlines..? and what is the
> proper way to skip printing blank lines while iterating file contents?

The end of the file is signalled by an empty string, and a blank line with
the trailing "\n" stripped off is an empty string, too. Therefore you have
to perform the line == '' test before the stripping.

Here's an alternative approach:

for line in f:
line = line.rstrip()
if line: 
print line

This will ignore any lines containing only whitespace and remove trailing
whitespace from the non-white lines.

Peter
 

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


Re: string.find first before location

2006-05-02 Thread Peter Otten
Gary Wessle wrote:

> I have a string like this
> 
> text = "abc abc and Here and there"
> I want to grab the first "abc" before "Here"
> 
> import string
> string.find(text, "Here") # 
> 
> I am having a problem with the next step.

These days str methods are preferred over the string module's functions.

>>> text = "abc abc and Here and there"
>>> here_pos = text.find("Here")
>>> text.rfind("abc", 0, here_pos)
4

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


Re: strip newlines and blanks

2006-05-02 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> i have a file test.dat eg
>
> abcdefgh
> ijklmn
>  <-newline
> opqrs
> tuvwxyz
>
>
> I wish to print the contents of the file such that it appears:
> abcdefgh
> ijklmn
> opqrs
> tuvwxyz
>
> here is what i did:
> f = open("test.dat")
> while 1:
> line = f.readline().rstrip("\n")
> if line == '':
> break
> print line
>
> but it always give me first 2 lines, ie
> abcdefgh
> ijklmn
>
> What can i do to make it print all w/o the newlines..? and what is the
> proper way to skip printing blank lines while iterating file contents?

assuming you want to skip *all* blank lines (even if they have whitespace
on them),

for line in open("test.dat"):
if line.strip():
print line





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


Re: Using elementtree: replacing nodes

2006-05-02 Thread Fredrik Lundh
André wrote:

> I've started using elementtree and don't understand how to use it to
> manipulate and replace nodes.  I know how to do this using a simple,
> but inefficient parser I wrote, but I'd rather learn to use a better
> tool - especially as it is to be added to the standard library.

> Now, I would like to find all  tags of the "text" class and

for pre in elem.getiterator("pre"):

or

for pre in elem.findall(".//pre"):

> 1. change the class value

pre.set("class", "value")

> 2. append another node (  )
> 3. surround the both nodes by a third one (  )

or in other words,

2. replace the  with a  element that contains some
new contents derived from the old element

# 1) build the new form
form = Element("form")
e = SubElement(form, "pre")
e.set("class", "text2")
e.text = pre.text
e = SubElement(form, "textarea", cols=80, name="code")
e = SubElement(form, "input", type="submit")

# 2) mutate the pre element
pre.clear()
pre.tag = "form"
pre[:] = [form]

for harder cases, a common pattern is:

for parent in elem.getiterator():
for index, child in enumerate(parent.findall("pre")):
# the code in here can manipulate parent[i] and child

another approach is to build a parent map; see the parent_map code
at

   http://effbot.org/zone/element.htm#the-element-type





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

Re: strip newlines and blanks

2006-05-02 Thread micklee74
thanks..and sorry, i am using the web version of google groups and
didn't find  an option i can edit my post, so i just removed it..
thanks again for the reply..

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


Re: stripping blanks

2006-05-02 Thread seeker
[EMAIL PROTECTED] wrote:
> hi
> i have a file test.dat eg
> 
> abcdefgh
> ijklmn
>  <-newline
> opqrs
> tuvwxyz
>   <---newline
> 
> I wish to print the contents of the file such that it appears:
> abcdefgh
> ijklmn
> opqrs
> tuvwxyz
> 
> here is what i did:
> f = open("test.dat")
> while 1:
> line = f.readline().rstrip("\n")
> if line == '':
> break
> #if not re.findall(r'^$',line):
> print line
> 
> but it always give me first 2 lines, ie
> abcdefgh
> ijklmn
> 
> What can i do to make it print all..?
> thanks
> 
Hi,

this should work better:


  f = open("test.dat")
  while 1:
  line = f.readline().rstrip("\n")
  if line == '':
  continue
  #if not re.findall(r'^$',line):
  print line
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: noob question: "TypeError" wrong number of args

2006-05-02 Thread Edward Elliott
Steve Holden wrote:
> Objects don't actually "pass references to themselves". The interpreter
> adds the bound instance as the first argument to a call on a bound method.

Sure, if you want to get technical  For that matter, objects don't actually
call their methods either -- the interpreter looks up the method name in a
function table and dispatches it.  I don't see how shorthand talk about
objects as actors hurts anything unless we're implementing an interpreter.


> Sorry, it's a wart on your brain. 

Fine it's a wart on my brain.  It's still a wart.

> Read Guido's arguments in favor of an 
> explicit self argument again before you assert this so confidently. 

I would if I could find it.  I'm sure he had good reasons, they may even
convince me.  But from my current perspective I disagree.  

> It's 
> certainly confusing to beginners, but there are actually quite sound
> reasons for it (see next paragraph).

While confusion for beginners is a problem, that's not such a big deal. 
It's a trivial fix that they see once and remember forever.  What I mind is
its ugliness, that the language makes me do work declaring self when it
knows damn well it won't like my code until I do what it wants (yes I'm
anthropomorphizing interpreters now).  The interpreter works for me, I
don't work for it.  Things it can figure out automatically, it should
handle.

 
> Hmm. I see. How would you then handle the use of unbound methods as
> first-class objects? If self is implicitly declared, that implies that
> methods can only be used when bound to instances.

I fail to see the problem here.  I'm taking about implicit declaration on
the receiving end.  It sounds like you're talking about implicit passing on
the sending end.  The two are orthogonal.  I can declare
def amethod (a, b):
and have self received implicitly (i.e. get the object instance bound by the
interpreter to the name self).  The sender still explicitly provides the
object instance, e.g.
obj.amethod (a,b)
or
class.amethod (obj, a, b)
IOW everything can still work exactly as it does now, only *without me
typing self* as the first parameter of every goddamn method I write.  Does
that make sense?

> How, otherwise, would 
> you have an instance call its superclass's __init__ method if it's no
> longer valid to say
> 
>  myClass(otherClass):
>  def __init__(self):
>  otherClass.__init__(self)
>  ...
> 

Like this:
  myClass(otherClass):
  def __init__():
  otherClass.__init__(self)

self is still there and still bound, I just don't have to type it out.  The
interpreter knows where it goes and what it does, automate it already!

>> * technically modules may be objects also, but in practice you don't
>> declare self as a parameter to module functions
> 
> The reason you don't do that is because the functions in a module are
> functions in a module, not methods of (some instance of) a class.
> Modules not only "may be" objects, they *are* objects, but the functions
> defined in them aren't methods. What, in Python, *isn't* an object?

If it looks like a duck and it quacks like a duck... Functions and methods
look different in their declaration but the calling syntax is the same. 
It's not obvious from the dot notation syntax where the 'self' argument
comes from.  Some interpreter magic goes on behind the scenes.  Great, I'm
all for it, now why not extend that magic a little bit further?

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


Re: set partitioning

2006-05-02 Thread Edward Elliott
[EMAIL PROTECTED] wrote:

> For the list [1,2,3,4], I'm looking for the following for k = 2:
> 
> [[1,2], [3,4]]
> [[1,3], [2,4]]
> [[1,4], [2,3]]

That's not what you asked for the first time.  You said you wanted "m
non-empty, disjoint subsets", but the subsets above are clearly not all
disjoint; only those on the same line are.  It sounds like what you really
want is the "powerset of non-empty, disjoint partitions of size k".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: returning none when it should be returning a list?

2006-05-02 Thread Christos Georgiou
On 1 May 2006 07:19:48 -0700, rumours say that [EMAIL PROTECTED] might
have written:

>I'm not sure what "falls off the end" of the function means, i searched
>online, it seems to mean that the function has reached the end
>prematurely and returned a default identifier to signal success or
>not.. Can you please explain what that means?

I think that you haven't grasped the fact that a chain of calls of a
recursive function needs a return for *every* invocation of the function
(but I could be wrong :)

Check the following function, analogous to your own:

>>> def f(x):
if x > 4:
print "   returning", x
return x
else:
print "   start recursion"
f(x+1)
print "   end recursion"


>>> print f(0)
   start recursion
   start recursion
   start recursion
   start recursion
   start recursion
   returning 5
   end recursion
   end recursion
   end recursion
   end recursion
   end recursion
None

Do you see why the function returns None?
-- 
TZOTZIOY, I speak England very best.
"Dear Paul,
please stop spamming us."
The Corinthians
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can Python kill a child process that keeps on running?

2006-05-02 Thread Edward Elliott
Serge Orlov wrote:
> I. Myself wrote:
>> Suppose it is supposed to run for one minute, but it just keeps going
>> and going.  Does Python have any way to kill it?
> 
> On linux it's pretty easy to do, just setup alarm signal. On windows
> it's not so trivial to the point you cannot do it using python.org
> distribution, you will need to poke in low level C API using win32

Can't you use a Timer thread and then send the runaway process a signal? 
Does Windows not have the equivalent of SIGHUP/SIGTERM/SIGKILL?

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


Re: stripping blanks

2006-05-02 Thread seeker
[EMAIL PROTECTED] wrote:
> hi
> i have a file test.dat eg
> 
> abcdefgh
> ijklmn
>  <-newline
> opqrs
> tuvwxyz
>   <---newline
> 
> I wish to print the contents of the file such that it appears:
> abcdefgh
> ijklmn
> opqrs
> tuvwxyz
> 
> here is what i did:
> f = open("test.dat")
> while 1:
> line = f.readline().rstrip("\n")
> if line == '':
> break
> #if not re.findall(r'^$',line):
> print line
> 
> but it always give me first 2 lines, ie
> abcdefgh
> ijklmn
> 
> What can i do to make it print all..?
> thanks
> 

Last suggestion I made was bad. Here is the new one. Hopefully thats 
correct.

f = open("test.dat")
  for line in f:
 printLine = line.rstrip("\n")
 if not printLine:
 continue
 print printLine
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Non-web-based templating system

2006-05-02 Thread Fuzzyman

[EMAIL PROTECTED] wrote:
> Hi,
>
> I'm creating a small application in Python that uses lists and
> dictionaries to create a rudimentary database. I'd like to create some
> "fill-in-the-blanks" reports from this data, ideally by taking an RTF
> or plaintext file as a template and replacing placeholder tags with my
> data.
> Are there any good pre-written systems that would allow me to do this?
>

Another option is the 'embedded_code.py' module used by `Firedrop2
`_ and `rest2web
`_.

It takes a text string as input and a namespace (dictionary) as input
and returns a text string.

It replaces single placeholders of the form :

<% name %>

It also executes chunks of embedded code in the namespace, and replaces
them with whatever the code prints to stdout. These are of the form :

<#
print name
if name2.startswith('something'):
print name2
#>

This is very useful for simple templating.

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/shareware.shtml


> Thanks,
>   - QS Computing.

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


Re: returning none when it should be returning a list?

2006-05-02 Thread Iain King

John Machin wrote:
>
> # Doh! Looks like recursion not necessary. Google 'eliminate tail
> recursion' :-)
>

I did, and found this:
http://www.biglist.com/lists/dssslist/archives/199907/msg00389.html
which explains that the Scheme compiler optimises (obvious) tail
recursion into iterative code.  I'm wondering if the python compiler
does the same?

Iain

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


Re: resume picking items from a previous list

2006-05-02 Thread Christos Georgiou
On 30 Apr 2006 05:33:39 -0700, rumours say that "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> might have written:

>
>kpp9c wrote:

>> For a time i pick from my songs, but i only play a few of the songs in
>> that list... now my wife, Jessica Alba, comes home, and i start playing
>> from Jessica's list of songs. After playing a few songs, Jessica, who
>> needs her beauty sleep, goes to bed, and i start my play loop which
>> starts picking from my songs again...

>Not sure I follow. Jessica goes to bed, and you... _listen to music_??

He said his *wife*, Jessica Alba.  There's *no* way you marry *anyone* you
won't get bored of eventually.
-- 
TZOTZIOY, I speak England very best.
"Dear Paul,
please stop spamming us."
The Corinthians
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can Python kill a child process that keeps on running?

2006-05-02 Thread Serge Orlov
Edward Elliott wrote:
> Serge Orlov wrote:
> > I. Myself wrote:
> >> Suppose it is supposed to run for one minute, but it just keeps going
> >> and going.  Does Python have any way to kill it?
> >
> > On linux it's pretty easy to do, just setup alarm signal. On windows
> > it's not so trivial to the point you cannot do it using python.org
> > distribution, you will need to poke in low level C API using win32
>
> Can't you use a Timer thread and then send the runaway process a signal?
> Does Windows not have the equivalent of SIGHUP/SIGTERM/SIGKILL?

Windows doesn't have signals, so os.kill (that should rather be called
os.send_signal) is not implemented on Windows. Perhaps os module should
have os.terminate(pid) that can be implemented on Windows.

You're right about timer thread, it's better, I didn't think of it
because of my lack of experience with threading module. The watchdog
process code in my second post is almost useless: it's complicated and
os.kill is not available on windows anyway :-( Time to rest.

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


Re: Using elementtree: replacing nodes

2006-05-02 Thread André
Fredrik Lundh wrote:
> André wrote:
>
> > I've started using elementtree and don't understand how to use it to
> > manipulate and replace nodes.

[snip]
It was mostly the following step which I couldn`t figure out...

> # 2) mutate the pre element
> pre.clear()
> pre.tag = "form"
> pre[:] = [form]
>
[snip]

> another approach is to build a parent map; see the parent_map code
> at
>
>http://effbot.org/zone/element.htm#the-element-type
> 


Thanks!

> 

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


Re: returning none when it should be returning a list?

2006-05-02 Thread Christos Georgiou
On 2 May 2006 03:03:45 -0700, rumours say that "Iain King"
<[EMAIL PROTECTED]> might have written:


>John Machin wrote:
>>
>> # Doh! Looks like recursion not necessary. Google 'eliminate tail
>> recursion' :-)

>
>I did, and found this:
>http://www.biglist.com/lists/dssslist/archives/199907/msg00389.html
>which explains that the Scheme compiler optimises (obvious) tail
>recursion into iterative code.  I'm wondering if the python compiler
>does the same?

No, it doesn't so far.

More info:

http://groups.google.com/groups/search?q=group%3Acomp.lang.python+tail+recursion+optimization&qt_s=Search>
-- 
TZOTZIOY, I speak England very best.
"Dear Paul,
please stop spamming us."
The Corinthians
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strip newlines and blanks

2006-05-02 Thread Sybren Stuvel
[EMAIL PROTECTED] enlightened us with:
> thanks..and sorry, i am using the web version of google groups and
> didn't find  an option i can edit my post

It's usenet, you can't edit posts.

> so i just removed it..

Which doesn't work at all. Stupid thing they allow you to try and
delete something on Google Groups, since removal of Usenet posts is
ignored by most Usetnet carriers.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Non-web-based templating system

2006-05-02 Thread Sybren Stuvel
[EMAIL PROTECTED] enlightened us with:
> I'm creating a small application in Python that uses lists and
> dictionaries to create a rudimentary database. I'd like to create
> some "fill-in-the-blanks" reports from this data, ideally by taking
> an RTF or plaintext file as a template and replacing placeholder
> tags with my data.

I'd go for Cheetah: http://www.cheetahtemplate.org/

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string.find first before location

2006-05-02 Thread Gary Wessle
Peter Otten <[EMAIL PROTECTED]> writes:

> Gary Wessle wrote:
> 
> > I have a string like this
> > 
> > text = "abc abc and Here and there"
> > I want to grab the first "abc" before "Here"
> > 
> > import string
> > string.find(text, "Here") # 
> > 
> > I am having a problem with the next step.
> 
> These days str methods are preferred over the string module's functions.
> 
> >>> text = "abc abc and Here and there"
> >>> here_pos = text.find("Here")
> >>> text.rfind("abc", 0, here_pos)
> 4
> 
> Peter

and what about when python 3.0 is released and those depreciated
functions like find and rfind are not supported. is there another
solution which is more permanent?

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


Re: stripping

2006-05-02 Thread Tim Williams
On 1 May 2006 23:20:56 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]
> wrote:hii have a file test.dat egabcdefghijklmn <-newline
opqrstuvwxyz  <---newlineI wish to print the contents of the file such that it appears:abcdefghijklmnopqrstuvwxyzhere is what i did:f = open("test.dat")
while 1:line = f.readline().rstrip("\n")if line == '':break#if not re.findall(r'^$',line):print linebut it always give me first 2 lines, ie
abcdefghijklmnWhat can i do to make it print all..?
The break is terminating the while loop after the first blank line,
replacing it with a continue would solve the problem in your script. 

However:

f = open("test.dat")
while 1:
line = f.readline().rstrip("\n")
if line:
 print line

is simpler and easier to read.   And:

>>> f = open("test.dat").read()  # read the whole file at once into string f
>>> print f.replace('\n\n','\n')
abcdefgh
ijklmn
opqrs
tuvwxyz

>>>

even simpler,  as long as the file isn't huge.

If you need the final newline removed, use:

>>>print f.replace('\n\n','\n')[:-1]
abcdefgh

ijklmn

opqrs

tuvwxyz

>>>

HTH :)





 

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

Re: stripping

2006-05-02 Thread Tim Williams
On 02/05/06, Tim Williams <[EMAIL PROTECTED]> wrote:
On 1 May 2006 23:20:56 -0700, 
[EMAIL PROTECTED] <[EMAIL PROTECTED]
> wrote:hii have a file test.dat eg


f = open("test.dat")
while 1:
line = f.readline().rstrip("\n")
if line:
 print line

is simpler and easier to read.   
Except for my obvious mistake, tThe while never terminates:

>>> for line in f:
...     line = line.rstrip("\n")
...     if line:
...         print line
... 
abcdefgh
ijklmn
opqrs
tuvwxyz

or even

>>> for line in open("test.dat"):
...     line = line.rstrip("\n")
...     if line:
...         print line
... 
abcdefgh
ijklmn
opqrs
tuvwxyz

:)


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

Re: string.find first before location

2006-05-02 Thread Peter Otten
Gary Wessle wrote:

>> These days str methods are preferred over the string module's functions.
>> 
>> >>> text = "abc abc and Here and there"
>> >>> here_pos = text.find("Here")
>> >>> text.rfind("abc", 0, here_pos)
>> 4
>> 
>> Peter
> 
> and what about when python 3.0 is released and those depreciated
> functions like find and rfind are not supported. is there another
> solution which is more permanent?

I think the functions may go away, the methods will stay; so I'm confident
the above will continue to work. 

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


Re: noob question: "TypeError" wrong number of args

2006-05-02 Thread bruno at modulix
Edward Elliott wrote:
> Holger wrote:
> 
>>oops, that was kinda embarrassing.
> 
> 
> It's really not.  You got a completely unhelpful error message saying you
> passed 2 args when you only passed one explicitly.  The fact the b is also
> an argument to b.addfile(f) is totally nonobvious until you know that 1) b
> is an object not a module*, and 2) objects pass references to themselves as
> the first argument to their methods.

Nope. It's the MethodType object (a descriptor) that wraps the function
that do the job. The object itself is totally unaware of this.

>  The syntax "b." is completely
> different from the syntax of any other type of parameter.
>
> The mismatch between the number of parameters declared in the method
> signature and the number of arguments actually passed

There's no mismatch at this level. The arguments passed to the *function
*object wrapped by the method actually matches the *function* signature.

> is nonobvious,
> unintuitive, and would trip up anybody who didn't already know what was
> going on.  It's ugly and confusing.  It's definitely a wart on the
> langauge.

I do agree that the error message is really unhelpful for newbies (now I
don't know how difficult/costly it would be to correct this).

> Making people pass 'self'

s/self/the instance/

> explicitly is stupid

No. It's actually a feature.


> because it always has to be
> the first argument, leading to these kinds of mistakes.  The compiler
> should handle it for you

I don't think this would be possible if we want to keep the full
dynamism of Python. How then could the compiler handle the following code ?

class MyObj(object):
  def __init__(self, name):
self.name = name

def someFunc(obj):
  try:
print obj.name
  except AttributeError:
print "obj %s has no name" % obj

import types
m = MyObj('parrot')
m.someMeth = types.MethodType(someFunc, obj, obj.__class__)
m.someMeth()

> - and no, explicit is not *always* better than
> implicit, just often and perhaps usually.  While it's easy to recognize
> once you know what's going on, that doesn't make it any less of a wart.
> 
> * technically modules may be objects also,

s/may be/are/

> but in practice you don't declare
> self as a parameter to module functions

def someOtherFunc():
  print "hello there"

m.someFunc = someOtherFunc
m.someFunc()


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: set partitioning

2006-05-02 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
> For the list [1,2,3,4], I'm looking for the following for k = 2:
> 
> [[1,2], [3,4]]
> [[1,3], [2,4]]
> [[1,4], [2,3]]
> 
> for k = 3:
> 
> [[1,2,3], [4]]
> [[1,2,4], [3]]
> [[1,3,4], [2]]
> [[2,3,4], [1]]
> 

def pickk(k,N,m=0) :
 if k==1 :
 return ((n,) for n in range(m,N))
 else :
 return ((n,)+more for more in pickk(k-1,N,m+1)
   for n in range(m,more[0]))

def partitionN(k,N) :
 subsets = [frozenset(S) for S in pickk(k,N)]
 def exhaust(rest,bound=0) :
 if len(rest) < k :
 if rest :
 yield [sorted(rest)]
 else :
 yield []
 for newbound in range(bound,len(subsets)) :
 S = subsets[newbound]
 if rest >= S :
 sS = [sorted(S)]
 for restpart in exhaust(rest-S,newbound+1) :
 yield sS+restpart
 return exhaust(set(range(N)))

partition = lambda k,S : [[[S[j] for j in S0] for S0 in P0]
  for P0 in partitionN(k,len(S))]

 >>> partition(2,[1,2,3,4])
[[[1, 2], [3, 4]], [[1, 3], [2, 4]], [[2, 3], [1, 4]]]
 >>> partition(3,[1,2,3,4])
[[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 3, 4], [2]], [[2, 3, 4], [1]]]


CAVEAT : insufficiently tested, not proved correct, uncommented, provided as is
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strip newlines and blanks

2006-05-02 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
> hi
> i have a file test.dat eg
> 
> abcdefgh
> ijklmn
>  <-newline
> opqrs
> tuvwxyz
> 
> 
> I wish to print the contents of the file such that it appears:
> abcdefgh
> ijklmn
> opqrs
> tuvwxyz
> 
> here is what i did:
> f = open("test.dat")
> while 1:
> line = f.readline().rstrip("\n")
> if line == '':
> break

break terminates the loop, so no more lines will be processed. Use 
continue, which ends only the current iteration of the loop. (Though you 
will need a separate test to terminate the loop when there are no more 
lines.)

You can iterate an open file directly; here is a shorter version:

for line in open('test.dat'):
   line = line.rstrip('\n')
   if line:
 print line

Kent

> print line
> 
> but it always give me first 2 lines, ie
> abcdefgh
> ijklmn
> 
> What can i do to make it print all w/o the newlines..? and what is the
> proper way to skip printing blank lines while iterating file contents?
> 
> thanks
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


pyqt v3.* and v4.*

2006-05-02 Thread Skink
Hi,

Is it possible to have both versions of pyqt (in my case 3.14.1 and 4.0)?

Version 3 is built using sip 4.2.1, version 4 is built using sip 4.4.3

When I run pyqt 4.0 (but with installed sip 4.2.1) I get:

from PyQt4 import QtCore, QtGui
TypeError: invalid argument to sipBadCatcherResult()

When I run pyqt 3.14 (but with installed sip 4.4.3) I get:

import qt
Segmentation fault


Both 3.14 and 4.0 work, but not when installed together.

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


Strange result with math.atan2()

2006-05-02 Thread Vedran Furač
I think that this results must be the same:

In [3]: math.atan2(-0.0,-1)
Out[3]: -3.1415926535897931

In [4]: math.atan2(-0,-1)
Out[4]: 3.1415926535897931

In [5]: -0 == -0.0
Out[5]: True


This is python 2.4.4c0 on Debian GNU/Linux.


Regards,

Vedran Furač


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

--version?

2006-05-02 Thread Paul Watson
Is there any chance that Python would support the --version command line 
  parameter?  It seems that many open source programs use this switch to 
report their version number.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython, wxcombobox opening

2006-05-02 Thread Philippe Martin
Hi,

>From the wxPython list:

> Hi,
> 
> Which event must I catch to be called when the user clicks on the combo 
> "button" to make the drop down list to appear ?

No, there isn't a specific event for the opening of the drop-down box.


Regards,

Philippe





Philippe Martin wrote:

> Hi,
> 
> I do not have the answer but am very interested in the issue. I tried
> this:
> 
> l_ev = wx.MouseEvent(wx.wxEVT_LEFT_DOWN)
> l_ev.SetEventObject(self.GetCombo())
> self.GetEventHandler().ProcessEvent(l_ev)
> 
> Which did send the event to the combo (which is in a pannel in my case) ..
> but that is apparently not the event that triggers the dropping of the
> list.
> 
> I posed elsewhere and will forward here any hint.
> 
> Philippe
> 
> 
> 
> Rony Steelandt wrote:
> 
>> Hi,
>> 
>> Does somebody knows a way to automaticely open the list part of a
>> wxCombobox when it gets the focus ?
>> 
>> tia,
>> 
>> Rony

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


Re: pyqt v3.* and v4.*

2006-05-02 Thread Phil Thompson
On Tuesday 02 May 2006 1:01 pm, Skink wrote:
> Hi,
>
> Is it possible to have both versions of pyqt (in my case 3.14.1 and 4.0)?

Yes - but not that version of PyQt3.

> Version 3 is built using sip 4.2.1, version 4 is built using sip 4.4.3
>
> When I run pyqt 4.0 (but with installed sip 4.2.1) I get:
>
> from PyQt4 import QtCore, QtGui
> TypeError: invalid argument to sipBadCatcherResult()
>
> When I run pyqt 3.14 (but with installed sip 4.4.3) I get:
>
> import qt
> Segmentation fault
>
>
> Both 3.14 and 4.0 work, but not when installed together.

Install the latest versions of PyQt3 and SIP.

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


Re: string.find first before location

2006-05-02 Thread Serge Orlov
Peter Otten wrote:
> Gary Wessle wrote:
>
> >> These days str methods are preferred over the string module's functions.
> >>
> >> >>> text = "abc abc and Here and there"
> >> >>> here_pos = text.find("Here")
> >> >>> text.rfind("abc", 0, here_pos)
> >> 4
> >>
> >> Peter
> >
> > and what about when python 3.0 is released and those depreciated
> > functions like find and rfind are not supported. is there another
> > solution which is more permanent?
>
> I think the functions may go away, the methods will stay; so I'm confident
> the above will continue to work.

find and rfind methods are in danger too. AFAIR they are to be replaced
by partion and rpartition methods. People who are worried about future
can continue to use index and rindex

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


Re: --version?

2006-05-02 Thread Adonis
Paul Watson wrote:
> Is there any chance that Python would support the --version command line 
>  parameter?  It seems that many open source programs use this switch to 
> report their version number.


try at a command prompt:
python -V

Hope this helps.

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


Re: string.find first before location

2006-05-02 Thread Peter Otten
Serge Orlov wrote:

> Peter Otten wrote:
>> Gary Wessle wrote:
>>
>> >> These days str methods are preferred over the string module's
>> >> functions.
>> >>
>> >> >>> text = "abc abc and Here and there"
>> >> >>> here_pos = text.find("Here")
>> >> >>> text.rfind("abc", 0, here_pos)
>> >> 4
>> >>
>> >> Peter
>> >
>> > and what about when python 3.0 is released and those depreciated
>> > functions like find and rfind are not supported. is there another
>> > solution which is more permanent?
>>
>> I think the functions may go away, the methods will stay; so I'm
>> confident the above will continue to work.
> 
> find and rfind methods are in danger too. AFAIR they are to be replaced
> by partion and rpartition methods. People who are worried about future
> can continue to use index and rindex

I really should read those PEPs before posting.

And just as I was starting to complain I noted that my original reply to
Gary is buggy -- excluding the last letter in the string from the rfind()
search if "Here" is not found is probably never the desired behaviour. So
r/index() is indeed superior here.

Peter

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


Re: pyqt v3.* and v4.*

2006-05-02 Thread Skink
Phil Thompson wrote:
> 
> 
> Install the latest versions of PyQt3 and SIP.

Thanks Phil!

v4.0 & v3.16 work with sip 4.4.3 ;)

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


Re: --version?

2006-05-02 Thread Paul Watson
Adonis wrote:
> Paul Watson wrote:
> 
>> Is there any chance that Python would support the --version command 
>> line  parameter?  It seems that many open source programs use this 
>> switch to report their version number.
> 
> 
> 
> try at a command prompt:
> python -V
> 
> Hope this helps.
> 
> Adonis

I am well aware of -V.  Could --version be supported as well?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange result with math.atan2()

2006-05-02 Thread Peter Otten
Vedran Fura? wrote:

> I think that this results must be the same:
> 
> In [3]: math.atan2(-0.0,-1)
> Out[3]: -3.1415926535897931
> 
> In [4]: math.atan2(-0,-1)
> Out[4]: 3.1415926535897931
> 
> In [5]: -0 == -0.0
> Out[5]: True

Glimpsing at the hardware formats:

>>> struct.pack("d", 0.0)
'\x00\x00\x00\x00\x00\x00\x00\x00'
>>> struct.pack("d", -0.0)
'\x00\x00\x00\x00\x00\x00\x00\x80'
>>> struct.pack("i", -0)
'\x00\x00\x00\x00'
>>> struct.pack("i", 0)
'\x00\x00\x00\x00'

-0 and +0 integers are identical while 0.0 and -0.0 floats are not. The
negative sign is therefore lost before the int --> float conversion takes
place.

Peter

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


produce xml documents with python, and display it with xsl in a internet browser

2006-05-02 Thread wyattroerb
Hi,
like a lot of other newbies in xml i suffer from the various ways you
can take for xml data processing in python.  Here are my two major
problems:
Problem number one:
A application written in python remote controls (demands actions) a HIL
(Hardware in the loop) test stand and evaluate its actions  (system
reactions on the demand ) afterwards. The application puts all the
results in a word protocol during the test. Now i would like to do the
next step and represent the results in a proper data type document (xml
- separate style from reference data). That means for python that it
is in charge of provideing the necessary  reference data for new xml
documents and maybe more (changing xsl sheets if new test data elements
were defined)?!?. I am not quite sure if it is better to specify a kind
of source/basic xml document  with all the >elements< and >attributes<
according to the defined test results. In that case python has to
modify the xml template with the new test results and save it as a new
xml document (to keep the base template unchanged fort he next test). I
suppose python could do the job with the help of DOM/SAX. I learned
from reports in certain forums that it is also possible to use simply
print statements. Does that mean i just have to do ordinary file
handling? For example:

f.open ("xml_file.xml", w)
f.write ("")
f.write (")
f.write ("")
f.write ("")
f.write ("")
.
.
.
f.close()

If it works in the ordinary way what is the advantage and what is the
disadvantage? Will I run in trouble if it comes to the transformation
of  tabs, and other xml related symbols.  I guess with the file method
i can create new elements and attributes in the python process/code
without taking care of the basic xml template. Maybe it is also
important to mention that i do not have the intention to process the
test data in python after the test again. I would like to give the
end-user (function developer in our lab) the possibility to check out
the test data results with a internet browser and here is my second
problem:
To accomplish this i made a base xsl file which includes Buttons to
give the end-user the possibility to call different xml templates (sort
of clicking through the xml tree/displaying data result fragments). The
trouble is that as far as i know the button feature ,,onclick" does
not allow to call  ,,xml:temlpates" just javascript functions. Is it
just possible to use javascript functions with DOM methods if i would
like to use buttons in html to extend and reduce displaying data from a
xml document? If this is the case then the xml:template functions in
xsl are useless, isn't it. I am quite sure that is not the case!


Sorry that i have so many stupid questions but a fool with a tool is
still a fool.
Anyway!  Many, many thanks for the slightest help.

wyatt

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


py2app, pythoncard build problems

2006-05-02 Thread loren . davie
Hi,

I'm attempting to build a small app that uses pythoncard for a gui
layer.  The intention is to use py2app to construct an .app bundle for
the Mac.  I'm running OS 10.4 on an Intel MacBook Pro.  I'm using the
default installed Python 2.3

The .app bundle appears to build, but when I start up it fails -
checking the console reveals that it can't find the "wx" package, as
its called from some pythoncard code.  (The app launches just fine in
non-bundled form when I run it from the command line using pythonw).

Not sure where to go with this.  Any help would be greatly appreciated
- thanks.

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


Re: Strange result with math.atan2()

2006-05-02 Thread Ben Caradoc-Davies
Vedran Furač wrote:
> I think that this results must be the same:
> In [3]: math.atan2(-0.0,-1)
> Out[3]: -3.1415926535897931
> In [4]: math.atan2(-0,-1)
> Out[4]: 3.1415926535897931

-0 is converted to 0, then to 0.0 for calculation, losing the sign. You 
might as well write 0.0 instead of -0

The behaviour of atan2 conforms to the ISO C99 standard (Python is 
implemented in C). Changing the sign of the first argument changes the 
sign of the output, with no special treatment for zero.

> In [5]: -0 == -0.0
> Out[5]: True

The constant -0 is an integer and is immediately converted to 0 (an 
integer). Two's-complement integers have no separate sign bit, and only 
one representation for zero. The integer -0 is identical in all respects 
to the integer 0

The constant -0.0 is a float, stored as an IEEE 754 bit pattern, and has 
a bit used to represent sign. The constants 0.0 and -0.0 compare equal, 
and both compare equal to 0, yet 0.0 and -0.0 have distinct bit patterns.

Because Python uses the C implementation of atan2, both arguments are 
converted to floats before calculation. -0 is converted to 0, then to 0.0

The behaviour of atan2 is mandated by ISO C99 (ISO/IEC 9899:1999). See 
the manuals of some implementers who tabulate these special values:

http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/atan2.3.html
http://www.ugcs.caltech.edu/manuals/libs/mpfr-2.2.0/mpfr_22.html

-- 
Ben Caradoc-Davies <[EMAIL PROTECTED]>
http://wintersun.org/
"Those who deny freedom to others deserve it not for themselves."
- Abraham Lincoln
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: --version?

2006-05-02 Thread gry
I agree.   The "--version" option has become quite a de-facto standard
in the linux world.  In my sys-admin role, I can blithely run
  initiate_global_thermonuclear_war --version
to find what version we have, even if I don't know what it does...

python --version

would be a very helpful addition. (Keep the "-V" too, if you like it
:-)

-- George

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


Pamie and Python - new browser focus

2006-05-02 Thread saltima

Hi all,

I'm trying to automate my web browser testing by using Pamie and
Python.

Everything is going great except for when a new window opens up. (on
the previous page, I click next, and a new window is opened up)

The focus it seems is never transferred. I suspect this because the
control is not being recognized.

Here's the line for the control on the new page.
ie.listBoxSelect('ddlOrType','1')

Here's the error msgs:

** elementFind() did not find select-name;id-ddlOrType
** listBoxSelect() did not find ddlOrType-1

I can't seem to figure this out.

Any ideas??

I would appreciate any help.

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


Re: set partitioning

2006-05-02 Thread Boris Borcic
I wrote:
> 
> def pickk(k,N,m=0) :
> if k==1 :
> return ((n,) for n in range(m,N))
> else :
> return ((n,)+more for more in pickk(k-1,N,m+1)
>   for n in range(m,more[0]))
> 
> def partitionN(k,N) :
> subsets = [frozenset(S) for S in pickk(k,N)]

while it doesn't otherwise change results, changing this line to

   subsets = [frozenset(S) for S in sorted(pickk(k,N))]

provides everything nicely ordered (e.g. lexicographically)

> def exhaust(rest,bound=0) :
> if len(rest) < k :
> if rest :
> yield [sorted(rest)]
> else :
> yield []
> for newbound in range(bound,len(subsets)) :
> S = subsets[newbound]
> if rest >= S :
> sS = [sorted(S)]
> for restpart in exhaust(rest-S,newbound+1) :
> yield sS+restpart
> return exhaust(set(range(N)))
> 
> partition = lambda k,S : [[[S[j] for j in S0] for S0 in P0]
>  for P0 in partitionN(k,len(S))]
> 
>  >>> partition(2,[1,2,3,4])
> [[[1, 2], [3, 4]], [[1, 3], [2, 4]], [[2, 3], [1, 4]]]
>  >>> partition(3,[1,2,3,4])
> [[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 3, 4], [2]], [[2, 3, 4], [1]]]
> 
> 
> CAVEAT : insufficiently tested, not proved correct, uncommented, 
> provided as is
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py2app, pythoncard build problems

2006-05-02 Thread Serge Orlov

[EMAIL PROTECTED] wrote:
> Hi,
>
> I'm attempting to build a small app that uses pythoncard for a gui
> layer.  The intention is to use py2app to construct an .app bundle for
> the Mac.  I'm running OS 10.4 on an Intel MacBook Pro.  I'm using the
> default installed Python 2.3
>
> The .app bundle appears to build, but when I start up it fails -
> checking the console reveals that it can't find the "wx" package, as
> its called from some pythoncard code.  (The app launches just fine in
> non-bundled form when I run it from the command line using pythonw).
>
> Not sure where to go with this.  Any help would be greatly appreciated

Most likely py2app analyzes code of pythoncard and cannot find
dependance on wx. As a quick workaround you can just insert "import wx"
in the beginning of your program where you import pythoncard. For a
more flexible solution you will need to read py2app docs how to force
bunding of a package from setup.py

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


Re: Strange result with math.atan2()

2006-05-02 Thread Vedran Furač
Ben Caradoc-Davies wrote:
> Vedran Furač wrote:
>> I think that this results must be the same:
>> In [3]: math.atan2(-0.0,-1)
>> Out[3]: -3.1415926535897931
>> In [4]: math.atan2(-0,-1)
>> Out[4]: 3.1415926535897931
> 
> -0 is converted to 0, then to 0.0 for calculation, losing the sign. You 
> might as well write 0.0 instead of -0
> 
> The behaviour of atan2 conforms to the ISO C99 standard (Python is 
> implemented in C). Changing the sign of the first argument changes the 
> sign of the output, with no special treatment for zero.
> 
> http://www.ugcs.caltech.edu/manuals/libs/mpfr-2.2.0/mpfr_22.html

Well, here I can read:

Special values are currently handled as described in the ISO C99 standard
for the atan2 function (note this may change in future versions):

* atan2(+0, -0) returns +Pi.
* atan2(-0, -0) returns -Pi. /* wrong too */
* atan2(+0, +0) returns +0.
* atan2(-0, +0) returns -0. /* wrong too */
* atan2(+0, x) returns +Pi for x < 0.
* atan2(-0, x) returns -Pi for x < 0


And the formula (also from that site):
if x < 0, atan2(y, x) = sign(y)*(PI - atan (abs(y/x)))
^^^

So, you can convert -0 to 0, but you must multiply the result with sign of
y, which is '-' (minus).

Also, octave:

octave2.9:1> atan2(-0,-1)
ans = -3.1416

or matlab:

>> atan2(-0,-5)

ans =

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

Re: --version?

2006-05-02 Thread Fredrik Lundh
Paul Watson wrote:

> I am well aware of -V.  Could --version be supported as well?

http://www.python.org/dev/
http://sourceforge.net/tracker/?group_id=5470&atid=355470





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


Re: Strange result with math.atan2()

2006-05-02 Thread Serge Orlov
Vedran Furac wrote:
> Ben Caradoc-Davies wrote:
> > Vedran Furac wrote:
> >> I think that this results must be the same:
> >> In [3]: math.atan2(-0.0,-1)
> >> Out[3]: -3.1415926535897931
> >> In [4]: math.atan2(-0,-1)
> >> Out[4]: 3.1415926535897931
> >
> > -0 is converted to 0, then to 0.0 for calculation, losing the sign. You
> > might as well write 0.0 instead of -0
> >
> > The behaviour of atan2 conforms to the ISO C99 standard (Python is
> > implemented in C). Changing the sign of the first argument changes the
> > sign of the output, with no special treatment for zero.
> >
> > http://www.ugcs.caltech.edu/manuals/libs/mpfr-2.2.0/mpfr_22.html
>
> Well, here I can read:
>
> Special values are currently handled as described in the ISO C99 standard
> for the atan2 function (note this may change in future versions):
>
> * atan2(+0, -0) returns +Pi.
> * atan2(-0, -0) returns -Pi. /* wrong too */
> * atan2(+0, +0) returns +0.
> * atan2(-0, +0) returns -0. /* wrong too */
> * atan2(+0, x) returns +Pi for x < 0.
> * atan2(-0, x) returns -Pi for x < 0
>   
>
> And the formula (also from that site):
>   if x < 0, atan2(y, x) = sign(y)*(PI - atan (abs(y/x)))
>   ^^^
>
> So, you can convert -0 to 0, but you must multiply the result with sign of
> y, which is '-' (minus).

But you miss the fact that 0 is an *integer*, not a float, and -0
doesn't exist.
Use this code until you stop passing integers to atan2:

from math import atan2 as math_atan2
def atan2(y, x):
if (isinstance(y, int) and y == 0) or (
isinstance(x, int) and x == 0):
raise ValueError("Argument that is an integer zero can \
produce wrong results")
return math_atan2(y, x)

print atan2(-0.0, -0.0)
print atan2(-0, -0)

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


Re: Possible constant assignment operators ":=" and "::=" for Python

2006-05-02 Thread Ben Sizer
[EMAIL PROTECTED] wrote:
> To begin with I'd like to apologize that I am not very experienced
> Python programmer so please forgive me if the following text does not
> make any sense.
>
> I have been missing constants in Python language. There are some
> workarounds available, for example the const-module. To me, this looks
> quite cumbersome and very unintuitive. For the interpreter, in the
> efficiency-wise, I just cannot tell.

The question is, why have you been missing them? Constants serve a
variety of purposes in other languages, some of which might not be
worthwhile in Python. There was a thread about 'symbols' a while back
which covers many of the uses of constants.

-- 
Ben Sizer

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


ConfigParser and multiple option names

2006-05-02 Thread Florian Lindner
Hello,
since ConfigParser does not seem to support multiple times the same option
name, like:

dir="/home/florian"
dir="/home/john"
dir="/home/whoever"

(only the last one is read in)

I wonder what the best way to work around this.

I think the best solution would be to use a seperation character:

dir="/home/florian, /home/john, home/whoever"

What character would be best to work on various operating systems? (of what
names may a path consist is the question)

What do you think? Any better ideas?

Thanks,

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


Re: wxPython, wxcombobox opening

2006-05-02 Thread Rony Steelandt
That is what I was afraid for

Thanks for answering,

Rony



> Hi,
>
> From the wxPython list:
>
>> Hi,
>> 
>> Which event must I catch to be called when the user clicks on the combo 
>> "button" to make the drop down list to appear ?
>
> No, there isn't a specific event for the opening of the drop-down box.
>
>
> Regards,
>
> Philippe
>
>
>
>
>
> Philippe Martin wrote:
>
>> Hi,
>> 
>> I do not have the answer but am very interested in the issue. I tried
>> this:
>> 
>> l_ev = wx.MouseEvent(wx.wxEVT_LEFT_DOWN)
>> l_ev.SetEventObject(self.GetCombo())
>> self.GetEventHandler().ProcessEvent(l_ev)
>> 
>> Which did send the event to the combo (which is in a pannel in my case) ..
>> but that is apparently not the event that triggers the dropping of the
>> list.
>> 
>> I posed elsewhere and will forward here any hint.
>> 
>> Philippe
>> 
>> 
>> 
>> Rony Steelandt wrote:
>> 
>>> Hi,
>>> 
>>> Does somebody knows a way to automaticely open the list part of a
>>> wxCombobox when it gets the focus ?
>>> 
>>> tia,
>>> 
>>> Rony


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


Re: Strange result with math.atan2()

2006-05-02 Thread Vedran Furač
Serge Orlov wrote:

>> So, you can convert -0 to 0, but you must multiply the result with sign of
>> y, which is '-' (minus).
> 
> But you miss the fact that 0 is an *integer*, not a float, and -0
> doesn't exist.

Yes, you are right, I completely missed that 0 is integer in python, and I
need a float.


Regards,

Vedran Furač
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: stripping blanks

2006-05-02 Thread Fulvio
Alle 17:06, martedì 02 maggio 2006, seeker ha scritto:
>      printLine = line.rstrip("\n")

I think that nobody considered if the text has (\r) or (\r\n) or (\n) at the 
end of the line(s).

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


Re: stripping blanks

2006-05-02 Thread Duncan Booth
Fulvio wrote:

> Alle 17:06, martedì 02 maggio 2006, seeker ha scritto:
>>      printLine = line.rstrip("\n")
> 
> I think that nobody considered if the text has (\r) or (\r\n) or (\n)
> at the end of the line(s).
> 
You think wrongly.

The suggested code opens the file in text mode so the line endings are 
automatically normalised to '\n'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bug in modulus?

2006-05-02 Thread Andrew Koenig
"Christophe" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> [EMAIL PROTECTED] a écrit :

> Floating point numbers just don't have the required precision to represent 
> 2.0 - 1e-050. For your specific problem, if you really want the result to 
> be < 2.0, the the best you can do is admit that floating point operations 
> have errors and return 0.0 when the modulus operation equals 2.0.

I disagree.  For any two floating-point numbers a and b, with b != 0, it is 
always possible to represent the exact value of a mod b as a floating-point 
number--at least on every floating-point system I have ever encountered. 
The implementation is not even that difficult.


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

Re: stripping blanks

2006-05-02 Thread Fredrik Lundh
Fulvio wrote:

> > printLine = line.rstrip("\n")
>
> I think that nobody considered if the text has (\r) or (\r\n) or (\n) at the
> end of the line(s).

if it's opened in text mode (the default), and is a text file, it will
always have "\n" at the end of the line.





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


Re: bug in modulus?

2006-05-02 Thread Andrew Koenig
"Andrew Koenig" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> I disagree.  For any two floating-point numbers a and b, with b != 0, it 
> is always possible to represent the exact value of a mod b as a 
> floating-point number--at least on every floating-point system I have ever 
> encountered. The implementation is not even that difficult.

Oops... This statement is true for the Fortran definition of modulus (result 
has the sign of the dividend) but not the Python definition (result has the 
sign of the divisor).  In the Python world, it's true only when the dividend 
and divisor have the same sign.


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


Re: ConfigParser and multiple option names

2006-05-02 Thread Alexis Roda
Florian Lindner escribió:
> I think the best solution would be to use a seperation character:
> 
> dir="/home/florian, /home/john, home/whoever"

RCS uses , in filenames

> What do you think? Any better ideas?

A bit ugly, but probably safer and simpler than adding arbitrary separators:

[section]
dir_1=/home/florian
dir_2=/home/john
dir_3=/home/whoever


a s(a|i)mple implementation to give you the idea, it has some bugs:

import ConfigParser
import re

class ConfigParserWithLists(ConfigParser.ConfigParser):
def setlist(self, section, option, value) :
for i, v in enumerate(value) :
self.set(section, '%s_%i' % (option, i + 1), v)

def getlist(self, section, option) :
res = []
m = re.compile('^' + option + '_\d+$').match
for oo in self.options(section) :
if m(oo) :
res.append(self.get(section, oo))
return res




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


Python and Windows new Powershell

2006-05-02 Thread BartlebyScrivener
The Windows Powershell is available, fka Monad.

Any special Python tricks? Just breezing through the manual, they
seemed to have borrowed from any language they wanted in making a new
scripting language.

http://tinyurl.com/l9ghj

rd

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


Re: ConfigParser and multiple option names

2006-05-02 Thread Florian Lindner
Alexis Roda wrote:

> Florian Lindner escribió:
>> I think the best solution would be to use a seperation character:
>> 
>> dir="/home/florian, /home/john, home/whoever"
> 
> RCS uses , in filenames

A kommata (,) is a valid character in path names. Ok, you can use quotes.

>> What do you think? Any better ideas?
> 
> A bit ugly, but probably safer and simpler than adding arbitrary
> separators:
> 
> [section]
> dir_1=/home/florian
> dir_2=/home/john
> dir_3=/home/whoever

I tend to use seperators, because I think it's more common to users. (the
PATH environment variable e.g.)
 
> a s(a|i)mple implementation to give you the idea, it has some bugs:
> 
[...]

Thanks for your input!

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

Re: ConfigParser and multiple option names

2006-05-02 Thread Larry Bates
Florian Lindner wrote:
> Hello,
> since ConfigParser does not seem to support multiple times the same option
> name, like:
> 
> dir="/home/florian"
> dir="/home/john"
> dir="/home/whoever"
> 
> (only the last one is read in)
> 
> I wonder what the best way to work around this.
> 
> I think the best solution would be to use a seperation character:
> 
> dir="/home/florian, /home/john, home/whoever"
> 
> What character would be best to work on various operating systems? (of what
> names may a path consist is the question)
> 
> What do you think? Any better ideas?
> 
> Thanks,
> 
> Florian

I would either use (not tested):

[directories]
dir_01="/home/florian"
dir_02="/home/john"
dir_03="/home/whoever"

and in my program do:

INI=ConfigParser.ConfigParser()
INI.read(inifilepath)

section="directories"
dirs=[x for x in INI.options(section) if x.startswith('dir_')]

or more easily:

[init]
dirs=/home/florian,/home/john,home/whoever

and in program do:

section="init"
dirs=INI.get(section, 'dirs',).split(',')

Which one to use depends on how many dirs you would be supporting.
If it is a lot, I like the first version.  If a few, the second
seems better.

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


milliseconds are not stored in the timestamp KInterbasDB + Firebird

2006-05-02 Thread Petr Jakes
I am trying to insert "timestamp" to the Firebird database using
standard library datetime module example given in the "KInterbasDB
Usage Guide" http://tinyurl.com/mplo4 , section "Example Programs
DATE/TIME/TIMESTAMP"

Even timestamp has the correct format before inserting to the database
(2006-26-2 17:25:34.940279 for example), milliseconds are not stored
and the database returns (2006,26,2,17,25,34). I have made some
Googling the whole afternoon to find if it is possible to configure
Firebird or KInterbasDB, but no success.

My environment: Fedora Core4, Firebird CS 1.5, Python 2.4.1,
KInterbasDB 3.2b1

Thanks for your advices.
Petr Jakes

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


RFC 822 continuations

2006-05-02 Thread Florian Lindner
Hello,
http://docs.python.org/lib/module-ConfigParser.html writes:

"with continuations in the style of RFC 822; "

what is meant with these continuations?

Thanks,

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


simultaneous assignment

2006-05-02 Thread John Salerno
Is there a way to assign multiple variables to the same value, but so 
that an identity test still evaluates to False?

e.g.:

 >>> w = x = y = z = False
 >>> w
False
 >>> x
False
 >>> w == x
True
 >>> w is x
True # not sure if this is harmful

The first line above is the only way I know to do it, but it seems to 
necessarily lead to the true identity test.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can Python kill a child process that keeps on running?

2006-05-02 Thread I. Myself
Steve Holden wrote:
> I. Myself wrote:
>> Serge Orlov wrote:
>>
>>> I. Myself wrote:
>>>  
>>>
 Suppose we spawn a child process with Popen.  I'm thinking of an
 executable file, like a compiled C program.
 Suppose it is supposed to run for one minute, but it just keeps going
 and going.  Does Python have any way to kill it?

 This is not hypothetical; I'm doing it now, and it's working pretty
 well, but I would like to be able to handle this run-on condition.  
 I'm
 using Windows 2000, but I want my program to be portable to linux.

>>>
>>> On linux it's pretty easy to do, just setup alarm signal. On windows
>>> it's not so trivial to the point you cannot do it using python.org
>>> distribution, you will need to poke in low level C API using win32
>>> extensions or ctypes. AFAIK twisted package 
>>> has some code to help you. Also take a look at buildbot sources
>>>  that uses twisted. Buildbot has the same
>>> problem as you have, it needs to kill run away or non-responding
>>> processes.
>>>  
>>
>> That is bad news.   Thanks anyway; bad news is better than no news.
>>
> Note, however, that ctypes is planned to be a part of the 2.5 
> distribution, so while there may not be a platform-independent way to 
> achieve your goals you will at leats be able to do so without external 
> extensions.
I'm an intermediate Python programmer.  Can you explain to me how ctypes 
will let me kill a child process?

Thanks,

Mitchell Timin

-- 
I'm proud of http://ANNEvolve.sourceforge.net.  If you want to write software,
or articles, or do testing or research for ANNEvolve, let me know.

Humans may know that my email address is: (but remove the 3 digit number)
zenguy at shaw666 dot ca


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


Re: RFC 822 continuations

2006-05-02 Thread Larry Bates
Florian Lindner wrote:
> Hello,
> http://docs.python.org/lib/module-ConfigParser.html writes:
> 
> "with continuations in the style of RFC 822; "
> 
> what is meant with these continuations?
> 
> Thanks,
> 
> Florian

>From ConfigParser source code:

Continuations are represented by an embedded newline then
leading whitespace.

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


xml-rpc and 64-bit ints?

2006-05-02 Thread Mark Harrison
I've got an API that deals with 64 bit int values.  Is there
any way of handling this smoothly?  Right now I'm casting
the values into and out of strings for the API.

If not, are there any nice alternatives to XML-RPC that
support this?

Many TIA!
Mark

-- 
Mark Harrison
Pixar Animation Studios
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous assignment

2006-05-02 Thread Diez B. Roggisch
John Salerno wrote:

> Is there a way to assign multiple variables to the same value, but so
> that an identity test still evaluates to False?
> 
> e.g.:
> 
>  >>> w = x = y = z = False
>  >>> w
> False
>  >>> x
> False
>  >>> w == x
> True
>  >>> w is x
> True # not sure if this is harmful
> 
> The first line above is the only way I know to do it, but it seems to
> necessarily lead to the true identity test.

Yes, and there is no way around that - given that python has not an
overloadable assignment operator as e.g. C++ offers (praise the BDFL!). The
semantics of what looks like assignment in python is "I've got a fancy
object somewhere, and now I want to be able to refer to it by that nice
name here". Actually things are somewhat more complicated in case of
list/dictionary element assignment, but for your case that is irrelevant.

Besides, depending on what you assign (e.g. integers, as well as the boolean
constants I guess) you might not even have the choice to guarantee how the
identity test results anyway. Consider this:

>>> a = 100
>>> b = 100
>>> a is b
False
>>> a = 100
>>> b = 100
>>> a is b
False
>>> a = 10
>>> b = 10
>>> a is b
True
>>>

I can't imagine what you're actually after here, but assuming that you
really need this and that we're talking "real" objects here, sequence
unpacking and assignment might come handy here, together with a small
list-comp:

a, b, c = [copy.copy(o) for i in xrange(3)]


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


Re: simultaneous assignment

2006-05-02 Thread Boris Borcic
John Salerno wrote:
> Is there a way to assign multiple variables to the same value, but so 
> that an identity test still evaluates to False?
> 
> e.g.:
> 
>  >>> w = x = y = z = False
>  >>> w
> False
>  >>> x
> False
>  >>> w == x
> True
>  >>> w is x
> True # not sure if this is harmful
> 
> The first line above is the only way I know to do it, but it seems to 
> necessarily lead to the true identity test.

 >>> class Foo :
def __eq__(*blah) : return False


 >>> w = x = y = z = Foo()
 >>> w ==  x
False
 >>> w is x
True
 >>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous assignment

2006-05-02 Thread John Salerno
Boris Borcic wrote:

>  >>> w ==  x
> False
>  >>> w is x
> True
>  >>>

That's the opposite of what I want to happen.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous assignment

2006-05-02 Thread John Salerno
Diez B. Roggisch wrote:

> I can't imagine what you're actually after here, but assuming that you
> really need this

Hard to explain because I'm still trying to figure out how to do it 
myself. I'm trying to solve a little puzzle using Python, even though 
I'm sure it's not necessary. Basically W, X, Y and Z are propositions 
that are either true or false, and the puzzle lists a few statements 
such as "Exactly one of X, Y and Z is true", and I'm trying to work out 
a little algorithm that might test for this kind of stuff.

Another thing I'm trying to do is write a function that tests to see if 
a list contains exactly one true item, and the rest are false (obviously 
this would have to be a list of boolean values, I guess). I'm sure this 
isn't a handy utility, but I enjoy figuring out how to implement it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous assignment

2006-05-02 Thread Diez B. Roggisch
John Salerno wrote:

> Diez B. Roggisch wrote:
> 
>> I can't imagine what you're actually after here, but assuming that you
>> really need this
> 
> Hard to explain because I'm still trying to figure out how to do it
> myself. I'm trying to solve a little puzzle using Python, even though
> I'm sure it's not necessary. Basically W, X, Y and Z are propositions
> that are either true or false, and the puzzle lists a few statements
> such as "Exactly one of X, Y and Z is true", and I'm trying to work out
> a little algorithm that might test for this kind of stuff.

Then use a Proposition-class that holds the actual value.
 
> Another thing I'm trying to do is write a function that tests to see if
> a list contains exactly one true item, and the rest are false (obviously
> this would have to be a list of boolean values, I guess).

No - you can for example override the comparison-semantics on the
Proposition-class to be comparable with True/False with the proper
semantics:




class Proposition(object):

def __init__(self, v):
self._v = v


def __eq__(self, o):
return self._v == o


TrueProposition = Proposition(True)
FalseProposition = Proposition(False)

print True == TrueProposition
print False == TrueProposition
print False == FalseProposition



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


Re: noob question: "TypeError" wrong number of args

2006-05-02 Thread Edward Elliott
bruno at modulix wrote:
>> that 1) b is an object not a module*, and 2) objects pass references to
>> themselves as the first argument to their methods.
> 
> Nope. It's the MethodType object (a descriptor) that wraps the function
> that do the job. The object itself is totally unaware of this.

It's shorthand, not to be taken literally.


>> Making people pass 'self'
> 
> s/self/the instance/
> 
>> explicitly is stupid
> 
> No. It's actually a feature.

potato, potahto.  


>> the first argument, leading to these kinds of mistakes.  The compiler
>> should handle it for you
> 
> I don't think this would be possible if we want to keep the full
> dynamism of Python. How then could the compiler handle the following code
> ?
> 
> class MyObj(object):
>   def __init__(self, name):
> self.name = name

class MyObj(object):
  def __init__(name):
self.name = name

And the rest should work fine.  When the interpreter sees a method
declaration, it can automatically 1) add the object instance parameter to
the signature, and 2) automatically bind the name self to the object
instance on dispatch.  Everything else is just as before.

>> but in practice you don't declare
>> self as a parameter to module functions
> 
> def someOtherFunc():
>   print "hello there"
> 
> m.someFunc = someOtherFunc
> m.someFunc()

Complete non-sequitor, what does this have to do with self?  

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


Re: bug in modulus?

2006-05-02 Thread Tim Peters
[Andrew Koenig, on the counter intuitive -1e-050 % 2.0 == 2.0 example]
>> I disagree.  For any two floating-point numbers a and b, with b != 0, it
>> is always possible to represent the exact value of a mod b as a
>> floating-point number--at least on every floating-point system I have ever
>> encountered. The implementation is not even that difficult.

[also Andrew]
> Oops... This statement is true for the Fortran definition of modulus (result
> has the sign of the dividend) but not the Python definition (result has the
> sign of the divisor).  In the Python world, it's true only when the dividend
> and divisor have the same sign.

Note that you can have it in Python too, by using math.fmod(a, b)
instead of "a % b".

IMO, it was a mistake (and partly my fault cuz I didn't whine early)
for Python to try to define % the same way for ints and floats.  The
hardware realities are too different, and so are the pragmatics.  For
floats, it's actually most useful most often to have both that a % b
is exact and that 0.0 <= abs(a % b) <= abs(b/2).  Then the sign of a%b
bears no relationship to the signs of a and b, but for purposes of
modular reduction it yields the result with the smallest possible
absolute value.  That's often valuable for floats (e.g., think of
argument reduction feeding into a series expansion, where time to
convergence typically depends on the magnitude of the input and
couldn't care less about the input's sign), but rarely useful for
ints.

I'd like to see this change in Python 3000.  Note that IBM's proposed
standard for decimal arithmetic (which Python's "decimal" module
implements) requires two operations here, one that works like
math.fmod(a, b) (exact and sign of a), and the other as described
above (exact and |a%b| <= |b/2|).  Those are really the only sane
definitions for a floating point modulo/remainder.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous assignment

2006-05-02 Thread John Salerno
Diez B. Roggisch wrote:

> Then use a Proposition-class that holds the actual value.
>  
>> Another thing I'm trying to do is write a function that tests to see if
>> a list contains exactly one true item, and the rest are false (obviously
>> this would have to be a list of boolean values, I guess).
> 
> No - you can for example override the comparison-semantics on the
> Proposition-class to be comparable with True/False with the proper
> semantics:

Hmm, classes still scare me a little, but I should consider this. The 
only thing is, it is not known in advance if the propositions are true 
or false, you have to figure that out yourself based on the combination 
of the statements given. I don't know if this changes the idea behind 
your Proposition class...I'll have to give it some more thought.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-3000] bug in modulus?

2006-05-02 Thread Guido van Rossum
This is way above my head. :-)

The only requirement *I* would like to see is that for floats that
exactly represent ints (or longs for that matter) the result ought of
x%y ought to have the same value as the same operation on the
corresponding ints (except if the result can't be represented exactly
as a float -- I don't know what's best then).

We're fixing this for / in Py3k, so passing an int into an algorithm
written for floats won't be harmful and won't require defensiev
float() casting everywhere. It would be a shame if we *introduced* a
new difference between ints and floats for %.

--Guido

On 5/2/06, Tim Peters <[EMAIL PROTECTED]> wrote:
> [Andrew Koenig, on the counter intuitive -1e-050 % 2.0 == 2.0 example]
> >> I disagree.  For any two floating-point numbers a and b, with b != 0, it
> >> is always possible to represent the exact value of a mod b as a
> >> floating-point number--at least on every floating-point system I have ever
> >> encountered. The implementation is not even that difficult.
>
> [also Andrew]
> > Oops... This statement is true for the Fortran definition of modulus (result
> > has the sign of the dividend) but not the Python definition (result has the
> > sign of the divisor).  In the Python world, it's true only when the dividend
> > and divisor have the same sign.
>
> Note that you can have it in Python too, by using math.fmod(a, b)
> instead of "a % b".
>
> IMO, it was a mistake (and partly my fault cuz I didn't whine early)
> for Python to try to define % the same way for ints and floats.  The
> hardware realities are too different, and so are the pragmatics.  For
> floats, it's actually most useful most often to have both that a % b
> is exact and that 0.0 <= abs(a % b) <= abs(b/2).  Then the sign of a%b
> bears no relationship to the signs of a and b, but for purposes of
> modular reduction it yields the result with the smallest possible
> absolute value.  That's often valuable for floats (e.g., think of
> argument reduction feeding into a series expansion, where time to
> convergence typically depends on the magnitude of the input and
> couldn't care less about the input's sign), but rarely useful for
> ints.
>
> I'd like to see this change in Python 3000.  Note that IBM's proposed
> standard for decimal arithmetic (which Python's "decimal" module
> implements) requires two operations here, one that works like
> math.fmod(a, b) (exact and sign of a), and the other as described
> above (exact and |a%b| <= |b/2|).  Those are really the only sane
> definitions for a floating point modulo/remainder.
> ___
> Python-3000 mailing list
> [email protected]
> http://mail.python.org/mailman/listinfo/python-3000
> Unsubscribe: 
> http://mail.python.org/mailman/options/python-3000/guido%40python.org
>


--
--Guido van Rossum (home page: http://www.python.org/~guido/)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous assignment

2006-05-02 Thread David Isaac

"John Salerno" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Is there a way to assign multiple variables to the same value, but so
> that an identity test still evaluates to False?

Make sure the value is not a singleton.
Assign them one at a time.
>>> w=1000
>>> x=1000
>>> w==x
True
>>> w is x
False
>>> w=2
>>> x=2
>>> w==x
True
>>> w is x
True

Hope that helps,
Alan Isaac


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


Re: simultaneous assignment

2006-05-02 Thread Diez B. Roggisch
> Hmm, classes still scare me a little, but I should consider this. The
> only thing is, it is not known in advance if the propositions are true
> or false, you have to figure that out yourself based on the combination
> of the statements given. I don't know if this changes the idea behind
> your Proposition class...I'll have to give it some more thought.

No, that was just an example to illustrate the comparison semantics. I don't
know enough about your problem to model it more appropriately.

Besides, you can of course change that self._v of a proposition.

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


Re: simultaneous assignment

2006-05-02 Thread bruno at modulix
John Salerno wrote:
> Is there a way to assign multiple variables to the same value,
> but so
> that an identity test still evaluates to False?

re-phrase it according to how Python works, and you'll get the answer:

"Is there a way to bind multiple names to the same object, but so the
identity of this object is different from the identity of this object ?"

> e.g.:
> 
 w = x = y = z = False

the statement:
  a = False
doesn't mean "assign the value False to the variable a", but "make the
name 'a' reference the object False" - which is quite different.

>>> a = False
>>> b = False
>>> a is b
True
>>> id(False)
46912499309888
>>> id(a)
46912499309888
>>> id(b)
46912499309888
>>>


 w
> False
 x
> False
 w == x
> True
 w is x
> True # not sure if this is harmful

Using identity test for boolean tests is usually not a good idea since
many other objects evals to True or False in a boolean context while not
being neither the True nor the False objects.

> The first line above is the only way I know to do it, but it seems to
> necessarily lead to the true identity test.

It does.

Now if I may ask: what is your actual problem ?

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous assignment

2006-05-02 Thread bruno at modulix
John Salerno wrote:
> Boris Borcic wrote:
> 
>>  >>> w ==  x
>> False
>>  >>> w is x
>> True
>>  >>>
> 
> 
> That's the opposite of what I want to happen.

And that wouldn't be really helpful anyway !-)

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Polling from keyboard

2006-05-02 Thread [EMAIL PROTECTED]
I am trying to find a way to poll the keyboard.  In my searching, I
have found that Windows users are given the msvcrt module.  Is there an
equivilant for Unix systems?

I am writing a p2p chat application, and would like to ideally approach
user input in a manner similar to the way I am using poll() to moniter
the sockets for events

thanks in advance

-- 
lucas

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


Re: using ftplib

2006-05-02 Thread Dave Hughes
Steve Holden wrote:

> John Salerno wrote:
> [...]
> > 
> > So if I already have files on the server and I want to change file
> > permissions, do I need to mess with TYPE A/TYPE I commands, or are
> > those  strictly for when you transfer files? Because I just did a
> > quick test  of changing file permissions through my FTP program,
> > and it still sent a  TYPE A command in the process. I know that the
> > retr and stor methods  might do this automatically, but if I don't
> > need to use those, and just  need to use transfercmd (assuming this
> > is the right method to use when  changing file permissions), do I
> > need to manually send a TYPE A/I  command as well?
> 
> The answer is "probably not", but a better answer is "try it in the
> interactive interpreter and see".

As far as I recall your speculation is indeed correct: a TYPE command
is only necessary before a transfer (it's only used to transform data
passing over the secondary data connection). I'm reasonably certain you
don't need *anything* before a SITE command (like SITE CHMOD), not even
PORT or PASV (unless the specific SITE command being invoked requires a
data transfer, which CHMOD shouldn't). But as Steve suggests, the best
way to know for sure is to give it a whirl and see what happens :-)

Incidentally, you might like to experiment with the command line ftp
client. On both Linux and Windows, the "quote" command can be used to
send commands "raw" to the FTP server. For example:

ftp> quote SITE CHMOD 755 afile.py


Dave.

-- 

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


Re: Polling from keyboard

2006-05-02 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> I am trying to find a way to poll the keyboard.  In my searching, I
> have found that Windows users are given the msvcrt module.  Is there an
> equivilant for Unix systems?
> 
> I am writing a p2p chat application, and would like to ideally approach
> user input in a manner similar to the way I am using poll() to moniter
> the sockets for events

I currently do that under Linux using /dev/input/*. However, that's for a
special case where we want several keyboards read simultaneously.

I guess what you want is a RAW-mode for your terminal, or alternatively the
event-system of your windowing system. Then you can get every keystroke.
But we need somewhat more information to be more helpful I fear.

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


Re: using ftplib

2006-05-02 Thread John Salerno
Dave Hughes wrote:

> As far as I recall your speculation is indeed correct: a TYPE command
> is only necessary before a transfer (it's only used to transform data
> passing over the secondary data connection). I'm reasonably certain you
> don't need *anything* before a SITE command (like SITE CHMOD), not even
> PORT or PASV (unless the specific SITE command being invoked requires a
> data transfer, which CHMOD shouldn't). But as Steve suggests, the best
> way to know for sure is to give it a whirl and see what happens :-)

Thanks. I sometimes forget I can experiment with the interactive 
interpreter, but I also didn't want to screw up anything on my server 
space by doing something weird! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous assignment

2006-05-02 Thread John Salerno
bruno at modulix wrote:

> Now if I may ask: what is your actual problem ?

Ok, since you're so curious. :)

Here's a scan of the page from the puzzle book:
http://johnjsalerno.com/spies.png

Basically I'm reading this book to give me little things to try out in 
Python. There's no guarantee that this puzzle is even conducive to (or 
worthy of) a programming solution.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unable to resize mmap object

2006-05-02 Thread Fabiano Sidler
On Sunday 30 April 2006 21:06, Serge Orlov wrote:
> Fabiano Sidler wrote:
>> Now, when I try to resize mm to 10 byte
>> --- snip ---
>> mm.resize(10)
>> --- snap ---
>> I get an EnvironmentError:[Errno 22] Invalid argument.
>
> Just a guess: try a new size argument that is multiple of page size.

No, doesn't work neitzer. :(

Thank you anyway for the idea!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SGML parsing tags and leeping track

2006-05-02 Thread hapaboy2059
could i make a global variable and keep track of each tag count?

Also how would i make a list or dictionary of tags that is found?
how can i handle any tag that is given?

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


Re: noob question: "TypeError" wrong number of args

2006-05-02 Thread bruno at modulix
Edward Elliott wrote:
> bruno at modulix wrote:
> 
>>>that 1) b is an object not a module*, and 2) objects pass references to
>>>themselves as the first argument to their methods.
>>
>>Nope. It's the MethodType object (a descriptor) that wraps the function
>>that do the job. The object itself is totally unaware of this.
> 
> 
> It's shorthand, not to be taken literally.
> 

It is to be taken literally. Either you talk about how Python
effectively works or the whole discussion is useless.

> 
>>>Making people pass 'self'
>>
>>s/self/the instance/
>>
>>
>>>explicitly is stupid
>>
>>No. It's actually a feature.
>  
> potato, potahto.  
> 

tss...

> 
>>>the first argument, leading to these kinds of mistakes.  The compiler
>>>should handle it for you
>
>>
>>I don't think this would be possible if we want to keep the full
>>dynamism of Python. How then could the compiler handle the following code
>>?
>>
>>class MyObj(object):
>>  def __init__(self, name):
>>self.name = name
> 
> 
> class MyObj(object):
>   def __init__(name):
> self.name = name

You skipped the interesting part, so I repost it and ask again: how
could the following code work without the instance being an explicit
parameter of the function to be used as a method ?

def someFunc(obj):
  try:
print obj.name
  except AttributeError:
print "obj %s has no name" % obj

import types
m = MyObj('parrot')
m.someMeth = types.MethodType(someFunc, obj, obj.__class__)
m.someMeth()

You see, wrapping a function into a method is not done at compile-time,
but at runtime. And it can be done manually outside a class statement.
In the above example, someFunc() can be used as a plain function.

In fact, almost any existing function taking at least one argument can
be turned into a method (in theory at least - practically, you of course
need to make sure the first argument is of a compatible type). This
wouldn't work with some automagical injection of the instance in the
function's local namespace, because you would then have to write
"method"'s code diffently from function's code.

> And the rest should work fine.  When the interpreter sees a method
> declaration,

The interpreter never sees a 'method declaration', since there is no
such thing as a 'method declaration' in Python. The def statement
creates a *function* object:

>>> class Parrot(object):
... def test(self):
... pass
... print "type(test) is : ", type(test)
...
type(test) is :  

>>>but in practice you don't declare
>>>self as a parameter to module functions
>>
>>def someOtherFunc():
>>  print "hello there"
>>
>>m.someFunc = someOtherFunc
>>m.someFunc()
>  
> Complete non-sequitor, what does this have to do with self?  

It has to do that the obj.name() syntax doesn't imply a *method* call -
it can as well be a plain function call. Also, and FWIW:
>>> def moduleFunc():
... print self.name
...
>>> moduleFunc()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 2, in moduleFunc
NameError: global name 'self' is not defined
>>>



HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous assignment

2006-05-02 Thread Steve R. Hastings
On Tue, 02 May 2006 17:15:05 +, John Salerno wrote:
> Basically W, X, Y and Z are propositions 
> that are either true or false, and the puzzle lists a few statements 
> such as "Exactly one of X, Y and Z is true", and I'm trying to work out 
> a little algorithm that might test for this kind of stuff.

Okay.  You don't need to worry about the "is" tests at all.


Python always represents the value "True" with a reference to a True
object, and likewise "False" is a reference to a False object.  To save
memory, Python has just one of each object, so:

a = False
b = False
a is b  # this will always be true


As some other posters showed by example, but didn't really explain, Python
will *sometimes* but not always reuse integer objects.  For common integer
values such as 0 and 1, Python will reuse the objects; for uncommon
(larger) values, Python usually won't.  So:

a = 12345
b = 12345
a is b  # probably not true
a = 0
b = 0
a is b  # always true


A key point is that you never really "assign a value to a variable".  What
you really do is "bind an object reference to a name".  The long,
simultaneous assignment form binds the same object reference to multiple
variables:

a = b = c = d = 12345
a is b  # always true


But as soon as you reassign any of the variables you will rebind the name
to some other object reference:

a += 1
a is b  # definitely false
a = 12345
a is b  # probably false


Python *could* notice that it already has an integer object with the value
12345, and rebind the name a with a reference to it.  But in practice
Python will probably just create a new integer object with value 12345,
since the Python interpreter doesn't spend large amounts of time looking
through its collection of objects to find ones that can be reused.

Python also has exactly one "None" object, and always uses references to
it whenever you reference None in your code.  This is why it is preferred
Python style to test for None with an "is" test:

a is None


Anyway, the major point I want you to take away from all this: it doesn't
matter whether the "is" test succeeds or fails, if all you care about is
the *value* of a variable.  Python reuses object references to save
memory, because this doesn't affect expressions that only care about the
*value*.  Your logic tests only care about True vs. False; they don't care
about the underlying implementation of how True and False are expressed.


> Another thing I'm trying to do is write a function that tests to see if 
> a list contains exactly one true item, and the rest are false (obviously 
> this would have to be a list of boolean values, I guess). I'm sure this 
> isn't a handy utility, but I enjoy figuring out how to implement it.

This is a simple problem.  I suggest you loop over the list and simply
count how many values are false, and how many are true.  I just wrote and
tested this function in about a minute.

The list doesn't have to be a list of booleans, actually.  Python has a
set of rules for evaluating other values as booleans:

if 0:
pass  # never executed; 0 always false

if "":
pass  # never executed; 0-length string always false

if []:
pass  # never executed; 0-length list always false


So, don't test to see if something is equal to True or False:

if 0 == False:
pass  # never executed; False and 0 do not directly compare


You *could* do this, but I don't really recommend it:

if bool(0) == False:
pass  # always executed


Do this:

if not 0:
pass  # always executed

if 1:
pass  # always executed


To convert a random value into a boolean value, you could use either
"bool()" or you could use "not not":

a = not not 0
b = bool(0)


"not not" will work on older versions of Python that didn't have an
explicit boolean type; "not 0" would return 1 in that case.  "bool()"
will work in Python 2.2 and newer.
-- 
Steve R. Hastings"Vita est"
[EMAIL PROTECTED]http://www.blarg.net/~steveha

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


Re: simultaneous assignment

2006-05-02 Thread John Salerno
Steve R. Hastings wrote:

> Anyway, the major point I want you to take away from all this: it doesn't
> matter whether the "is" test succeeds or fails, if all you care about is
> the *value* of a variable.  Python reuses object references to save
> memory, because this doesn't affect expressions that only care about the
> *value*.  Your logic tests only care about True vs. False; they don't care
> about the underlying implementation of how True and False are expressed.

Great explanation. Thanks!

> This is a simple problem.  I suggest you loop over the list and simply
> count how many values are false, and how many are true.  I just wrote and
> tested this function in about a minute.

Yeah, after trying some crazy things, I just wrote it this way:

def truth_test(seq):
 truth = 0
 for item in seq:
 if item:
 truth += 1
 if truth == 1:
 return True
 else:
 return False

Not sure I like having to keep a counter though, but the other stuff I 
did was really convoluted, like checking to see if the first item was 
True, and if it was, popping it from the list and iterating over the 
rest of the items (needless to say, the in-place change wasn't helpful).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-Monitor Support

2006-05-02 Thread Jesse Hager
Mark rainess wrote:
> Hello,
> 
> 
> Does Python or wxPython include any support for multiple monitors. In my
> application multiple monitors are located at a distance. It is not
> convenient to move a window from the main monitor to one of the others.
> I want to have the option to open an an application on any connected
> monitor. I am using wxPython. Does anyone know how to do it?
> 
> Thanks
> 
> Mark Rainess

import wx

app = wx.App()

#To get the count of displays
num_displays = wx.Display.GetCount()

#Open a frame on each display
for display_num in range(num_displays):
#Get a display object
display = wx.Display(display_num)

#To get a wx.Rect that gives the geometry of a display
geometry = display.GetGeometry()

#Create a frame on the display
frame = wx.Frame(None,-1,"Display %d"%display_num,
geometry.GetTopLeft(),geometry.GetSize())

#Make the frame visible
frame.Show()

app.MainLoop()

Creating a window on a different display is the same as creating one on
the main display, all you need to do is specify coordinates somewhere on
the alternate display when calling the constructor.

Use wx.Display to find out about the displays on the system, it also
lets you query and set the current video mode for a display.

Hope this helps.

-- 
Jesse Hager
email = "[EMAIL PROTECTED]".decode("rot13")
-- 
http://mail.python.org/mailman/listinfo/python-list


Wake on LAN and Shutdown for Windows and Linux

2006-05-02 Thread diffuser78
I am using 8 computers on a small network. I have one Main computer
which should be able to remotely start other computers. I used Wake on
LAN to start them all.

My Main computer is Linux.

Other 4 are Windows and 3 are Linux.

How can I shutdown Windows box from my Main (Linux) ?

Also, How can I shutdown other Linux terminals from my Main (Linux) ?


Help is appreciated.

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


Re: simultaneous assignment

2006-05-02 Thread Grant Edwards
On 2006-05-02, John Salerno <[EMAIL PROTECTED]> wrote:

> Yeah, after trying some crazy things, I just wrote it this way:
>
> def truth_test(seq):
>  truth = 0
>  for item in seq:
>  if item:
>  truth += 1
>  if truth == 1:
>  return True
>  else:
>  return False
>
> Not sure I like having to keep a counter though, but the other stuff I 
> did was really convoluted, like checking to see if the first item was 
> True, and if it was, popping it from the list and iterating over the 
> rest of the items (needless to say, the in-place change wasn't helpful).

Python knows how to count.  :)

def countFalse(seq):
return len([v for v in seq if not v])

def countTrue(seq):
return len([v for v in seq if v])

def truth_test(seq):
return countTrue(seq) == 1

-- 
Grant Edwards   grante Yow!  I FORGOT to do the
  at   DISHES!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stripping

2006-05-02 Thread Edward Elliott
[EMAIL PROTECTED] wrote:
> while 1:
> line = f.readline().rstrip("\n")
> if line == '':
> break
> #if not re.findall(r'^$',line):
> print line
 
you want continue, not break there.  but that gives you an infinite loop, so
you need a new exit condition.  you're better off scrapping the while and
using a for loop or list comprehension on readline.

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


Re: stripping

2006-05-02 Thread Jesse Hager
[EMAIL PROTECTED] wrote:
> hi
> i have a file test.dat eg
> 
> abcdefgh
> ijklmn
>  <-newline
> opqrs
> tuvwxyz
>   <---newline
> 
> 
> I wish to print the contents of the file such that it appears:
> abcdefgh
> ijklmn
> opqrs
> tuvwxyz
> 
> here is what i did:
> f = open("test.dat")
> while 1:
> line = f.readline().rstrip("\n")
> if line == '':
> break
> #if not re.findall(r'^$',line):
> print line
> 
> but it always give me first 2 lines, ie
> abcdefgh
> ijklmn
> 
> What can i do to make it print all..?
> thanks
> 
Change the 'break' statement to a 'continue'.

-- 
Jesse Hager
email = "[EMAIL PROTECTED]".decode("rot13")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous assignment

2006-05-02 Thread John Salerno
Grant Edwards wrote:

> Python knows how to count.  :)
> 
> def countFalse(seq):
> return len([v for v in seq if not v])
> 
> def countTrue(seq):
> return len([v for v in seq if v])
> 
> def truth_test(seq):
> return countTrue(seq) == 1

Gosh, so much to learn! Of course, I already know all about list 
comprehensions, but now I just need to learn to *use* them! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simultaneous assignment

2006-05-02 Thread Boris Borcic
Steve R. Hastings wrote:
> So, don't test to see if something is equal to True or False:
> 
> if 0 == False:
> pass  # never executed; False and 0 do not directly compare

of course they do - ie  isinstance(False,int) is True and False == 0

> 
> 
> You *could* do this, but I don't really recommend it:
> 
> if bool(0) == False:
> pass  # always executed
> 
> 
> Do this:
> 
> if not 0:
> pass  # always executed
> 
> if 1:
> pass  # always executed
> 
> 
> To convert a random value into a boolean value, you could use either
> "bool()" or you could use "not not":
> 
> a = not not 0
> b = bool(0)
> 
> 
> "not not" will work on older versions of Python that didn't have an
> explicit boolean type; "not 0" would return 1 in that case.  "bool()"
> will work in Python 2.2 and newer.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >