Re: os.wait() losing child?

2007-07-13 Thread Hrvoje Niksic
Jason Zheng <[EMAIL PROTECTED]> writes:

> Hrvoje Niksic wrote:
>>> greg wrote:
>> Actually, it's not that bad.  _cleanup only polls the instances that
>> are no longer referenced by user code, but still running.  If you hang
>> on to Popen instances, they won't be added to _active, and __init__
>> won't reap them (_active is only populated from Popen.__del__).
>>
>
> Perhaps that's the difference between Python 2.4 and 2.5.
[...]
> Nope it still doesn't work. I'm running python 2.4.4, tho.

That explains it, then, and also why greg's code didn't work.  You
still have the option to try to run 2.5's subprocess.py under 2.4.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function parameter type safety?

2007-07-13 Thread Bruno Desthuilliers
Robert Dailey a écrit :
> Hi,
> 
> Is there a way to force a specific parameter in a function to be a
> specific type?

No, and that's considered a GoodThing(tm).

> For example, say the first parameter in a function of
> mine is required to be a string.  If the user passes in an integer, I
> want to notify them that they should pass in a string, not an integer.
> 

Document the fact that the function expects a string as it's first 
param. If someone pass an int, it's likely that he'll soon find out 
there's something wrong (either from an exception or from obviously 
incoherent results). This is usually enough.

If you're in the case that passing a non-string will not raise an 
exception in the function but just lead to strange results or raise 
somewhere else, you can eventually use an assertion to ease debugging - 
but don't get into the habit of systematically type-check functions 
arguments, this would be fighting against the language.

My 2 cents...
-- 
http://mail.python.org/mailman/listinfo/python-list


Question about PyDict_SetItemString

2007-07-13 Thread lgx
Does PyDict_SetItemString(pDict,"key",PyString_FromString("value"))
cause memory leak?

>From Google results, I find some source code write like that. But some
code write like below:

obj =  PyString_FromString("value");
PyDict_SetItemString(pDict,"key",obj);
Py_DECREF(obj);

So, which one is correct?

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


Re: Question about PyDict_SetItemString

2007-07-13 Thread Stefan Behnel
lgx schrieb:
> Does PyDict_SetItemString(pDict,"key",PyString_FromString("value"))
> cause memory leak?

You shouldn't use that at all. If you look at the sources, what SetItemString
does is: create a Python string from the char* and call PyDict_SetItem() to
put the new string in. So it is actually much more efficient to use
PyDict_SetItem() directly in your case.

If you want to temporarily create a char* from a string and you know that the
char content won't be modified, use the PyString_FROM_STRING macro, which just
returns the internal pointer.

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


Re: How to create new files?

2007-07-13 Thread Hrvoje Niksic
Robert Dailey <[EMAIL PROTECTED]> writes:

> class filestream:
>   def __init__( self, filename ):
>   self.m_file = open( filename, "rwb" )
[...]
> So far, I've found that unlike with the C++ version of fopen(), the
> Python 'open()' call does not create the file for you when opened
> using the mode 'w'.

According to your code, you're not using 'w', you're using 'rwb'.  In
that respect Python's open behaves the same as C's fopen.

> Also, you might notice that my "self.m_file.read()" function is wrong,
> according to the python docs at least. read() takes the number of
> bytes to read, however I was not able to find a C++ equivalent of
> "sizeof()" in Python. If I wanted to read in a 1 byte, 2 byte, or 4
> byte value from data into python I have no idea how I would do this.

Simply read as much data as you need.  If you need to unpack external
data into Python object and vice versa, look at the struct module
(http://docs.python.org/lib/module-struct.html).
-- 
http://mail.python.org/mailman/listinfo/python-list


how to call bluebit...

2007-07-13 Thread 78ncp

helo...

i'm so glad can join to this website...

i want to ask..

how to import bluebit matrik calculator that result of singular value
decomposition (SVD) in python programming..

thank's for your answer.

-- 
View this message in context: 
http://www.nabble.com/how-to-call-bluebit...-tf4072919.html#a11575281
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Class decorators do not inherit properly

2007-07-13 Thread Bruno Desthuilliers
Chris Fonnesbeck a écrit :
> I have a class that does MCMC sampling (Python 2.5) that uses decorators 
> -- one in particular called _add_to_post that appends the output of the 
> decorated method to a class attribute.

> However, when I 
> subclass this base class, the decorator no longer works:
> 
> Traceback (most recent call last):
>   File "/Users/chris/Projects/CMR/closed.py", line 132, in 
> class M0(MetropolisHastings):
>   File "/Users/chris/Projects/CMR/closed.py", line 173, in M0
> @_add_to_post
> NameError: name '_add_to_post' is not defined
> 
> yet, when I look at the dict of the subclass (here called M0), I see the 
> decorator method:
> 
> In [5]: dir(M0)
> Out[5]: 
> ['__call__',
>  '__doc__',
>  '__init__',
>  '__module__',
>  '_add_to_post',
> ...
> 
> I dont see what the problem is here -- perhaps someone could shed 
> some light. I thought it might be the underscore preceding the name, 
> but I tried getting rid of it and that did not help.

A minimal runnable code snippet reproducing the problem would *really* 
help, you know...

Anyway: the body of a class statement is it's own namespace. So in the 
body of your base class, once the _add_to_post function is defined, you 
can use it. But when subclassing, the subclass's class statement creates 
a new namespace, in which _add_to_post is not defined - hence the 
NameError. To access this symbol, you need to use a qualified name, ie:

class SubClass(BaseClass):
   @BaseClass._add_to_post
   def some_method(self):
 # code here

Now there may be better solutions, but it's hard to tell without knowing 
more about your concrete use case.

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


Re: Class decorators do not inherit properly

2007-07-13 Thread Bruno Desthuilliers
Lee Harr a écrit :
>> Traceback (most recent call last):
>>   File "/Users/chris/Projects/CMR/closed.py", line 132, in 
>> class M0(MetropolisHastings):
>>   File "/Users/chris/Projects/CMR/closed.py", line 173, in M0
>> @_add_to_post
>> NameError: name '_add_to_post' is not defined
>>
>> yet, when I look at the dict of the subclass (here called M0), I see the 
>> decorator method:
>>
> 
> 
> I think the term "class decorator" is going to eventually
> mean something other than what you are doing here. I'd
> avoid the term for now.
> 
> 
> When you decorate a class method,
> the function you use
> needs to be defined before the method definition.

This is true whatever you are decorating - class method, static method, 
instance method, function. And FWIW, the term "class method" has a 
definite meaning in Python.

> Using a class method to decorate another class method is
> going to be tricky. The way I usually do it is to create
> a separate function outside of the class definition for
> the decorator function.

The problem is then that this function cannot easily access the class 
object - which is what the OP want.

> 
> You're going to have to show us the actual code you are
> having trouble with, or else (probably more useful, really)
> try to put together a minimal example of what you are
> trying to do and show us that code.

+1 on this

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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-13 Thread Paul Rubin
Ben Finney <[EMAIL PROTECTED]> writes:
> This is interesting. Do you have any references we can read about this
> assertion -- specifically, that "GOTO" was not well loved (I assume
> "by the programming community at large") even by around 1966?

Dijkstra's famous 1968 "GOTO considered harmful" letter
(http://www.acm.org/classics/oct95/) quotes a 1966 article by N. Wirth
and C.A.R. Hoare:

The remark about the undesirability of the go to statement is far from
new. I remember having read the explicit recommendation to restrict
the use of the go to statement to alarm exits, but I have not been
able to trace it; presumably, it has been made by C. A. R. Hoare. In
[1, Sec. 3.2.1.] Wirth and Hoare together make a remark in the same
direction in motivating the case construction: "Like the conditional,
it mirrors the dynamic structure of a program more clearly than go to
statements and switches, and it eliminates the need for introducing a
large number of labels in the program."

Reference: 1. Wirth, Niklaus, and Hoare C. A. R.  A contribution
to the development of ALGOL. Comm. ACM 9 (June 1966), 413-432.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-13 Thread Ben Finney
John Nagle <[EMAIL PROTECTED]> writes:

> Donn Cave wrote:
> > In its day, goto was of course very well loved.
>
> No, it wasn't.  By 1966 or so, "GOTO" was starting to look like a
> bad idea.  It was a huge hassle for debugging.

This is interesting. Do you have any references we can read about this
assertion -- specifically, that "GOTO" was not well loved (I assume
"by the programming community at large") even by around 1966?

-- 
 \ "It is not enough to have a good mind. The main thing is to use |
  `\  it well."  -- Rene Descartes |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to create new files?

2007-07-13 Thread Bruno Desthuilliers
Robert Dailey a écrit :
> Hi,
> 
> I'm trying to create a Python equivalent of the C++ "ifstream" class,
> with slight behavior changes.
> 
> Basically, I want to have a "filestream" object that will allow you to
> overload the '<<' and '>>' operators to stream out and stream in data,
> respectively. So far this is what I have:
> 
> class filestream:

class Filestream(object):

>   def __init__( self, filename ):
>   self.m_file = open( filename, "rwb" )

You don't need this C++ 'm_' prefix here - since the use of self is 
mandatory, it's already quite clear that it's an attribute.


> # def __del__( self ):
> # self.m_file.close()
> 
>   def __lshift__( self, data ):
>   self.m_file.write( data )
> 
>   def __rshift__( self, data ):
>   self.m_file.read( data )
> 
 >
> So far, I've found that unlike with the C++ version of fopen(), the
> Python 'open()' call does not create the file for you when opened
> using the mode 'w'. 

It does. But you're not using 'w', but 'rw'.

> I get an exception saying that the file doesn't
> exist.

Which is what happens when trying to open an inexistant file in read mode.

> I expected it would create the file for me. Is there a way to
> make open() create the file if it doesn't exist

yes : open it in write mode.

def __init__( self, filename ):
 try:
 self._file = open( filename, "rwb" )
 except IOError:
 # looks like filename doesn't exist
 f = open(filename, 'w')
 f.close()
 self._file = open( filename, "rwb" )


Or you can first test with os.path.exists:

def __init__( self, filename ):
 if not os.path.exists(filename):
 # looks like filename doesn't exist
 f = open(filename, 'w')
 f.close()
 self._file = open( filename, "rwb" )

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


Re: Fastest way to convert a byte of integer into a list

2007-07-13 Thread Paul McGuire
On Jul 12, 5:34 pm, Godzilla <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm trying to find a way to convert an integer (8-bits long for
> starters) and converting them to a list, e.g.:
>
> num = 255
> numList = [1,1,1,1,1,1,1,1]
>
> with the first element of the list being the least significant, so
> that i can keep appending to that list without having to worry about
> the size of the integer. I need to do this because some of the
> function call can return a 2 lots of 32-bit numbers. I have to find a
> way to transport this in a list... or is there a better way?

Standing on the shoulders of previous posters, I put this together.

-- Paul


# init list of tuples by byte
bytebits = lambda num : [num >> i & 1 for i in range(8)]
bytes = [ tuple(bytebits(i)) for i in range(256) ]

# use bytes lookup to get bits in a 32-bit integer
bits = lambda num : sum((bytes[num >> i & 255] for i in range(0,32,8)),
())

# use base-2 log to find how many bits in an integer of arbitrary
length
from math import log,ceil
log_of_2 = log(2)
numBits = lambda num : int(ceil(log(num)/log_of_2))

# expand bits to integers of arbitrary length
arbBits = lambda num : sum((bytes[num >> i & 255] for i in
range(0,numBits(num),8)),())

print arbBits((1<<34)-1)
print arbBits(37)

# prints
#(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
#(1, 0, 1, 0, 0, 1, 0, 0)

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


Re: Getting values out of a CSV

2007-07-13 Thread Daniel
>> > Note that every time you see [x for x in ...] with no condition, you  
>> can
>> > write list(...) instead - more clear, and faster.
>> >
>> > data = list(csv.reader(open('some.csv', 'rb')))
>>
>> Faster? No. List Comprehensions are faster.
>
> [EMAIL PROTECTED] pdfps $ python -m timeit -c 'data = list(open("make.ps"))'
> 100 loops, best of 3: 7.5 msec per loop
> [EMAIL PROTECTED] pdfps $ python -m timeit -c 'data = [line for line in
> open("make.ps")]'
> 100 loops, best of 3: 9.2 msec per loop
>
> On my system just putting into a list is faster.  I think this is
> because you don't need to assign each line to the variable 'line' each
> time in the former case.
>
> I, too, think it's faster to just use list() instead of 'line for line
> in iterable', as it seems kind of redundant.
>

$ python -m timeit -c 'import csv; data = list(csv.reader(open("some.csv",  
"rb")))'
1 loops, best of 3: 44 usec per loop
$ python -m timeit -c 'import csv; data = [row for row in  
csv.reader(open("some.csv", "rb"))]'
1 loops, best of 3: 37 usec per loop

I don't know why there seems to be a differece, but I know that list comps  
are python are very heavily optimised.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fast powerset function

2007-07-13 Thread Carsten Haese
On 13 Jul 2007 02:25:59 -0700, Paul Rubin wrote
> Antoon Pardon <[EMAIL PROTECTED]> writes:
> > On 7/12/07, Arash Arfaee <[EMAIL PROTECTED]> wrote:
> > > I need a powerset generator function. It's really slow with recursion. 
> > > Does
> > > anybody have any idea or code(!!) to do it in an acceptable time?
> > My idea would be the following. ...
> > 3) let n range from 0 to 2 ** lng
> 
> That may help a little but my guess is the slowness comes from
> the size (2**n) of the power set.

That's true if by "a little bit" you mean "a lot." Observe:

"""
def recursive_powerset(s):
if not s: yield set()
for x in s:
s2 = s - set([x])
for subset in recursive_powerset(s2):
yield subset
for subset in recursive_powerset(s2):
yield subset.union(set([x]))

def nonrecursive_powerset(s):
# Four lines of code hidden.
# I want the OP to figure this out for himself.

import time

print "   N Recursive Non-Recursive"
print "   - - -"
for n in range(8):
t1 = time.time()
x = list(recursive_powerset(set(range(n
t2 = time.time()
x = list(nonrecursive_powerset(set(range(n
t3 = time.time()
print "%4d %12.6fs %12.6fs" % (n,t2-t1,t3-t2)
"""

Results:

   N Recursive Non-Recursive
   - - -
   0 0.29s 0.26s
   1 0.27s 0.28s
   2 0.63s 0.36s
   3 0.000379s 0.67s
   4 0.004795s 0.000191s
   5 0.045020s 0.001054s
   6 0.633989s 0.013931s
   714.881078s 0.212958s

It is correct that a power set algorithm can never be truly fast because the
run time is exponential by definition, but the non-recursive (iterative)
method is still a lot faster than the recursive method.

-Carsten

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


Re: MaildirMessage

2007-07-13 Thread Steve Holden
Ben Finney wrote:
> "Gabriel Genellina" <[EMAIL PROTECTED]> writes:
> 
>> msg is an instance of MaildirMessage (subclass of Message) - it has
>> no specific iterator, so "for m in msg" tries to use the sequence
>> protocol, starting at 0; that is, tries to get msg[0]. Message
>> objects support the mapping protocol, and msg[0] tries to find a
>> *header* 0, converting the name 0 to lowercase, and fails miserably.
> 
> Which is a bug in the 'email.message' module, in my view. If it's
> attempting to support a mapping protocol, it should allow iteration
> the same way standard Python mappings do: by iterating over the keys.
> 
Stop assuming that everyone sees requirements the same as you - the 
author of the email module has long years of experience, and has 
provided an excellent and overall usable piece of software.

Criticisms such as yours are easy (we can all experess our opinions, to 
which we are all entitled), but mere expression of an opinion isn't 
going to change anything. Instead, change the module to do what you 
think it should. Then you can at least use it yourself, and if your code 
is a genuine improvement you can submit it as a patch.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: The Modernization of Emacs: terminology buffer and keybinding

2007-07-13 Thread Steve Holden
Twisted wrote:

[on 7/7/07]: I don't know, but it sure as hell isn't emacs.

Then, more recently:

> On Jul 12, 7:10 pm, Miles Bader <[EMAIL PROTECTED]> wrote:
>> Twisted <[EMAIL PROTECTED]> writes:
>>> I won't dignify your insulting twaddle and random ad-hominem verbiage
>>> with any more responses after this one. Something with actual logical
>>> argumentation to rebut may be another matter of course.
>> Er, why don't you just answer his question (what version)?  He's asking
>> for actual information, which will help us understand what you are
>> (trying) to to say.
>>
>> If you continue to just make vague and unsupported (and rather hostile)
>> assertions, without examples, version numbers, or other concrete
>> information, do you expect anybody will continue listening to you?
> 
> Some people can't let sleeping dogs lie I guess.
> 
That would be yourself you are describing, I presume?

> I can't remember the specific version after all these years. It may
> have been 18 or 19 point something. As for "concrete information" this
> thread is littered with fairly specific anecdotes. I know, I know;
> anecdotes aren't really proof of anything. Got any better suggestions?
> HCI stuff is a bit slippery to try to hang a rigorous theory and
> quantitative facts upon. For most people, a crappy interface isn't
> something they can precisely define, but they know it when they see it
> (or at least try to use it).
> 
If your usage of emacs has to be qualified by "after all these years" 
then you should not have made pejorative remarks about it without 
expecting others whose experience is more recent to correct (or at ;east 
disagree with) you.

Or do you just like the sound of your fingers on the keyboard? ;-)

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: scripts into wxPython

2007-07-13 Thread kyosohma
On Jul 13, 7:39 am, justme <[EMAIL PROTECTED]> wrote:
> Hello
>
> I've been happily scripting away for the last few years (Matlab, now
> Python) and all has been fine. Now I find myself scripting up code for
> clients, but they all want a nice GUI. I've had a tinker with wxPython
> and it all seems standard enough but I was wondering if anyone has any
> comments about how easy it is to shoehorn some fairly complex scripts
> into a GUI so that non-scripters can use the code. I assume I'll need
> to recode up all the input outputs?
>
> Any thoughts, or should I have started GUI programming right at the
> outset!
>
> Cheers

Yup! To get the inputs, you'll have to redo them in wxPython. But it's
not a big deal. If you're outputs are print statements than you can
just redirect stdout to a textctrl in wxPython and you won't need to
do too much there. Most of the backend complex stuff won't need any
changing or very little as long as it was written in a refactored /
stand-alone fashion.

Mike

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


Re: Getting values out of a CSV

2007-07-13 Thread Marc 'BlackJack' Rintsch
On Fri, 13 Jul 2007 15:05:29 +0300, Daniel wrote:

>>> > Note that every time you see [x for x in ...] with no condition, you  
>>> can
>>> > write list(...) instead - more clear, and faster.
>>> >
>>> > data = list(csv.reader(open('some.csv', 'rb')))
>>>
>>> Faster? No. List Comprehensions are faster.
>>
>> [EMAIL PROTECTED] pdfps $ python -m timeit -c 'data = list(open("make.ps"))'
>> 100 loops, best of 3: 7.5 msec per loop
>> [EMAIL PROTECTED] pdfps $ python -m timeit -c 'data = [line for line in
>> open("make.ps")]'
>> 100 loops, best of 3: 9.2 msec per loop
>>
>> On my system just putting into a list is faster.  I think this is
>> because you don't need to assign each line to the variable 'line' each
>> time in the former case.
>>
>> I, too, think it's faster to just use list() instead of 'line for line
>> in iterable', as it seems kind of redundant.
>>
> 
> $ python -m timeit -c 'import csv; data = list(csv.reader(open("some.csv",  
> "rb")))'
> 1 loops, best of 3: 44 usec per loop
> $ python -m timeit -c 'import csv; data = [row for row in  
> csv.reader(open("some.csv", "rb"))]'
> 1 loops, best of 3: 37 usec per loop
> 
> I don't know why there seems to be a differece, but I know that list comps  
> are python are very heavily optimised.

Does the machine use power saving features like SpeedStep or
something similar, i.e. runs the processor always with 100% speed or is it
dynamically stepped if there's load on the processor?  Do both tests read
the data always from cache or has the very first loop had to fetch the CSV
file from disk?

$ python -m timeit -n 1000 -c 'import csv; data = [row for row in
csv.reader(open("test.csv", "rb"))]' 1000 loops, best of 3: 1.27 msec per
loop

$ python -m timeit -n 1000 -c 'import csv; data =
list(csv.reader(open("test.csv", "rb")))' 1000 loops, best of 3: 1.25 msec
per loop

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: web page text extractor

2007-07-13 Thread kublai
On Jul 13, 5:44 pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Jul 12, 4:42 am, kublai <[EMAIL PROTECTED]> wrote:
>
> > Hello,
>
> > For a project, I need to develop a corpus of online news stories.  I'm
> > looking for an application that, given the url of a web page, "copies"
> > the rendered text of the web page (not the source HTNL text), opens a
> > text editor (Notepad), and displays the copied text for the user to
> > examine and save into a text file. Graphics and sidebars to be
> > ignored. The examples I have come across are much too complex for me
> > to customize for this simple job. Can anyone lead me to the right
> > direction?
>
> > Thanks,
> > gk
>
> One of the examples provided with pyparsing is an HTML stripper - view
> it online athttp://pyparsing.wikispaces.com/space/showimage/htmlStripper.py.
>
> -- Paul

Stripping tags is indeed one strategy that came to mind. I'm wondering
how much information (for example, paragraphing) would be lost, and if
what would be lost would be acceptable (to the project). I looked at
pyparsing and I see that it's got a lot of text processing
capabilities that I can use along the way. I sure will try it. Thanks
for the post.

Best,
gk

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


Re: The Modernization of Emacs: terminology buffer and

2007-07-13 Thread Gabor Urban

Hullo,

I was just wondering if this thread was whithering out.. I gues not for
a good time.

A short summary in the hope for the last posting in this topic.

Some provocative posting caused or Twister brother to send a large amount of
doubtful info. It seems, he had some very bad experience with an undefined
version of so called 'emacs'. Or he was not able to win against his
prejudice. On the other hand most of the users of the true, standard and
canonical Emacs (and Xemacs as well) were able to point out his factual
errors and misconceptions. (BTW Xemacs is not for X11... just eXtended..
:-)) )

But, for God's sake this is Python list. Would like to stick to it?

Back to Python... which version is to be used in production environment?

Sincerely yours,

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

pytz giving incorrect offset and timezone

2007-07-13 Thread Sanjay
Hi All,

I am facing some strange problem in pytz.

The timezone "Asia/Calcutta" is actually IST, which is GMT + 5:30. But
while using pytz, it is being recognized as HMT (GMT + 5:53). While I
digged into the oslan database, I see the following:

# Zone NAME GMTOFF RULES FORMAT [UNTIL]
Zone Asia/Calcutta 5:53:28 - LMT 1880 # Kolkata
   5:53:20 - HMT 1941 Oct # Howrah Mean Time?
   6:30 - BURT 1942 May 15 # Burma Time
   5:30 - IST 1942 Sep
   5:30 1:00 IST 1945 Oct 15
   5:30 - IST

A similar problem is also posted at
http://groups.google.co.in/group/comp.lang.python/browse_thread/thread/55496e85797ac890
without any responnses.

Unable to know how to proceed. Needing help. Tried posting in
launchpad and mailed to Stuart, but yet to get any response.

thanks
Sanjay

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


Writing a Python manual for Poser 7. Advice required re copyright/license

2007-07-13 Thread PhilC
Hi Folks,

I'm attempting to write a comprehensive manual explaining how to write
Python scripts for the Poser 7 application. All the example scripts,
explanatory paragraphs and screen shots will naturally be all my own
work. My difficulty is in knowing how I may present the large amount
of tabulated data that lists out all the Tkinter functions and their
options. I'm familiar with Fredrik Lundh's "An Introduction to
Tkinter" at http://effbot.org/tkinterbook/ but would not wish to
blindly copy the tables. However there are only so many ways to type:-

"background= 
The background color. The default is system specific."

The manual may be published in book form so may not be free. Does
anyone have contact information for Mr Lundh in order that I might
perhaps send him a draft copy for his comment?

Many thanks,

PhilC

http://www.philc.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to call bluebit...

2007-07-13 Thread Daniel Nogradi
> how to import bluebit matrik calculator that result of singular value
> decomposition (SVD) in python programming..

I'm not really sure I understand you but you might want to check out scipy:

http://scipy.org/

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


Re: Assignments to __class_ broken in Python 2.5?

2007-07-13 Thread samwyse
(Yes, I probably should have said CPython in my subject, not Python.
Sorry.)

On Jul 13, 12:56 am, samwyse <[EMAIL PROTECTED]> wrote:

> OK, in classobject.h, we find this:
>
> #define PyClass_Check(op) ((op)->ob_type == &PyClass_Type)
>
> That seems straightforward enough.  And the relevant message appears
> in classobject.c here:
>
> static int
> instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
> [...]
> if (strcmp(sname, "__class__") == 0) {
> if (v == NULL || !PyClass_Check(v)) {
> PyErr_SetString(PyExc_TypeError,
>"__class__ must be set to a class");
> return -1;
> }
>
> Back in our test code, we got these:
>
> > Empty = 
> > Excpt = 
>
> The first class (Empty) passes the PyClass_Check macro, the second one
> (Excpt) evidently fails.  I'll need to dig deeper.  Meanwhile, I still
> have to wonder why the code doesn't allow __class_ to be assigned a
> type instead of a class.  Why can't we do this in the C code (assuming
> the appropriate PyType_Check macro):
>
> if (v == NULL || !(PyClass_Check(v) || PyType_Check(v))) {

After a good night's sleep, I can see that Empty is a "real" class;
i.e. its repr() is handled by class_repr() in classobject.c.  Excpt,
on the other hand, is a type; i.e. its repr is handled by type_repr()
in typeobject.c.  (You can tell because class_repr() returns a value
formatted as "" whereas type_repr returns a value
formatted as "<%s '%s.%s'>", where the first %s gets filled with
either "type" or "class".)

This is looking more and more like a failure to abide by PEP 252/253.
I think that the patch is simple, but I'm unusre of the
ramifications.  I also haven't looked at the 2.4 source to see how
things used to work.  Still, I think that I've got a work-around for
OP's problem, I just need to test it under both 2.4 and 2.5.

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


Re: variable naming query

2007-07-13 Thread Neil Cerutti
On 2007-07-12, Ben Finney <[EMAIL PROTECTED]> wrote:
>> self.__myvariable
>
> Indicates to the reader that the attribute '__myvariable' is
> not available by that name outside the object, and name
> mangling is automatically done to discourage its use from
> outside the object.

>From _Python Reference Manual (2.3.2) Reserved Classes of
Identifiers:
  
  __* 

  Class-private names. Names in this category, when used
  within the context of a class definition, are re-written to
  use a mangled form to help avoid name clashes between
  ``private'' attributes of base and derived classes.

Further, from the _Python Tutorial (9.6) Private Variables_:

  (Buglet: derivation of a class with the same name as the base
  class makes use of private variables of the base class
  possible.) 

In other words, it's a misfeature that's best avoided.

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


Re: diferent answers with isalpha()

2007-07-13 Thread nuno
On Jul 13, 6:07 am, Jyotirmoy Bhattacharya <[EMAIL PROTECTED]>
wrote:
> On Jul 13, 5:05 am, [EMAIL PROTECTED] wrote:
>
> > In Idle when I do print 'á'.isalpha() I get True. When I make and
> > execute a script file with the same code I get False.
>
> > Why do I have diferent answers ?
>
> Non-ASCII characters in ordinary (8-bit) strings have all kinds of
> strangeness. First, the answer of isalpha() and friends depends on the
> current locale. By default, Python uses the "C" locale where the
> alphabetic characters are a-zA-z only. To set the locale to whatever
> is the OS setting for the current user, put this near the beginning of
> your script:
>
> import locale
> locale.setlocale(locale.LC_ALL,'')
>
> Apparently IDLE does this for you. Hence the discrepancy you noted.
>
> Second, there is the matter of encoding. String literals like the one
> you used in your example are stored in whatever encoding your text
> editor chose to store your program in. If it doesn't match the
> encoding using by the current locale, once again the program fails.
>
> As I see it, the only way to properly handle characters outside the
> ASCII set is to use Unicode strings.

Jyotirmoy,

You are right. Thank you for your information.

I will follow your advice but it gets me into another problem with
string.maketrans/translate that I can't solve.

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


Re: bool behavior in Python 3000?

2007-07-13 Thread Bruno Desthuilliers
Miles a écrit :
> On Jul 12, 8:37 pm, Alan Isaac <[EMAIL PROTECTED]> wrote:
>> I do not like that bool(False-True) is True.
> 
> I've never seen the "A-B" used to represent "A and not B", nor have I
> seen any other operator used for that purpose in boolean algebra,
> though my experience is limited.  Where have you seen it used?

I've personnaly seen the usual arithmatic operators used for boolean 
algebra in quite a lot of papers covering the topic - but I've always 
had to translate them to more common boolean ops to understand these 
papers.

> What's wrong with 'and', 'or', and 'not'?  I think that redefining *,
> +, and - to return booleans would only encourage programmers to use
> them as shortcuts for standard boolean operations--I'd hate to see
> code like this:
 if user.registered * (user.age > 13) - user.banned: ...
> 

OMG ! Lord have mercy ! St Guido, save us !

> I don't mind that arithmatic operations are _possible_ with bools, but
> I would strongly prefer to see the boolean keywords used for
> operations on booleans.

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


Re: bool behavior in Python 3000?

2007-07-13 Thread Bruno Desthuilliers
Steven D'Aprano a écrit :
(snip)
> It makes more sense to explicitly cast bools to ints 

s/cast bools to ints/build ints from bools/

AFAICT, there's no such thing as typecast in Python.

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


Re: Getting values out of a CSV

2007-07-13 Thread Michael Hoffman
Daniel wrote:
> On Fri, 13 Jul 2007 08:51:25 +0300, Gabriel Genellina 
> <[EMAIL PROTECTED]> wrote:
 >
>> Note that every time you see [x for x in ...] with no condition, you 
>> can write list(...) instead - more clear, and faster.
 >
> Faster? No. List Comprehensions are faster.

Why do you think that?
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: web page text extractor

2007-07-13 Thread Paul McGuire
On Jul 12, 4:42 am, kublai <[EMAIL PROTECTED]> wrote:
> Hello,
>
> For a project, I need to develop a corpus of online news stories.  I'm
> looking for an application that, given the url of a web page, "copies"
> the rendered text of the web page (not the source HTNL text), opens a
> text editor (Notepad), and displays the copied text for the user to
> examine and save into a text file. Graphics and sidebars to be
> ignored. The examples I have come across are much too complex for me
> to customize for this simple job. Can anyone lead me to the right
> direction?
>
> Thanks,
> gk

One of the examples provided with pyparsing is an HTML stripper - view
it online at http://pyparsing.wikispaces.com/space/showimage/htmlStripper.py.

-- Paul

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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-13 Thread Diez B. Roggisch
John Nagle schrieb:
> Chris Mellon wrote:
>> You can't prove a program to be correct, in the sense that it's proven
>> to do what it's supposed to do and only what it's supposed to do.
> 
> Actually, you can prove quite a bit about programs with the right 
> tools.
> For example, proving that a program cannot subscript out of range is
> quite feasible.  (Although not for C, where it's most needed; that language
> is just too ill-defined.) 

You can - when there is input involved?

> You can prove that certain assertions about
> an object always hold when control is outside the object.  You can
> prove that certain entry conditions for a function are satisfied by
> all its callers.
> 
> Take a look at what the "Spec#" group at Microsoft is doing.
> There's also some interesting USAF work on avionics at
> 
> http://www.stsc.hill.af.mil/crossTalk/2006/09/0609SwardGerkenCasey.html

"""
For example, SPARK does not support dynamic allocation of memory so 
things such as pointers and heap variables are not supported.
"""

Pardon me, but if that's the restrictions one has to impose to his 
programs to make them verifiable, I'm not convinced that this is a way 
to go for python - or any other language - that needs programs beyond 
the most trivial tasks.

Which is not to say that trivial code couldn't have errors, and if it's 
extremely cruical code, it's important that it hasn't errors. But all I 
can see is that you can create trustable, simple sub-systems in such a 
language. And by building upon them, you can ensure that at least these 
won't fail.

But to stick with the example: if the path-planning of the UAV that 
involves tracking a not before-known number of enemy aircrafts steers 
the UAV into the ground, no proven-not-to-fail radius calculation will 
help you.

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


Re: Tool for finding external dependencies

2007-07-13 Thread syt
On Jul 9, 3:39 am, Rob Cakebread <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I need to find external dependencies for modules (not Python standard
> library imports).
>
> Currently I usepylintand manually scan the output, which is very
> nice, or usepylint's--ext-import-graph option to create a .dot file
> and extract the info from it, but either way can take a very long
> time.
>
> I'm aware of Python's modulefinder.py, but it doesn't find external
> dependencies (or at least I don't know how to make it do them).

notice that you can launch pylint in the following way to disabling
everything but dependencies analysis : ::

  pylint --enable-checker=imports yourproject

this will disable all others checkers and you may gain a signifiant
speedup.

-- Sylvain

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


Re: Fast powerset function

2007-07-13 Thread Antoon Pardon
On 7/12/07, Arash Arfaee <[EMAIL PROTECTED]> wrote:
> I need a powerset generator function. It's really slow with recursion. Does
> anybody have any idea or code(!!) to do it in an acceptable time?
> Thanks

My idea would be the following.

1) Turn your set into a list: lst

2) let lng be the number of elements.

3) let n range from 0 to 2 ** lng

4) now n represents subset as follows

   consider n as a binary number
   bit k is set in n <=> lst[k] is a member of the subset.

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


Re: Class decorators do not inherit properly

2007-07-13 Thread Diez B. Roggisch
Chris Fonnesbeck schrieb:
> I have a class that does MCMC sampling (Python 2.5) that uses decorators 
> -- one in particular called _add_to_post that appends the output of the 
> decorated method to a class attribute. However, when I 
> subclass this base class, the decorator no longer works:
> 
> Traceback (most recent call last):
>   File "/Users/chris/Projects/CMR/closed.py", line 132, in 
> class M0(MetropolisHastings):
>   File "/Users/chris/Projects/CMR/closed.py", line 173, in M0
> @_add_to_post
> NameError: name '_add_to_post' is not defined
> 
> yet, when I look at the dict of the subclass (here called M0), I see the 
> decorator method:
> 
> In [5]: dir(M0)
> Out[5]: 
> ['__call__',
>  '__doc__',
>  '__init__',
>  '__module__',
>  '_add_to_post',
> ...
> 
> I dont see what the problem is here -- perhaps someone could shed 
> some light. I thought it might be the underscore preceding the name, 
> but I tried getting rid of it and that did not help.

Does this simple example show your problem?


class Meta(type):
 def __init__(cls, *args):
 print "Meta.__init__ called"
 return super(Meta, cls).__init__(*args)


class A(object):
 __metaclass__ = Meta

 def decorator(f):
 print "decorator called"
 return f

 @decorator
 def foo(self):
 pass


class B(A):
 [EMAIL PROTECTED]
 def bar(self):
 pass


print dir(A())
print dir(B())


then it explains the problem easily: the class-statement (class 
Name(base): http://mail.python.org/mailman/listinfo/python-list


Re: Question about PyDict_SetItemString

2007-07-13 Thread Stefan Behnel
lgx schrieb:
> Does PyDict_SetItemString(pDict,"key",PyString_FromString("value"))
> cause memory leak?
> 
>>From Google results, I find some source code write like that. But some
> code write like below:
> 
> obj =  PyString_FromString("value");
> PyDict_SetItemString(pDict,"key",obj);
> Py_DECREF(obj);

Sorry, my previous response came from the completely wrong bag.

The second is right. PyString_FromString() increases the refcount of the
returned string, so you have to decref it after use.

PyDict_SetItemString() does its own refcount increase internally when it
stores the value, so don't bother about it at all when you think about what
refcounts you have to increase or decrease.

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


Re: how to install pygame package?

2007-07-13 Thread Daniel Nogradi
> Im working in red hat linux 9.0. I've downloaded the pygame package
> but i dont know how to install it. If anybody has the time to detail
> the steps sequentially... thanx!
>
> P.S. I've downloaded both the tar and the rpm packages...

First you can try the rpm package:

su
(give the root password)
rpm -i 

Or with the tar package:

tar xzvf 
cd  (the name of the created directory)
./configure
make
su
(give the root password)
make install

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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-13 Thread Antoon Pardon
On 2007-07-13, Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
> "Donn Cave" <[EMAIL PROTECTED]> wrote:
>
>>In its day, goto was of course very well loved.
>
> Does anybody know for sure if it is in fact possible to
> design a language completely free from conditional jumps?

I think you have to be more clear on what you mean. I would consider a
while loop as a conditional jump but I have the impression you don't.
Is that correct?

> At the lower level, I don't think you can get away with
> conditional calls - hence the "jumps with dark glasses",
> continue and break.

Would you consider raise as belonging in this collection?

> I don't think you can get that functionality in another way.
>
> Think of solving the problem of reading a text file to find
> the first occurrence of some given string - can it be done 
> without either break or continue?  (given that you have to 
> stop when you have found it)

It depend on what the language offers. Should PEP 325 be implemented the
code would look something like:

  do:
line = fl.readline()
  while st not in line:
pass

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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-13 Thread Marc 'BlackJack' Rintsch
On Fri, 13 Jul 2007 08:37:00 +0200, Hendrik van Rooyen wrote:

> "Donn Cave" <[EMAIL PROTECTED]> wrote:
> 
>>In its day, goto was of course very well loved.
> 
> Does anybody know for sure if it is in fact possible to
> design a language completely free from conditional jumps?

GOTO is unconditional.  I guess it depends on what you call a jump.

> At the lower level, I don't think you can get away with
> conditional calls - hence the "jumps with dark glasses",
> continue and break.
> 
> I don't think you can get that functionality in another way.

Don't think in terms of calls and jumps but conditionally evaluating
functions with no side effects.

> Think of solving the problem of reading a text file to find
> the first occurrence of some given string - can it be done 
> without either break or continue?  (given that you have to 
> stop when you have found it)

Finding an element in a list in Haskell:

findFirst needle haystack = f 0 haystack where
f _ [] = -1
f i (x:xs) | x == needle = i
   | otherwise   = f (i+1) xs

No ``break`` or ``continue`` but a recursive function.

>  I can't think of a way, even in assembler, to do this without
> using a conditional jump - but maybe my experience has
> poisoned my mind, as I see the humble if statement as a plethora
> of local jumps...

Technically yes, and with exceptions we have non local jumps all over the
place.

You are seeing the machine language behind it, and of course there are lots
of GOTOs, but not "uncontrolled" ones.  The language above hides them and
allows only a limited set of jumps.  Easing the proofs that the program is
correct.  If you have a conditional call you can proof both alternative
calls and build the proof the the function that builds on those
alternatives on them.

Trying to guess how some source would look like in machine language isn't
that easy anymore the higher the abstraction level of the used
programming language is.  In Haskell for example you have to keep in mind
that it uses lazy evaluation and that the compiler knows very much about
the program structure and data types and flow to do optimizations.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fast powerset function

2007-07-13 Thread Paul Rubin
Antoon Pardon <[EMAIL PROTECTED]> writes:
> On 7/12/07, Arash Arfaee <[EMAIL PROTECTED]> wrote:
> > I need a powerset generator function. It's really slow with recursion. Does
> > anybody have any idea or code(!!) to do it in an acceptable time?
> My idea would be the following. ...
> 3) let n range from 0 to 2 ** lng

That may help a little but my guess is the slowness comes from
the size (2**n) of the power set.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting values out of a CSV

2007-07-13 Thread Kelvie Wong
On 7/12/07, Daniel <[EMAIL PROTECTED]> wrote:
> On Fri, 13 Jul 2007 08:51:25 +0300, Gabriel Genellina
> <[EMAIL PROTECTED]> wrote:
> >> data = [row for row in csv.reader(open('some.csv', 'rb'))
> >
> > Note that every time you see [x for x in ...] with no condition, you can
> > write list(...) instead - more clear, and faster.
> >
> > data = list(csv.reader(open('some.csv', 'rb')))
>
> Clearer? Maybe, but list comprehensions are clearer (at least for me)
>
> Faster? No. List Comprehensions are faster.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

[EMAIL PROTECTED] pdfps $ python -m timeit -c 'data = list(open("make.ps"))'
100 loops, best of 3: 7.5 msec per loop
[EMAIL PROTECTED] pdfps $ python -m timeit -c 'data = [line for line in
open("make.ps")]'
100 loops, best of 3: 9.2 msec per loop

On my system just putting into a list is faster.  I think this is
because you don't need to assign each line to the variable 'line' each
time in the former case.

I, too, think it's faster to just use list() instead of 'line for line
in iterable', as it seems kind of redundant.

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


Re: Function parameter type safety?

2007-07-13 Thread Dave Baum
In article <[EMAIL PROTECTED]>,
 Robert Dailey <[EMAIL PROTECTED]> wrote:

> Hi,
> 
> Is there a way to force a specific parameter in a function to be a
> specific type? For example, say the first parameter in a function of
> mine is required to be a string. If the user passes in an integer, I
> want to notify them that they should pass in a string, not an integer.

At present, there isn't any built-in way to do this (see the recent 
thread "PEP 3107 and stronger typing" for a long discussion).

However, you can use assert and isinstance() to check it manually:

def foo(a):
   assert isinstance(a, str), "argument 'a' must be a string"


I wouldn't advocate getting carried away with this pattern since it 
precludes your function from working with duck typing and defeats some 
of the dynamic nature of Python.  On the other hand, without such checks 
the resulting exceptions from assuming an argument is one type when it 
is another can be a bit misleading.

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


Re: patching pylint.el

2007-07-13 Thread syt
On Jul 9, 4:13 pm, lgfang <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I think this is a bug ofpylint.el.  But I failed finding a way to
> submit the bug neither in its official site nor in google.  So I post
> it here wishing it may be useful for some buddies.
>
> The bug is that it uses "compile-internal" from "compile" without
> require compile.  So "M-xpylint" will fail if compile hadn't been
> loaded in advance by any means.
>
> My fix is rather straightforward: add "(require 'compile)" in the code.
>
> -- begin diff output --
> 2a3>   (require 'compile)
>
> -- end diff output --

fyi, pylint related bug should be reported on the python-
[EMAIL PROTECTED] mailing list.
I've opened a ticket for your bug/patch: http://www.logilab.org/bug/eid/4026

cheers,
Sylvain

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


Re: Function parameter type safety?

2007-07-13 Thread Robert Dailey
Good replies.

I'm in the process of learning Python. I'm a native C++ programmer, so
you can see how the question relates. There's a lot of cool things C++
allowed you to do with type-checking, such as function overloading.
With templates + type checking, I can create a STD version of ifstream/
ofstream in Python. However, I found it isn't possible since Python
mainly works with strings in file data instead of bytes. To write a
number 40 to a file in python would take 6 bytes instead of 4, for
example. Anyway, I just wanted to explain why I was asking about type
checking. There's other measures I'm willing to take to get my job
done. Thanks guys.

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


Re: Question about PyDict_SetItemString

2007-07-13 Thread Hrvoje Niksic
lgx <[EMAIL PROTECTED]> writes:

>From Google results, I find some source code write like that. But
>some code write like below:
>
> obj =  PyString_FromString("value");
> PyDict_SetItemString(pDict,"key",obj);
> Py_DECREF(obj);
>
> So, which one is correct?

The latter is correct.  While PyDict_GetItemString returns a borrowed
reference, PyDict_SetItemString doesn't steal the reference.  This
makes sense because adding to the dictionary can fail for various
reasons (insufficient memory, invalid key, hash or comparison
functions failing), and that allows you to write code like this:

obj = ;
int err = PyDict_SetItemString(dict, "key", obj);
Py_DECREF(obj);
if (err)
  return NULL;   /* or whatever is appropriate in your case */

That won't leak regardless of whether PyDict_SetItemString succeeded,
and will correctly propagate an error if it occurs.

Please note that there is a new mailing list for Python/C API
questions, see http://mail.python.org/mailman/listinfo/capi-sig .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MaildirMessage

2007-07-13 Thread Tzury
> Which is a bug in the 'email.message' module, in my view. If it's
> attempting to support a mapping protocol, it should allow iteration
> the same way standard Python mappings do: by iterating over the keys.

I thought it is a bug as well, but who am I a python newbie to say so.
I found inspect.getmembers(msg) as a good solution to map the message
properties.

10x,
Tzury

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


Re: Fast powerset function

2007-07-13 Thread Carsten Haese
On Fri, 2007-07-13 at 08:15 -0400, I wrote:
> [...]
> def recursive_powerset(s):
> if not s: yield set()
> for x in s:
> s2 = s - set([x])
> for subset in recursive_powerset(s2):
> yield subset
> for subset in recursive_powerset(s2):
> yield subset.union(set([x]))
> [...]

Pardon the soliloquy, but now that I'm a bit more awake, I realize that
this is unnecessarily slow due to the duplicate invocation of the
recursive call. Changing it thusly cuts the run time roughly in half:

def recursive_powerset(s):
if not s: yield set()
for x in s:
s2 = s - set([x])
for subset in recursive_powerset(s2):
yield subset
yield subset.union(set([x]))

However, this doesn't change the fact that the iterative method blows
the recursive method out of the water.

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


scripts into wxPython

2007-07-13 Thread justme
Hello

I've been happily scripting away for the last few years (Matlab, now
Python) and all has been fine. Now I find myself scripting up code for
clients, but they all want a nice GUI. I've had a tinker with wxPython
and it all seems standard enough but I was wondering if anyone has any
comments about how easy it is to shoehorn some fairly complex scripts
into a GUI so that non-scripters can use the code. I assume I'll need
to recode up all the input outputs?

Any thoughts, or should I have started GUI programming right at the
outset!

Cheers

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


Re: How to create new files?

2007-07-13 Thread Robert Dailey
On Jul 13, 3:04 am, Bruno Desthuilliers  wrote:
> Robert Dailey a écrit :
>
> > Hi,
>
> > I'm trying to create a Python equivalent of the C++ "ifstream" class,
> > with slight behavior changes.
>
> > Basically, I want to have a "filestream" object that will allow you to
> > overload the '<<' and '>>' operators to stream out and stream in data,
> > respectively. So far this is what I have:
>
> > class filestream:
>
> class Filestream(object):
>
> >def __init__( self, filename ):
> >self.m_file = open( filename, "rwb" )
>
> You don't need this C++ 'm_' prefix here - since the use of self is
> mandatory, it's already quite clear that it's an attribute.
>
>
>
> > #  def __del__( self ):
> > #  self.m_file.close()
>
> >def __lshift__( self, data ):
> >self.m_file.write( data )
>
> >def __rshift__( self, data ):
> >self.m_file.read( data )
>
> > So far, I've found that unlike with the C++ version of fopen(), the
> > Python 'open()' call does not create the file for you when opened
> > using the mode 'w'.
>
> It does. But you're not using 'w', but 'rw'.
>
> > I get an exception saying that the file doesn't
> > exist.
>
> Which is what happens when trying to open an inexistant file in read mode.
>
> > I expected it would create the file for me. Is there a way to
> > make open() create the file if it doesn't exist
>
> yes : open it in write mode.
>
> def __init__( self, filename ):
>  try:
>  self._file = open( filename, "rwb" )
>  except IOError:
>  # looks like filename doesn't exist
>  f = open(filename, 'w')
>  f.close()
>  self._file = open( filename, "rwb" )
>
> Or you can first test with os.path.exists:
>
> def __init__( self, filename ):
>  if not os.path.exists(filename):
>  # looks like filename doesn't exist
>  f = open(filename, 'w')
>  f.close()
>  self._file = open( filename, "rwb" )
>
> HTH

Thanks for the variable naming tips. Is it normal for Python
programmers to create class members with a _ prefixed?

I also figured out why it wasn't creating the file after I had posted,
I realized I was doing "rw" instead of just "w". Thank you for
verifying. Thanks to everyone else for your replies as well.

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

Re: How to create new files?

2007-07-13 Thread ahlongxp
On Jul 13, 5:14 am, Robert Dailey <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm trying to create a Python equivalent of the C++ "ifstream" class,
> with slight behavior changes.
>
> Basically, I want to have a "filestream" object that will allow you to
> overload the '<<' and '>>' operators to stream out and stream in data,
> respectively. So far this is what I have:
>
> class filestream:
> def __init__( self, filename ):
> self.m_file = open( filename, "rwb" )
>
> #   def __del__( self ):
> #   self.m_file.close()
>
> def __lshift__( self, data ):
> self.m_file.write( data )
>
> def __rshift__( self, data ):
> self.m_file.read( data )
>
> So far, I've found that unlike with the C++ version of fopen(), the
> Python 'open()' call does not create the file for you when opened
> using the mode 'w'. I get an exception saying that the file doesn't
> exist. I expected it would create the file for me. Is there a way to
> make open() create the file if it doesn't exist, or perhaps there's
> another function I can use to create the file? I read the python docs,
> I wasn't able to find a solution.
>
using "w" or "wb" will create new file if it doesn't exist.
at least it works for me.
> Also, you might notice that my "self.m_file.read()" function is wrong,
> according to the python docs at least. read() takes the number of
> bytes to read, however I was not able to find a C++ equivalent of
> "sizeof()" in Python. If I wanted to read in a 1 byte, 2 byte, or 4
> byte value from data into python I have no idea how I would do this.
>
f.read(10) will read up to 10 bytes.
you know what to do now.

> Any help is greatly appreciated. Thanks.

and another thing to mention, __del__() will not always be called( any
comments?).
so you'd better flush your file explicitely by yourself.

--
ahlongxp

Software College,Northeastern University,China
[EMAIL PROTECTED]
http://www.herofit.cn



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


Re: bool behavior in Python 3000?

2007-07-13 Thread ahlongxp
On Jul 11, 5:36 am, Bjoern Schliessmann  wrote:

> Is there any type named "bool" in standard Python?

check this out.
>>> doespythonrock = True
>>> print type(doespythonrock)

>>>

--
ahlongxp

Software College,Northeastern University,China
[EMAIL PROTECTED]
http://www.herofit.cn


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


Re: os.wait() losing child?

2007-07-13 Thread Jason Zheng
Hrvoje Niksic wrote:
> Jason Zheng <[EMAIL PROTECTED]> writes:
> 
>> Hrvoje Niksic wrote:
 greg wrote:
>>> Actually, it's not that bad.  _cleanup only polls the instances that
>>> are no longer referenced by user code, but still running.  If you hang
>>> on to Popen instances, they won't be added to _active, and __init__
>>> won't reap them (_active is only populated from Popen.__del__).
>>>
>> Perhaps that's the difference between Python 2.4 and 2.5.
> [...]
>> Nope it still doesn't work. I'm running python 2.4.4, tho.
> 
> That explains it, then, and also why greg's code didn't work.  You
> still have the option to try to run 2.5's subprocess.py under 2.4.
Is it more convenient to just inherit the Popen class? I'm concerned 
about portability of my code. It will be run on multiple machines with 
mixed Python 2.4 and 2.5 environments.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: access to the namespace of a function from within its invocation

2007-07-13 Thread Bruno Desthuilliers
Poor Yorick a écrit :
> In the example below, the attribute "data" is added to a function 
> object.  "me" can be used to get the function when it is invoked using 
> an identifier that matches the "co_name" attribute of function's code 
> object.  Can anyone conjure an example of accessing fun2.data from 
> without prior knowledge of the value of fun2.f_code.co_name?
> 
> ###code begin###
> #!/bin/python
> 
> import sys
> 
> def me():
>t = sys._getframe(0)
>return t.f_back.f_globals[t.f_back.f_code.co_name]
> def fun1():
>m = me
>print me().data
>def makefun () :
>def tmpfunc():
>print 'need something like me().data'
>return tmpfunc
> 
> fun1.s = fun1
> fun1.data=['one', 'two', 'three']
> fun1()
> fun2 = makefun()
> fun2.data=['four', 'five','six']
> fun2()
> 
> ###code end###
> 

Not a direct answer to your question, but anyway;

As soon as you want to bundle data with behaviour, OO comes to mind. 
Good news is that Python is actually an OOPL which implements functions 
as objects and let you define function-like ('callable') objects.

class DataFunc(object):
   def __init__(self, data):
 self.data = data

   def __call__(self, *args, **kw):
 print self.data

fun2 = DataFunc(['four', 'five', 'forty-two'])
fun2()

Note that you'll also have to correctly implement the __get__ method if 
you want an instance of DataFunc to be usable as a method (look for the 
descriptor protocol in the FineManual(tm) for more information on this 
point).

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

Re: Function parameter type safety?

2007-07-13 Thread Michele Simionato
On Jul 13, 4:53 pm, Robert Dailey <[EMAIL PROTECTED]> wrote:
> Good replies.
>
> I'm in the process of learning Python. I'm a native C++ programmer, so
> you can see how the question relates. There's a lot of cool things C++
> allowed you to do with type-checking, such as function overloading.

This is an area of hot debate in Python and things are changing. You
may want
to have a look at http://www.python.org/dev/peps/pep-3119 about
interfaces,
and to http://www.python.org/dev/peps/pep-3124 about overloading and
generic functions. Both PEPs are for Python 3000, but their existence
should be an indication that people are not happy with the current
situation
in Python. You can something better than overloading already, with
P.J. Eby
modules simplegeneric and/or RuleDispatch, but I would say that they
are not
commonly used. So the right thing to do for now is to follow the good
advices you received, but keep in mind that there will be alternatives
in
the near future (such as interface checking/function overload).

  Michele Simionato

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


Re: How to create new files?

2007-07-13 Thread Bruno Desthuilliers
Robert Dailey a écrit :
> On Jul 13, 3:04 am, Bruno Desthuilliers  [EMAIL PROTECTED]> wrote:
(snip)
> Thanks for the variable naming tips. Is it normal for Python
> programmers to create class members with a _ prefixed?

This is the convention to denote implementation attributes. This won't 
of course prevent anyone to access these attributes, but anyone doing so 
is on it's own since it has been warned the attribute was not part of 
the interface.

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


permission denied in shutil.copyfile

2007-07-13 Thread Ahmed, Shakir
Is there any way to copy a file from src to dst if the dst is
exclusively open by other users.

I am using 

src  = 'c:\mydata\data\*.mdb'
dst = 'v:\data\all\*.mdb'

shutil.copyfile(src,dst)

but getting error message permission denied.

Any help is highly appreciated.

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


Tibco Rendezvous

2007-07-13 Thread rdahlstrom
Has anyone found or written a Tibco Rendezvous (tibrv) module for
Python?  I've only found some really old ones with German
documentation and not updated since some time around 2000.

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


Re: web page text extractor

2007-07-13 Thread rdahlstrom
To maintain paragraphs, replace any p or br tags with your favorite
operating system's crlf.

On Jul 13, 8:57 am, kublai <[EMAIL PROTECTED]> wrote:
> On Jul 13, 5:44 pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Jul 12, 4:42 am, kublai <[EMAIL PROTECTED]> wrote:
>
> > > Hello,
>
> > > For a project, I need to develop a corpus of online news stories.  I'm
> > > looking for an application that, given the url of a web page, "copies"
> > > the rendered text of the web page (not the source HTNL text), opens a
> > > text editor (Notepad), and displays the copied text for the user to
> > > examine and save into a text file. Graphics and sidebars to be
> > > ignored. The examples I have come across are much too complex for me
> > > to customize for this simple job. Can anyone lead me to the right
> > > direction?
>
> > > Thanks,
> > > gk
>
> > One of the examples provided with pyparsing is an HTML stripper - view
> > it online athttp://pyparsing.wikispaces.com/space/showimage/htmlStripper.py.
>
> > -- Paul
>
> Stripping tags is indeed one strategy that came to mind. I'm wondering
> how much information (for example, paragraphing) would be lost, and if
> what would be lost would be acceptable (to the project). I looked at
> pyparsing and I see that it's got a lot of text processing
> capabilities that I can use along the way. I sure will try it. Thanks
> for the post.
>
> Best,
> gk


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


Can a low-level programmer learn OOP?

2007-07-13 Thread Chris Carlen
Hi:

 From what I've read of OOP, I don't get it.  I have also found some 
articles profoundly critical of OOP.  I tend to relate to these articles.

However, those articles were no more objective than the descriptions of 
OOP I've read in making a case.  Ie., what objective 
data/studies/research indicates that a particular problem can be solved 
more quickly by the programmer, or that the solution is more efficient 
in execution time/memory usage when implemented via OOP vs. procedural 
programming?

The problem for me is that I've programmed extensively in C and .asm on 
PC DOS way back in 1988.  Then didn't program for nearly 10 years during 
which time OOP was popularized.  Starting in 1999 I got back into 
programming, but the high-level-ness of PC programming and the 
completely foreign language of OOP repelled me.  My work was in analog 
and digital electronics hardware design, so naturally I started working 
with microcontrollers in .asm and C.  Most of my work involves low-level 
signal conditioning and real-time control algorithms, so C is about as 
high-level as one can go without seriously loosing efficiency.  The 
close-to-the-machine-ness of C is ideal here.  This is a realm that I 
truly enjoy and am comfortable with.

Hence, being a hardware designer rather than a computer scientist, I am 
conditioned to think like a machine.  I think this is the main reason 
why OOP has always repelled me.

Perhaps the only thing that may have clicked regarding OOP is that in 
certain cases I might prefer a higher-level approach to tasks which 
involve dynamic memory allocation.  If I don't need the execution 
efficiency of C, then OOP might produce working results faster by not 
having to worry about the details of memory management, pointers, etc.

But I wonder if the OOP programmers spend as much time creating classes 
and trying to organize everything into the OOP paradigm as the C 
programmer spends just writing the code?

Ultimately I don't care what the *name* is for how I program.  I just 
need to produce results.  So that leads back to objectivity.  I have a 
problem to solve, and I want to find a solution that is as quick as 
possible to learn and implement.

Problem:

1.  How to most easily learn to write simple PC GUI programs that will 
send data to remote embedded devices via serial comms, and perhaps 
incorporate some basic (x,y) type graphics display and manipulation 
(simple drawing program).  Data may result from user GUI input, or from 
parsing a text config file.  Solution need not be efficient in machine 
resource utilization.  Emphasis is on quickness with which programmer 
can learn and implement solution.

2.  Must be cross-platform: Linux + Windows.  This factor can have a big 
impact on whether it is necessary to learn a new language, or stick with 
C.  If my platform was only Linux I could just learn GTK and be done 
with it.  I wouldn't be here in that case.

Possible solutions:

Form 1:  Use C and choose a library that will enable cross-platform GUI 
development.

Pro:  Don't have to learn new language.
Con:  Probably will have difficulty with cross-platform implementation 
of serial comms.  This will probably need to be done twice.  This will 
waste time.

Form 2:  Use Python and PySerial and TkInter or wxWidgets.

Pro:  Cross-platform goal will likely be achieved fully.  Have a 
programmer nearby with extensive experience who can help.
Con:  Must learn new language and library.  Must possibly learn a 
completely new way of thinking (OOP) not just a new language syntax. 
This might be difficult.

Form 3:  Use LabVIEW

Pro:  I think that the cross-platform goal can be met.
Con:  Expensive.  I would prefer to use an Open Source solution.  But 
that isn't as important as the $$$.  I have also generally found the 2D 
diagrammatical programming language of "G" as repelling as OOP.  I 
suspect that it may take as much time to learn LabVIEW as Python.  In 
that case the time spent on Python might be better spent since I would 
be learning something foundational as opposed to basically just learning 
how to negotiate someone's proprietary environment and drivers.


Comments appreciated.


-- 
Good day!


Christopher R. Carlen
Principal Laser&Electronics Technologist
Sandia National Laboratories CA USA
[EMAIL PROTECTED]
NOTE, delete texts: "RemoveThis" and
"BOGUS" from email address to reply.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Understanding python functions - Instant Python tutorial

2007-07-13 Thread Chris Carlen
Gabriel Genellina wrote:
> En Thu, 12 Jul 2007 21:51:08 -0300, Chris Carlen  
> <[EMAIL PROTECTED]> escribió:
>> http://hetland.org/writing/instant-python.html
>> I don't understand Hetland's terminology though, when he is speaking of
>> "binding" and "reference."  Actually, Hetland's entire first paragraph
>> is unclear.
> First, see this short article http://effbot.org/zone/python-objects.htm

I'll have a look.

> Now, forget about C "variables" and "pointers" because you won't get 
> much  far with those concepts.

Ok, painful, but I'll try.

> Objects exist - and we usually use names to refer to them. This line:
> 
> a =  1
> 
> means "make the name 'a' refer to the object 1", or, "bind the name 'a' 
> to  the instance of type int with value 1", or "let 'a' be a reference 
> to the  object 1"
> 
> This line:
> 
> some_list[1] = 4
> 
> means "make the second element of some_list refer to the object 4", or  
> "alter some_list so its element [1] is a reference to the object 4"
> 
> bind the name 'a' to the instance of type int with value 1", or "let 
> 'a'  be a reference to the object 1"
> 
> Note that some objects are immutable - like the number 1, which will  
> always be the number 1 (*not* an integer "variable" that can hold any  
> integer value). Other objects -like lists and dictionaries, by example, 
> or  most user defined classes- are mutable, and you can change its 
> contents  and properties. Modifying an object is not the same as 
> rebinding its name:
> 
> x = [1,2,3]
> y = x
> x[1] = 4
> print x# [1, 4, 3]
> print y # [1, 4, 3]

Thanks to your explanation, I understand!

> x = [1,2,3]
> y = x
> x = [1,4,3]
> print x# [1, 4, 3]
> print y# [1, 2, 3]
> 
> You can test is two names refer to the same object using the is 
> operator:  x is y. You will get True in the first case and False in the 
> second case.

I don't quite get this "x is y" stuff yet.

Let's go back the statement:

x = [1,2,3]

Do we then say: "[1,2,3] is x" or is it the other way around: "x is 
[1,2,3]" ???

I think it is the former in Python, whereas it would be the latter in C.

So Python is like saying "I am Chris Carlen."

This is actually completely ridiculous, since I am me, not my name.  The 
name refers to me.  I get that.  Yet our spoken language puts it in a 
way which is backwards.


Thanks for the input.





-- 
Good day!


Christopher R. Carlen
Principal Laser&Electronics Technologist
Sandia National Laboratories CA USA
[EMAIL PROTECTED]
NOTE, delete texts: "RemoveThis" and
"BOGUS" from email address to reply.
-- 
http://mail.python.org/mailman/listinfo/python-list

sys.exit versus termination of source code

2007-07-13 Thread Carl DHalluin
Hi,

 

I am playing with the atexit module but I don't find a way to see the
difference

between a script calling sys.exit() and the interpreting
arriving at the end

of the source code file. This has a semantic difference for my
applications.

Is there a way to determine in an exithandler (that is registered using
atexit.register)

how I exited?

 

Second question: is there a way to determine in my exithandler what the
return code was.

atexit doesn't seem to support that

 

Third question: I can solve part of my problem by reassigning sys.exit =
myfunction

Is that a wise idea?

 

Thanks

Carl D'Halluin

www.qlayer.com

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

Re: Getting values out of a CSV

2007-07-13 Thread Daniel
On Fri, 13 Jul 2007 16:18:38 +0300, Marc 'BlackJack' Rintsch  
<[EMAIL PROTECTED]> wrote:
>> $ python -m timeit -c 'import csv; data =  
>> list(csv.reader(open("some.csv",
>> "rb")))'
>> 1 loops, best of 3: 44 usec per loop
>> $ python -m timeit -c 'import csv; data = [row for row in
>> csv.reader(open("some.csv", "rb"))]'
>> 1 loops, best of 3: 37 usec per loop
>>
>> I don't know why there seems to be a differece, but I know that list  
>> comps
>> are python are very heavily optimised.
>
> Does the machine use power saving features like SpeedStep or
> something similar, i.e. runs the processor always with 100% speed or is  
> it
> dynamically stepped if there's load on the processor?  Do both tests read
> the data always from cache or has the very first loop had to fetch the  
> CSV
> file from disk?
>
> $ python -m timeit -n 1000 -c 'import csv; data = [row for row in
> csv.reader(open("test.csv", "rb"))]' 1000 loops, best of 3: 1.27 msec per
> loop
>
> $ python -m timeit -n 1000 -c 'import csv; data =
> list(csv.reader(open("test.csv", "rb")))' 1000 loops, best of 3: 1.25  
> msec
> per loop

No SpeedStep - tried a few repeats just in case files were cached,  
consistent 35usec for comp 40usec for list

Python 2.5.1 on Linux 1.2ghz

Even replacing the csv lookup with a straight variable declaration:  
[range(10)*3], same results

Weird.

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


Re: Circular import problem

2007-07-13 Thread bvdp

> Seehttp://effbot.org/zone/import-confusion.htm
> Try to move the circular references later in the code (maybe inside a
> function, when it is required), or much better, refactor it so there is no
> circularity.
>
> --
> Gabriel Genellina

Yes, thanks. I'd read that page before posting. Helpful.

But, I still don't understand how python can access a function in a
file I have NOT included. In this case, to get things to work, I DO
NOT "import MMA.grooves" but later in the module I access a function
with "xx=MMA.grooves.somefunc()" and it finds the function, and works
just fine. It shouldn't work.

I have tried to delay the import, and that does work. But, from a
stylistic view I really to like to have all my imports at the top of
the module. Maybe some old assembler/C habits on my part.



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


how to implementation latent semantic indexing in python..

2007-07-13 Thread 78ncp

hi...
how to implementation algorithm latent semantic indexing in python
programming...??

thank's for daniel who answered my question before..

-- 
View this message in context: 
http://www.nabble.com/how-to-implementation-latent-semantic-indexing-in-python..-tf4075439.html#a11582773
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Can a low-level programmer learn OOP?

2007-07-13 Thread Marc 'BlackJack' Rintsch
On Fri, 13 Jul 2007 09:06:44 -0700, Chris Carlen wrote:

> Perhaps the only thing that may have clicked regarding OOP is that in 
> certain cases I might prefer a higher-level approach to tasks which 
> involve dynamic memory allocation.  If I don't need the execution 
> efficiency of C, then OOP might produce working results faster by not 
> having to worry about the details of memory management, pointers, etc.

That's not something tied to OOP.  Automatic memory management is also
possible with procedural languages.

> But I wonder if the OOP programmers spend as much time creating classes 
> and trying to organize everything into the OOP paradigm as the C 
> programmer spends just writing the code?

Creating classes and organizing the program in an OOP language isn't
different from creating structs and organizing the program in C.

On one side Python is a very OOP language as everything is an object.  On
the other side it is possible to write parts of the program in procedural
or even functional style.  Python is not Java, you don't have to force
everything into classes.

>From my experience Python makes it easy to "just write the code".  Easier
than C because I don't have to deal with so much machine details, don't
have to manage memory, don't need extra indexes for looping over lists and
so on.  And the "crashes" are much gentler, telling me what the error is
and where instead of a simple "segfault" or totally messed up results.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Understanding python functions - Instant Python tutorial

2007-07-13 Thread Wildemar Wildenburger
Chris Carlen wrote:
> Let's go back the statement:
>
> x = [1,2,3]
>
> Do we then say: "[1,2,3] is x" or is it the other way around: "x is 
> [1,2,3]" ???
>   
This will yield 'False', because 'is' checks for *identity* not 
equality. In your case you assign a list the name 'x' and then check 
(via the 'is' operator) if it is the same object as another (newly 
created) list. While they are equal (same class and contents) they are 
not the same.
Try this:

x = [1, 2, 3]
y = [1, 2, 3]
id(x), id(y)
x == y
x is y

Then you'll see.

> This is actually completely ridiculous, since I am me, not my name.  The 
> name refers to me.  I get that.  Yet our spoken language puts it in a 
> way which is backwards.
>   
To stress the point: "a is b" has the same meaning as "b is a". It does 
not check for "being a certain thing" (as in "Archimedes is a human") 
but rather for "one thing beeing the exact same as the other" (as in 
"Superman is Clark Kent").
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with Python's "robots.txt" file parser in module robotparser

2007-07-13 Thread Nikita the Spider
In article <[EMAIL PROTECTED]>,
 John Nagle <[EMAIL PROTECTED]> wrote:

>I asked over at Webmaster World, and over there, they recommend against
> using redirects on robots.txt files, because they questioned whether all of
> the major search engines understand that.  Does a redirect for 
> "foo.com/robots.txt" mean that the robots.txt file applies to the domain
> being redirected from, or the domain being redirected to?

Good question. I'd guess the latter, but it's a little ambiguous. I 
agree that redirecting a request for robots.txt is probably not a good 
idea. Given that the robots.txt standard isn't as standard as it could 
be, I think it's a good idea in general to apply the KISS principle when 
dealing with things robots.txt-y.

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


Re: Understanding python functions - Instant Python tutorial

2007-07-13 Thread Chris Carlen
Ben Finney wrote:
> Chris Carlen <[EMAIL PROTECTED]> writes:
 >
> def change(some_list):
> some_list[1] = 4
>
> x = [1,2,3]
> change(x)
> print x # Prints out [1,4,3] 
 > ---
 > def nochange(x):
 > x = 0
 >
 > y = 1
 > nochange(y)
 > print y # Prints out 1
 >
>>I don't understand Hetland's terminology though, when he is speaking
>>of "binding" and "reference."  Actually, Hetland's entire first
>>paragraph is unclear.
>>
>>Can anyone reword this in a way that is understandable?
> 
> I've had some success with the following way of thinking about it.
> 
> Some languages have "variables", which act like boxes that have names
> etched on the side. Once created, the box can contain an object, and
> it can be inspected while in the box; to change the variable, you
> throw out the object and put a different object in the same box.

Yes, so y = x takes a copy of the stuff in the x box and puts it in the 
y box.  Which is what really happens in the hardware.

> That's not how Python works. Every value is an object; the assignment
> operator binds a name to an object. This is more like writing the name
> on a sticky-note, and sticking it onto the object.
> 
>   * The object itself doesn't change or "move".
> 
>   * The object can be referred to by that name, but isn't "inside" the
> name in any way.
> 
>   * Assigning multiple names to the same object just means you can
> refer to that same object by all those names.
> 
>   * When a name goes away, the object still exists -- but it can't be
> referred to if there are no longer any names left on it.
> 
>   * Assigning a different object to an existing name just means that
> the same sticky-note has moved from the original object to the new
> one. Referring to the same name now references a different object,
> while the existing object keeps all the other names it had.

Excellent description.  This understandable to me since I can envision 
doing this with pointers.  But I have no idea how Python actually 
implements this.  It also appears that I am being guided away from 
thinking about it in terms of internal implementation.

> When you pass an object as a parameter to a function, the object
> receives a new sticky-label: the parameter name under which it was
> received into the function scope. Assignment is an act of binding a
> name to an object; no new object is created, and it still has all the
> other names it had before.

Ok, so I can understand the code above now.

In the first case I pass the reference to the list to change().  In the 
function, some_list is another name referring to the actual object 
[1,2,3].  Then the function changes the object referred to by the second 
element of the list to be a 4 instead of a 2.  (Oh, the concept applies 
here too!)  Out of the function, the name x refers to the list which has 
been changed.

In the second case, y refers to a '1' object and when the function is 
called the object 1 now gets a new reference (name) x inside the 
function.  But then a new object '0' is assigned to the x name.  But the 
y name still refers to a '1'.

I get it.  But I don't like it.  Yet.  Not sure how this will grow on me.

> When the function ends, all the names that were created inside that
> function's scope disappear; but the objects still exist under any
> names they had previously, and if you use those names you'll be
> looking at the same object as was manipulated inside the function.
> 
> When the object has lost all its names -- for example, they've
> disappeared because the scope they were in has closed, or they've been
> re-bound to other objects -- they can no longer be referenced. At some
> point after that, the automatic garbage collection will clean that
> object out of memory.
> 
> This sticky-note analogy, and the behaviour described, is what is
> meant by "references". A name refers to an object; changing the object
> means that by referring to that same object under its different names,
> you will see the same, modified, object.
> 
> In Python, all names are references to objects. The assignment
> operator '=' doesn't create or change a "variable"; instead, it binds
> a name as reference to an object. All functions receive their
> parameters as the existing object with a new name -- a reference to
> that object, just like any other name.
> 
> Hope that helps.


A great deal of help, thanks.  Excellent explanation.  Wow.  This is 
strange.  A part of me wants to run and hide under the nearest 8-bit 
microcontroller.  But I will continue learning Python.



-- 
Good day!


Christopher R. Carlen
Principal Laser&Electronics Technologist
Sandia National Laboratories CA USA
[EMAIL PROTECTED]
NOTE, delete texts: "RemoveThis" and
"BOGUS" from email address to reply.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Understanding python functions - Instant Python tutorial

2007-07-13 Thread Wildemar Wildenburger
Wildemar Wildenburger wrote:
> x = [1, 2, 3]
> y = [1, 2, 3]
> id(x), id(y)
> x == y
> x is y
>   
Ooops!

Make that:

x = [1, 2, 3]
y = [1, 2, 3]
id(x); id(y)
x == y
x is y

(had to be a semicolon there)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can a low-level programmer learn OOP?

2007-07-13 Thread John Nagle
Chris Carlen wrote:
> Hi:
> 
>  From what I've read of OOP, I don't get it.  I have also found some 
> articles profoundly critical of OOP.  I tend to relate to these articles.
> 
> However, those articles were no more objective than the descriptions of 
> OOP I've read in making a case.  Ie., what objective 
> data/studies/research indicates that a particular problem can be solved 
> more quickly by the programmer, or that the solution is more efficient 
> in execution time/memory usage when implemented via OOP vs. procedural 
> programming?
> 
> The problem for me is that I've programmed extensively in C and .asm on 
> PC DOS way back in 1988.  Then didn't program for nearly 10 years during 
> which time OOP was popularized.  Starting in 1999 I got back into 
> programming, but the high-level-ness of PC programming and the 
> completely foreign language of OOP repelled me.  My work was in analog 
> and digital electronics hardware design, so naturally I started working 
> with microcontrollers in .asm and C.  Most of my work involves low-level 
> signal conditioning and real-time control algorithms, so C is about as 
> high-level as one can go without seriously loosing efficiency.  The 
> close-to-the-machine-ness of C is ideal here.  This is a realm that I 
> truly enjoy and am comfortable with.
> 
> Hence, being a hardware designer rather than a computer scientist, I am 
> conditioned to think like a machine.  I think this is the main reason 
> why OOP has always repelled me.

 Why?

 I've written extensively in C++, including hard real-time programming
in C++ under QNX for a DARPA Grand Challenge vehicle.  I have an Atmel
AVR with a cable plugged into the JTAG port sitting on my desk right now.
Even that little thing can be programmed in C++.

 You can sometimes get better performance in C++ than in C, because C++
has "inline".  Inline expansion happens before optimization, so you
can have abstractions that cost nothing.

 If it has state and functions, it probably should be an object.
The instances of the object can be static in C++; dynamic memory
allocation isn't required in C++, as it is in Python.

 Python is a relatively easy language, easier than C++, Java,
or even Perl.  It's quite forgiving.  The main implementation,
CPython, is about 60x slower than C, though, so if you're trying
to implement, say, a rapidly changing digital oscilloscope display,
the result may be sluggish.

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


Re: Re-raising exceptions with modified message

2007-07-13 Thread samwyse
On Jul 13, 12:45 am, Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
> samwyse wrote:
> > TypeError: __class__ must be set to a class
>
> > Excpt ceratinly appears to be a class.  Does anyone smarter than me
> > know what's going on here?
>
> Not that I want to appear smarter, but I think the problem here is that
> exceptions are new-style classes now, whereas Empty is an old-style
> class. But even if you define Empty as a new-style class, it will not
> work, you get:
>
> TypeError: __class__ assignment: only for heap types
>
> This tells us that we cannot change the attributes of a built-in
> exception. If it would be possible, I simply would have overridden the
> __str__ method of the original exception in the first place.
>
> -- Chris

Chris, you owe me a beer if you're ever in St. Louis, or I'm ever in
Germany.

# - CUT HERE -

# Written by Sam Denton <[EMAIL PROTECTED]>
# You may use, copy, or distribute this work,
# as long as you give credit to the original author.

# tested successfully under Python 2.4.1, 2.4.3, 2.5.1

"""
On Jul 5, 2007, at 8:53 am, Christoph Zwerschke <[EMAIL PROTECTED]>
wrote:
> What is the best way to re-raise any exception with a message
> supplemented with additional information (e.g. line number in a
> template)? Let's say for simplicity I just want to add "sorry" to
> every exception message.

Here is an example of typical usage:

>>> def typical_usage(code):
... try:
... code()
... except Exception, e:
... simplicity = lambda self: str(e) + ", sorry!"
... raise modify_message(e, simplicity)

Note that if we want to re-cycle the original exception's message,
then we need our re-formatter (here called 'simplicity') to be
defined inside the exception handler.  I tried verious approaches
to defining the re-formater, but all of them eventually needed a
closure; I decided that I liked this approach best.

This harness wraps the example so that doctest doesn't get upset.

>>> def test_harness(code):
... try:
... typical_usage(code)
... except Exception, e:
... print "%s: %s" % (e.__class__.__name__, str(e))

Now for some test cases:

>>> test_harness(lambda: 1/0)
ZeroDivisionError: integer division or modulo by zero, sorry!

>>> test_harness(lambda: unicode('\xe4'))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position
0: ordinal not in range(128), sorry!

"""

def modify_message(old, f):
"""modify_message(exception, mutator) --> exception

Modifies the string representation of an exception.
"""
class NewStyle(old.__class__):
def __init__(self): pass
NewStyle.__name__ = old.__class__.__name__
NewStyle.__str__ = f
new = NewStyle()
new.__dict__ = old.__dict__.copy()
return new

def _test():
import doctest
return doctest.testmod(verbose=True)

if __name__ == "__main__":
_test()

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


Re: os.wait() losing child?

2007-07-13 Thread Hrvoje Niksic
Jason Zheng <[EMAIL PROTECTED]> writes:

>>> Nope it still doesn't work. I'm running python 2.4.4, tho.
>> That explains it, then, and also why greg's code didn't work.  You
>> still have the option to try to run 2.5's subprocess.py under 2.4.
> Is it more convenient to just inherit the Popen class?

You'd still need to change its behavior to not call _cleanup.  For
example, by removing "your" instances from subprocess._active before
chaining up to Popen.__init__.

> I'm concerned about portability of my code. It will be run on
> multiple machines with mixed Python 2.4 and 2.5 environments.

I don't think there is a really clean way to handle this.
-- 
http://mail.python.org/mailman/listinfo/python-list


renaming an open file in nt like unix?

2007-07-13 Thread aaron . watters
Hi.  I'm writing an archival system which I'd like to be portable
to Windows.

The system relies on the property of Unix which allows a
process to keep a file open even if another process renames
it while it is open.  Neither process sees any anomaly or
error.

Do the NT file systems support this feature (which I think is
standard for POSIX systems)?

Inquiring minds want to know.  -- Aaron Watters

===
an apple every 8 hours
will keep 3 doctors away.  -- kliban

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


Re: patching pylint.el

2007-07-13 Thread lgfang
> "syt" == syt  <[EMAIL PROTECTED]> writes:
syt> fyi, pylint related bug should be reported on the python-
syt> [EMAIL PROTECTED] mailing list.  I've opened a ticket for
syt> your bug/patch: http://www.logilab.org/bug/eid/4026

Thank you, Sylvain

Fanglungang (fang.lungang at gmail)

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


Re: renaming an open file in nt like unix?

2007-07-13 Thread Thomas Heller
[EMAIL PROTECTED] schrieb:
> Hi.  I'm writing an archival system which I'd like to be portable
> to Windows.
> 
> The system relies on the property of Unix which allows a
> process to keep a file open even if another process renames
> it while it is open.  Neither process sees any anomaly or
> error.
> 
> Do the NT file systems support this feature (which I think is
> standard for POSIX systems)?

Yes, you can do that.  We implemented something like this to replace
dlls there are currently in use - rename the currently open file, create a new 
one
with the old name (newly started processes will use the new one then),
and delete the renamed one at the next possible occasion (usually at
the next reboot).  I'm not so sure on which NT versions it works this
way, at least in w2000 and newer.

Thomas

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


CTypes FAQs - buffer memmove offsetof uchar ((void *) -1) etc.

2007-07-13 Thread p . lavarre
http://wiki.python.org/moin/ctypes now tries to answer:

'''FAQ: How do I copy bytes to Python from a ctypes.Structure?'''
'''FAQ: How do I copy bytes to a ctypes.Structure from Python?'''
'''FAQ: Why should I fear using ctypes.memmove?'''
'''FAQ: How do I change the byte length of a ctypes.Structure?'''
'''FAQ: How do I say memcpy?'''
'''FAQ: How do I say offsetof?'''
'''FAQ: How do I say uchar?'''
'''FAQ: How do I say ((void *) -1)?'''
'''FAQ: How do I contribute to this CTypes FAQ?'''
'''FAQ: How do I learn Python CTypes, after learning C and Python?'''

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


Re: Understanding python functions - Instant Python tutorial

2007-07-13 Thread Chris Mellon
On 7/13/07, Chris Carlen <[EMAIL PROTECTED]> wrote:
> Ben Finney wrote:
> > Chris Carlen <[EMAIL PROTECTED]> writes:

> > That's not how Python works. Every value is an object; the assignment
> > operator binds a name to an object. This is more like writing the name
> > on a sticky-note, and sticking it onto the object.
> >
> >   * The object itself doesn't change or "move".
> >
> >   * The object can be referred to by that name, but isn't "inside" the
> > name in any way.
> >
> >   * Assigning multiple names to the same object just means you can
> > refer to that same object by all those names.
> >
> >   * When a name goes away, the object still exists -- but it can't be
> > referred to if there are no longer any names left on it.
> >
> >   * Assigning a different object to an existing name just means that
> > the same sticky-note has moved from the original object to the new
> > one. Referring to the same name now references a different object,
> > while the existing object keeps all the other names it had.
>
> Excellent description.  This understandable to me since I can envision
> doing this with pointers.  But I have no idea how Python actually
> implements this.  It also appears that I am being guided away from
> thinking about it in terms of internal implementation.
>

I assume that you're familiar with the general concept of hash tables.
Scopes in Python are hash tables mapping strings to Python objects.
Names are keys into the hash table.

a = 10

is the same as
currentScope["a"] = 10

print a

is the same as
print currentScope["a"]

As you can see, there's no way that assignment can result in any sort
of sharing. The only way that changes can be seen between shared
objects is if they are mutated via mutating methods.

Python objects (the values in the hashtable) are refcounted and can be
shared between any scope.

> > When you pass an object as a parameter to a function, the object
> > receives a new sticky-label: the parameter name under which it was
> > received into the function scope. Assignment is an act of binding a
> > name to an object; no new object is created, and it still has all the
> > other names it had before.
>

Each scope is it's own hashtable. The values can be shared, but not
the keys. When you call a function, the objects (retrieved from the
callers local scope by name) are inserted into the functions local
scope, bound to the names in the function signature. This is what
Guido calls "call by object reference".



> Ok, so I can understand the code above now.
>
> In the first case I pass the reference to the list to change().  In the
> function, some_list is another name referring to the actual object
> [1,2,3].  Then the function changes the object referred to by the second
> element of the list to be a 4 instead of a 2.  (Oh, the concept applies
> here too!)  Out of the function, the name x refers to the list which has
> been changed.
>
> In the second case, y refers to a '1' object and when the function is
> called the object 1 now gets a new reference (name) x inside the
> function.  But then a new object '0' is assigned to the x name.  But the
> y name still refers to a '1'.
>
> I get it.  But I don't like it.  Yet.  Not sure how this will grow on me.
>

You need to learn about Pythons scoping now, not it's object passing
semantics. When you're used to thinking in terms of pointers and
memory addresses it can take some work to divorce yourself from those
habits.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fast powerset function

2007-07-13 Thread Jyotirmoy Bhattacharya
On Jul 13, 6:34 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
> def recursive_powerset(s):
> if not s: yield set()
> for x in s:
> s2 = s - set([x])
> for subset in recursive_powerset(s2):
> yield subset
> yield subset.union(set([x]))
>
Your recursive_powerset is buggy--it generates too many sets. The loop
over the elements of s is unnecessary. Here is one alternative:

def recursive_powerset(s):
   def do_recursive(S):
   if not S:
   yield set([])
   return
   x=set(S.pop())
   for t in do_recursive(S):
   yield t
   yield t|x
   return do_recursive(s.copy())

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


RE: Tibco Rendezvous

2007-07-13 Thread Kip Lehman


Circa summer 2003, at a company I previously worked at, a co-worker and
I had an occasion to see if we could get Python and TIBCO Rendezvous
working together.

The SWIG-based tibrv mechanism was insufficient, buggy and was problematic
in terms of keeping up with Python releases.

We resorted to using ctypes with the relevant TIBCO header files
and confabulating our own package to work with TIBCO Rendezvous messages
(both publishing and subscribing).
We didn't concern ourselves with certified messages.

Feel free to contact me directly if you want me to see if I can 
unearth any further info.



--

--
Kip Lehman
kipster  t  earthlink  net

...still waiting for PanAm, Amtrack and the USPS to deliver my .sig

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


NoneType object not iterable

2007-07-13 Thread tom
Hi!
My code is

 > db = {}
 >
> def display():
> keyList = db.keys()
> sortedList = keyList.sort()
> for name in sortedList:
> line = 'Name: %s, Number: %s' % (name, db[name])
> print line.replace('\r', '')

And it gives following error:

> for name in sortedList:
> TypeError: 'NoneType' object is not iterable

How can sortedList variable turn into NoneType? I just don't get it...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fast powerset function

2007-07-13 Thread Carsten Haese
On Fri, 2007-07-13 at 17:38 +, Jyotirmoy Bhattacharya wrote:
> On Jul 13, 6:34 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
> > def recursive_powerset(s):
> > if not s: yield set()
> > for x in s:
> > s2 = s - set([x])
> > for subset in recursive_powerset(s2):
> > yield subset
> > yield subset.union(set([x]))
> >
> Your recursive_powerset is buggy--it generates too many sets. The loop
> over the elements of s is unnecessary. Here is one alternative:
> 
> def recursive_powerset(s):
>def do_recursive(S):
>if not S:
>yield set([])
>return
>x=set(S.pop())
>for t in do_recursive(S):
>yield t
>yield t|x
>return do_recursive(s.copy())

Right you are. Note however that x=set(S.pop()) should be
x=set([S.pop()]) for this to run.

Forget everything I've said about timing comparisons, the correct
recursive implementation is actually faster than the iterative
implementation I was testing.

-Carsten


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


Re: NoneType object not iterable

2007-07-13 Thread Stargaming
[EMAIL PROTECTED] schrieb:
> Hi!
> My code is
> 
>  > db = {}
>  >
> 
>> def display():
>> keyList = db.keys()
>> sortedList = keyList.sort()
>> for name in sortedList:
>> line = 'Name: %s, Number: %s' % (name, db[name])
>> print line.replace('\r', '')
> 
> 
> And it gives following error:
> 
>> for name in sortedList:
>> TypeError: 'NoneType' object is not iterable
> 
> 
> How can sortedList variable turn into NoneType? I just don't get it...

It does not turn into something. The `sort()` method just works "in 
place", i. e. it will mutate the list it has been called with. It 
returns None (because there is no other sensible return value).

For you, that means: You don't have to distinguish between keyList and 
sortedList. Just call ``.sort()`` on keyList and it will just work.

HTH,
Stargaming

P.S. same information is in the docs: 
http://docs.python.org/lib/typesseq-mutable.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can a low-level programmer learn OOP?

2007-07-13 Thread Simon Hibbs
Chris,

I can fully relate to your post. I trained as a programmer in the 80s
when OOP was an accademic novelty, and didn't learn OOP untill around
2002. However now I find myself naturaly thinking in OOP terms,
although I'm by no means an expert - I'm a sysadmin that writes the
occasional utility. I found learning OOP with Python very easy because
it has such a stripped-down and convenient syntax.

The advantages of OOP aren't in performance or memory, they're in the
fact that OOP simplifies the ways in which we can think about and
solve a problem. OOP packages up the functionality of a program into
logical units (objects) which can be written, debugged and maintained
independently of the rest of the programme almost as if they were
completely seperate programmes of their own, with their own data and
'user inteface' in the form of callable functions (actualy methods).

Here's a realy excellent tutorial on Python that's fun to follow.
Downloading and installing python, and following this tutorial will
probably take about as long as it took to write your post in the first
place. At the end of it you'll have a good idea how OOP works, and how
Python works. Learning OOp this way is easy and painless, and what you
learn about the theory and principles of OOP in Python will be
transferable to C++ if you end up going in that direction.

I hope this was helpful.

Simon Hibbs


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


Re: Can a low-level programmer learn OOP?

2007-07-13 Thread Simon Hibbs

Sorry, here's the tutorial link:

http://hetland.org/writing/instant-python.html


Simon Hibbs

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


Re: Can a low-level programmer learn OOP?

2007-07-13 Thread Chris Carlen
John Nagle wrote:
> Chris Carlen wrote:[edit]
>> Hence, being a hardware designer rather than a computer scientist, I 
>> am conditioned to think like a machine.  I think this is the main 
>> reason why OOP has always repelled me.
> 
> Why?

When pointers were first explined to me, I went "Ok."  And rather 
quickly ideas lit up in my head about what I could do with them.

When I read what OOP is, that doesn't happen.  All I think is "what's 
the point of this?"  "What can this do for me that I can do already with 
the procedural way of thinking?"  And if it can't do anything new, then 
why rearrange my thinking to a new terminology?  It's results that 
matter, not the paradigm.

> I've written extensively in C++, including hard real-time programming
> in C++ under QNX for a DARPA Grand Challenge vehicle.

Did the vehicle win?

> I have an Atmel
> AVR with a cable plugged into the JTAG port sitting on my desk right now.
> Even that little thing can be programmed in C++.

Yes.

> You can sometimes get better performance in C++ than in C, because C++
> has "inline".  Inline expansion happens before optimization, so you
> can have abstractions that cost nothing.

That's interesting.  But why is this any different than using 
preprocessor macros in C?

> 
> If it has state and functions, it probably should be an object.
> The instances of the object can be static in C++; dynamic memory
> allocation isn't required in C++, as it is in Python.

Why?  Why is OOP any better at explaining a state machine to a computer? 
  I can write state machines all over the place in C, which tend to be 
the core of most of my embedded programs.  I can write them with 
hardcoded logic if that seems like the easy thing to do any the 
probability of extensive changes is extremely low.  They are extremely 
easy to read and to code.  I have written a table-driven state machine 
with arbitrary-length input condition lists.  The work was all in 
designing the data structures.  The code to update the state machine was 
about 4 lines.

Why would OOP be better?  Different is not better.  Popular is not 
better.  What the academics say is not better.  Less lines of code might 
be better, if the priority is ease of programming.  Or, less machine 
execution time or memory usage might be better, if that is the priority.

Until I can clearly understand why one or the other of those goals might 
better be realized for a given problem with OOP vs. procedures, I just 
don't get it.

I will keep an open mind however, that until I work with it for some 
time there is still the possibility that I will have some light go on 
about OOP.  So don't worry, I'm not rejecting your input.

> Python is a relatively easy language, easier than C++, Java,
> or even Perl.  It's quite forgiving.  The main implementation,
> CPython, is about 60x slower than C, though, so if you're trying
> to implement, say, a rapidly changing digital oscilloscope display,
> the result may be sluggish.

Yes, I certainly wouldn't consider Python for that.

Thanks for your comments.


-- 
Good day!


Christopher R. Carlen
Principal Laser&Electronics Technologist
Sandia National Laboratories CA USA
[EMAIL PROTECTED]
NOTE, delete texts: "RemoveThis" and
"BOGUS" from email address to reply.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NoneType object not iterable

2007-07-13 Thread Bjoern Schliessmann
Daniel wrote:

> db is out of scope, you have to pass it to the function:

What's wrong about module attributes?

Regards,


Björn

-- 
BOFH excuse #418:

Sysadmins busy fighting SPAM.

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


Re: 2**2**2**2**2 wrong? Bug?

2007-07-13 Thread Wayne Brehaut
On Mon, 09 Jul 2007 23:51:25 -0700, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:

>On Jul 9, 11:42?pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
>> On Jul 9, 11:21 pm, "Jim Langston" <[EMAIL PROTECTED]> wrote:> In Python 2.5 
>> on intel, the statement
>> > 2**2**2**2**2
>> > evaluates to>>> 2**2**2**2**2
>>
>> > 200352993040684646497907235156025575044782547556975141926501697371089405955
>> >   63114
>> > 530895061308809333481010382343429072631818229493821188126688695063647615470
>> >   29165
>> > 041871916351587966347219442930927982084309104855990570159318959639524863372
>> >   36720
>>
>> 
>>
>> Exponentiation is right associative, so this is the same as:
>>
>> 2**(2**(2**(2**2)))
>> 2**2**2**4
>> 2**2**16
>> 2**65536
>>
>> 2=10**0.3010, so 2**65536 is approx 10**19726
>>
>> There are 19730 digits in your answer,
>
 import gmpy
 n = 2**2**2**2**2
 gmpy.numdigits(n)
>19729
>
>Did you count the 'L'?

numdigits(n)?

What?  'L' is a digit in Python?  I'm going back to Fortran!

wwwayne

>>so this seems to be at least in
>> the ball park.
>>
>> -- Paul
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fast powerset function

2007-07-13 Thread Evan Klitzke
On 7/12/07, Arash Arfaee <[EMAIL PROTECTED]> wrote:
> I need a powerset generator function. It's really slow with recursion. Does
> anybody have any idea or code(!!) to do it in an acceptable time?
> Thanks
> -Arash

Here's a much simpler (and faster) solution I got from a coworker:

s = range(18)
result = []

l = len(s)
for i in range(2**l):
n = i
x = []
for j in range(l):
if n & 1:
x.append(s[j])
n >>= 1
result.append(x)

print result


-- 
Evan Klitzke <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Understanding python functions - Instant Python tutorial

2007-07-13 Thread Wayne Brehaut
On Fri, 13 Jul 2007 18:49:06 +0200, Wildemar Wildenburger
<[EMAIL PROTECTED]> wrote:

>Wildemar Wildenburger wrote:
>> x = [1, 2, 3]
>> y = [1, 2, 3]
>> id(x), id(y)
>> x == y
>> x is y
>>   
>Ooops!
>
>Make that:
>
>x = [1, 2, 3]
>y = [1, 2, 3]
>id(x); id(y)
>x == y
>x is y
>
>(had to be a semicolon there)

Not "had to be" since a discerning reader will note that the two
values in the list:

>>> id(x), id(y)
(19105872, 19091664)

are different, and can guess that id() means "address of".  But "nicer
to be" perhaps since it makes it even more clea rto discerning
readers, and more likely clear to others.  ;-)

>>> id(x); id(y)
19105872
19091664

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


Re: NoneType object not iterable

2007-07-13 Thread Daniel
On Fri, 13 Jul 2007 20:44:13 +0300, <[EMAIL PROTECTED]> wrote:

>
> Hi!
> My code is
>
>  > db = {}
>  >
>> def display():
>> keyList = db.keys()
>> sortedList = keyList.sort()
>> for name in sortedList:
>> line = 'Name: %s, Number: %s' % (name, db[name])
>> print line.replace('\r', '')
>
> And it gives following error:
>
>> for name in sortedList:
>> TypeError: 'NoneType' object is not iterable
>
> How can sortedList variable turn into NoneType? I just don't get it...

db is out of scope, you have to pass it to the function:
>> def display(db):
>> keyList = db.keys()
>> sortedList = keyList.sort()
>> for name in sortedList:
>> line = 'Name: %s, Number: %s' % (name, db[name])
>> print line.replace('\r', '')


-- 
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NoneType object not iterable

2007-07-13 Thread Daniel
On Fri, 13 Jul 2007 21:13:20 +0300, Bjoern Schliessmann  
<[EMAIL PROTECTED]> wrote:

>
> Daniel wrote:
>
>> db is out of scope, you have to pass it to the function:
>
> What's wrong about module attributes?
>

I made a mistake
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NoneType object not iterable

2007-07-13 Thread Paul Rubin
Stargaming <[EMAIL PROTECTED]> writes:
> It does not turn into something. The `sort()` method just works "in
> place", i. e. it will mutate the list it has been called with. It
> returns None (because there is no other sensible return value).
> 
> For you, that means: You don't have to distinguish between keyList and
> sortedList. Just call ``.sort()`` on keyList and it will just work.

Alternatively, use
   sortedList = sorted(keyList)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Understanding python functions - Instant Python tutorial

2007-07-13 Thread Steve Holden
Chris Mellon wrote:
> On 7/13/07, Chris Carlen <[EMAIL PROTECTED]> wrote:
>> Ben Finney wrote:
>>> Chris Carlen <[EMAIL PROTECTED]> writes:
> 
>>> That's not how Python works. Every value is an object; the assignment
>>> operator binds a name to an object. This is more like writing the name
>>> on a sticky-note, and sticking it onto the object.
>>>
>>>   * The object itself doesn't change or "move".
>>>
>>>   * The object can be referred to by that name, but isn't "inside" the
>>> name in any way.
>>>
>>>   * Assigning multiple names to the same object just means you can
>>> refer to that same object by all those names.
>>>
>>>   * When a name goes away, the object still exists -- but it can't be
>>> referred to if there are no longer any names left on it.
>>>
>>>   * Assigning a different object to an existing name just means that
>>> the same sticky-note has moved from the original object to the new
>>> one. Referring to the same name now references a different object,
>>> while the existing object keeps all the other names it had.
>> Excellent description.  This understandable to me since I can envision
>> doing this with pointers.  But I have no idea how Python actually
>> implements this.  It also appears that I am being guided away from
>> thinking about it in terms of internal implementation.
>>
> 
> I assume that you're familiar with the general concept of hash tables.
> Scopes in Python are hash tables mapping strings to Python objects.
> Names are keys into the hash table.
> 
> a = 10
> 
> is the same as
> currentScope["a"] = 10
> 
> print a
> 
> is the same as
> print currentScope["a"]
> 
> As you can see, there's no way that assignment can result in any sort
> of sharing. The only way that changes can be seen between shared
> objects is if they are mutated via mutating methods.
> 
> Python objects (the values in the hashtable) are refcounted and can be
> shared between any scope.
> 
>>> When you pass an object as a parameter to a function, the object
>>> receives a new sticky-label: the parameter name under which it was
>>> received into the function scope. Assignment is an act of binding a
>>> name to an object; no new object is created, and it still has all the
>>> other names it had before.
> 
> Each scope is it's own hashtable. The values can be shared, but not
> the keys. When you call a function, the objects (retrieved from the
> callers local scope by name) are inserted into the functions local
> scope, bound to the names in the function signature. This is what
> Guido calls "call by object reference".
> 
This is, of course, something of an oversimplification. First, the 
global statement allows you to modify a name of module scope from inside 
another scope such as a functions.

> 
> 
>> Ok, so I can understand the code above now.
>>
>> In the first case I pass the reference to the list to change().  In the
>> function, some_list is another name referring to the actual object
>> [1,2,3].  Then the function changes the object referred to by the second
>> element of the list to be a 4 instead of a 2.  (Oh, the concept applies
>> here too!)  Out of the function, the name x refers to the list which has
>> been changed.
>>
>> In the second case, y refers to a '1' object and when the function is
>> called the object 1 now gets a new reference (name) x inside the
>> function.  But then a new object '0' is assigned to the x name.  But the
>> y name still refers to a '1'.
>>
>> I get it.  But I don't like it.  Yet.  Not sure how this will grow on me.
>>
> 
> You need to learn about Pythons scoping now, not it's object passing
> semantics. When you're used to thinking in terms of pointers and
> memory addresses it can take some work to divorce yourself from those
> habits.

Then, of course, there are the nested scoping rule for functions defined 
inside other functions.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


A Python newbie ask a simple question

2007-07-13 Thread xing93111
what does the statement "choice = raw_input(prompt)[0]" mean? I don't
know why there is a '[0]' in the statement.

Thank you very much

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


Re: renaming an open file in nt like unix?

2007-07-13 Thread Steve Holden
Thomas Heller wrote:
> [EMAIL PROTECTED] schrieb:
>> Hi.  I'm writing an archival system which I'd like to be portable
>> to Windows.
>>
>> The system relies on the property of Unix which allows a
>> process to keep a file open even if another process renames
>> it while it is open.  Neither process sees any anomaly or
>> error.
>>
>> Do the NT file systems support this feature (which I think is
>> standard for POSIX systems)?
> 
> Yes, you can do that.  We implemented something like this to replace
> dlls there are currently in use - rename the currently open file, create a 
> new one
> with the old name (newly started processes will use the new one then),
> and delete the renamed one at the next possible occasion (usually at
> the next reboot).  I'm not so sure on which NT versions it works this
> way, at least in w2000 and newer.
> 
> Thomas
> 
You do have to be careful though, because sometimes Windows refuses to 
let you rename a file because it's in use.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: sys.exit versus termination of source code

2007-07-13 Thread Steve Holden
Carl DHalluin wrote:
> Hi,
> 
>  
> 
> I am playing with the atexit module but I don’t find a way to see the 
> difference
> 
> between a script calling sys.exit() and the interpreting 
> arriving at the end
> 
> of the source code file. This has a semantic difference for my applications.
> 
> Is there a way to determine in an exithandler (that is registered using 
> atexit.register)
> 
> how I exited?
> 
I don't believe so.

>  
> 
> Second question: is there a way to determine in my exithandler what the 
> return code was.
> 
> atexit doesn’t seem to support that
> 
I don't believe so.
>  
> 
> Third question: I can solve part of my problem by reassigning sys.exit = 
> myfunction
> 
> Is that a wise idea?
> 
>  
> 
> Thanks
> 
> Carl D’Halluin
> 
> www.qlayer.com
> 
It would be much more sensible to replace the calls to sys.exit with 
calls to some function that sets the required "this was not falling off 
the end" indication and then calls sys.exit.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: A Python newbie ask a simple question

2007-07-13 Thread Jeff McNeil
The raw_input built-in returns a string.  The '[0]' subscript returns
the first character in the user supplied response as strings support
indexing.

[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mystr = "asdf"
>>> mystr[0]
'a'
>>>

>>> raw_input("Another one, please: ")[0]
Another one, please: ASDF
'A'
>>>

-Jeff

On 7/13/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> what does the statement "choice = raw_input(prompt)[0]" mean? I don't
> know why there is a '[0]' in the statement.
>
> Thank you very much
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-13 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 Paul Rubin  wrote:

> Ben Finney <[EMAIL PROTECTED]> writes:
> > This is interesting. Do you have any references we can read about this
> > assertion -- specifically, that "GOTO" was not well loved (I assume
> > "by the programming community at large") even by around 1966?
> 
> Dijkstra's famous 1968 "GOTO considered harmful" letter
> (http://www.acm.org/classics/oct95/) quotes a 1966 article by N. Wirth
> and C.A.R. Hoare:
> 
> The remark about the undesirability of the go to statement is far from
> new. I remember having read the explicit recommendation to restrict
> the use of the go to statement to alarm exits, but I have not been
> able to trace it; presumably, it has been made by C. A. R. Hoare. In
> [1, Sec. 3.2.1.] Wirth and Hoare together make a remark in the same
> direction in motivating the case construction: "Like the conditional,
> it mirrors the dynamic structure of a program more clearly than go to
> statements and switches, and it eliminates the need for introducing a
> large number of labels in the program."
> 
> Reference: 1. Wirth, Niklaus, and Hoare C. A. R.  A contribution
> to the development of ALGOL. Comm. ACM 9 (June 1966), 413-432.

So, all I need is comments from a computer scientist or two,
pointing out problems with the procedural/imperative programming
model, and we can establish that it was already hated and on its
way out by the late 90's?  How about OOP?  Already on its way out
by the time Python 1.0 hit the streets?

The thing that allows us to be so smug about the follies of the
past, is that we can pretend everyone knew better.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2**2**2**2**2 wrong? Bug?

2007-07-13 Thread Paul McGuire
On Jul 13, 1:20 pm, Wayne Brehaut <[EMAIL PROTECTED]> wrote:
> On Mon, 09 Jul 2007 23:51:25 -0700, "[EMAIL PROTECTED]"
>
>
>
>
>
> <[EMAIL PROTECTED]> wrote:
> >On Jul 9, 11:42?pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
> >> On Jul 9, 11:21 pm, "Jim Langston" <[EMAIL PROTECTED]> wrote:> In Python 
> >> 2.5 on intel, the statement
> >> > 2**2**2**2**2
> >> > evaluates to>>> 2**2**2**2**2
>
> >> > 200352993040684646497907235156025575044782547556975141926501697371089405955
> >> >   63114
> >> > 530895061308809333481010382343429072631818229493821188126688695063647615470
> >> >   29165
> >> > 041871916351587966347219442930927982084309104855990570159318959639524863372
> >> >   36720
>
> >> 
>
> >> Exponentiation is right associative, so this is the same as:
>
> >> 2**(2**(2**(2**2)))
> >> 2**2**2**4
> >> 2**2**16
> >> 2**65536
>
> >> 2=10**0.3010, so 2**65536 is approx 10**19726
>
> >> There are 19730 digits in your answer,
>
>  import gmpy
>  n = 2**2**2**2**2
>  gmpy.numdigits(n)
> >19729
>
> >Did you count the 'L'?
>
> numdigits(n)?
>
> What?  'L' is a digit in Python?  I'm going back to Fortran!
>
> wwwayne
>
>
>
> >>so this seems to be at least in
> >> the ball park.
>
> >> -- Paul- Hide quoted text -
>
> - Show quoted text -- Hide quoted text -
>
> - Show quoted text -

'L' counts for 50, but only when you use Roman font.

-- Paul

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


Re: Can a low-level programmer learn OOP?

2007-07-13 Thread Evan Klitzke
On 7/13/07, John Nagle <[EMAIL PROTECTED]> wrote:
>  You can sometimes get better performance in C++ than in C, because C++
> has "inline".  Inline expansion happens before optimization, so you
> can have abstractions that cost nothing.

This is a bit off topic, but inline is a keyword in C since C99.

-- 
Evan Klitzke <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Numpy array index handling

2007-07-13 Thread phishboh
Being a Matlab user wanting to switch to Python/SciPy, I'd like to
know how the following Matlab code would be written in Python:

% First, just some artificial data
N = 100 ;
input = sign(randn(1, N)) ;
a = (1 : N) ;
% This is what I'd like to do;
% for indices where the input has a certain value, compute and store
something
% for indices where the input has another certain value, compute and
store something else
output(input < 0) = 10 * a(input < 0) ;
output(input > 0) = 20 * a(input > 0) ;

I have tried the following in Python:
N = 100
input = sign(randn(N))
a = arange(N)
output = zeros(N)
output[input < 0] = 10 * a[input < 0]
output[input > 0] = 20 * a[input > 0]

However, that gives me in IndexError.

Of course I could use a for-loop, but I assume that there is another
way (although I haven't been able to find it in any documentation).

Many thanks in advance!

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


  1   2   >