Re: newbie: dictionary - howto get key value

2005-03-14 Thread Peter Otten
Joal Heagney wrote:

> Does python guarantee that the lists given by phone.values() and
> phone.keys() are in mutual order? Or is it possible that python will
> return the lists in different orders for .values() and .keys()?
 
Yes. Quoted from http://docs.python.org/lib/typesmapping.html:

Keys and values are listed in an arbitrary order which is non-random, varies
across Python implementations, and depends on the dictionary's history of
insertions and deletions. If items(), keys(), values(), iteritems(),
iterkeys(), and itervalues() are called with no intervening modifications
to the dictionary, the lists will directly correspond. This allows the
creation of (value, key) pairs using zip(): "pairs = zip(a.values(),
a.keys())". The same relationship holds for the iterkeys() and itervalues()
methods: "pairs = zip(a.itervalues(), a.iterkeys())" provides the same
value for pairs. Another way to create the same list is "pairs = [(v, k)
for (k, v) in a.iteritems()]". 

Peter 

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


Re: Generating data types automatically

2005-03-14 Thread Thomas Heller
Torsten Bronger <[EMAIL PROTECTED]> writes:

> Hallöchen!
>
> I have to generate a lot of data types (for ctypes by the way).  An
> example is
>
> ViUInt32  = u_long
> ViPUInt32 = POINTER(ViUInt32)
> ViAUInt32 = ViPUInt32
>
> Therefore, I defined functions that should make my life easier:
>
> def generate_type_dublett(visa_type, ctypes_type):
> visa_type_name = visa_type.__name__
> exec visa_type_name + "=" + ctypes_type.__name__
> exec "ViP" + visa_type_name[2:] + "=POINTER(" + visa_type_name + ")"
>
> def generate_type_triplett(visa_type, ctypes_type):
> generate_type_dublett(visa_type, ctypes_type)
> visa_type_name = visa_type.__name__
> exec "ViA" + visa_type_name[2:] + "=" + "ViP" + visa_type_name[2:]
>
> generate_type_triplett(ViUInt32, c_ulong)
>
>
> However, this doesn't work, probably because the defined type exist
> only locally within the function.

Others have answered your question already, but I would like to note one
thing:  The POINTER() function caches its results, so you could (and
should, imo) write 'POINTER(ViUInt32)' instead everywhere in your code.
Calling POINTER(ViUInt32) *allways* returns the same type.

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


Re: Web framework

2005-03-14 Thread Joe
On Sun, 13 Mar 2005 19:20:34 +0100, "Diez B. Roggisch"
<[EMAIL PROTECTED]> wrote:
>Plain wrong. You can access them via FTP and WEBDAV.

Not wrong. I am aware of this, but it's not like that many development
tools can work through FTP or WebDav... Besides, how to have the
source code under source control if it's stuck in the ZODB?

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


Re: Itertools wishlists

2005-03-14 Thread Ville Vainio
> "Raymond" == Raymond Hettinger <[EMAIL PROTECTED]> writes:

Raymond> Each one of the options listed is a reason that flatten()
Raymond> shouldn't be an itertool.  It fails tests of obviousness,
Raymond> learnability, complexity of implementation, and
Raymond> simplicity of API.  The options also suggest that the
Raymond> abstraction is not as basic or universal as we would
Raymond> hope.

A simpler API:

def flatten(sequence, atomic_test = lambda o: isinstance(o,basestring)):
  """ don't recurse into iterables if atomic_test -> True """

I believe speaking of the "levels" of flattening is contorted here.

Raymond> Perhaps "require" was the wrong word.  The issue is that
Raymond> appear to be very few real situations where flatten()
Raymond> would be the tool of choice.

Suppose that I get a very complex data structure involving lists of
tuples of tuples [] of strings. I just want to quickly search the
sequence for valid file names, without going through elaborate
unpacking. Then I just do

files = (f fof f in flatten(monster_data_struct) if os.path.isfile(str(f)))

Yep, this is a real use case (ipython + some of my own data munging
tools).

Raymond> Generalizing the two results, it may be fair to say that
Raymond> the desire to flatten is a code smell indicating that
Raymond> structure is being unnecessarily destroyed or that
Raymond> earlier processing introduced unwanted structure.  Let
Raymond> the data guide the programming.

You are looking the problem from a specific mindset, that of writing
good clean pythonic code. flatten is for situations when you need an
implementation 20 seconds ago (where someone might have recommended
perl in the past, and which is a perfectly valid niche for Python as
well).

It's not a matter of life & death for me, obviously (it's in my own
stdlib). I still can't see how its existence would make rest of
itertools magically harder to learn. When I come up with a problem
where I imagine itertools might come in handy, I check the docs to see
whether there is anything appropriate for the problem. I don't
memorize all the functions, just the fact that such functions
exist.

Also, the following itertool functions are not very useful anymore,
with the advent of genexps:

ifilter(pred, seq) --> elements of seq where pred(elem) is True
ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False
imap(fun, p, q, ...) --> fun(p0, q0), fun(p1, q1), ...
starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ...

I don't believe a genuinely useful 'flatten' would increase the
cognitive load any more than these.

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expressions: large amount of or's

2005-03-14 Thread Daniel Yoo
Daniel Yoo <[EMAIL PROTECTED]> wrote:
: John Machin <[EMAIL PROTECTED]> wrote:


: : tree.search("I went to alpha beta the other day to pick up some spam")

: : could use a startpos (default=0) argument for efficiently restarting
: : the search after finding the first match

: Ok, that's easy to fix.  I'll do that tonight.

Done.  'startpos' and other bug fixes are in Release 0.7:

http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ahocorasick-0.7.tar.gz

But I think I'd better hold off adding the ahocorasick package to PyPI
until it stabilizes for longer than a day... *grin*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Add Properties to Instances?

2005-03-14 Thread Martin Miller
In answer to my question about instance properties not working, Bengt
Richter suggest using:
> > >>> class InstProp(object):
> > ... def __getattribute__(self, attr):
> > ... p = object.__getattribute__(self, attr)
> > ... if isinstance(p, property): return p.__get__(self)
> > ... return p

and more generally for any descriptor object:

>  >>> class InstProp(object):
>  ... def __getattribute__(self, attr):
>  ... p = object.__getattribute__(self, attr)
>  ... if hasattr(p, '__get__'): return p.__get__(self,
type(self))
>  ... return p

Both the above makes the '__get__' method of any property attributes of
the instance to be used. However, it does not cause attempts to be made
to access their "__set__' methods when assigning to them (which should
fail in my case because my properties don't have such a method because
they are read-only).

Just overriding '__getattribute__' alone is insufficent to make
instance property/descriptor attributes fully function. To do so also
requires overriding the __setattr__ method so it checks for a '__set__'
method and then uses it if one is found (or delegates it to
object.__setattr__ if not).

Similarily, an override for '__delattr__' would also be need for
complete property functionality, I believe.

For just making instance attributes read-only, it seems to be that the
simplist solution would be to override __setattr__ and make it check to
see if the attribute is write protected or not, which is really all I
need for the specific task I'm trying to accomplish (which is
esstentially what Jeremy Bowers said in his reply).

What still puzzles me, though, is why all the above to make properties
work on instances is necessary in the first place. It's certainly not
clear (to me) from what is said in the How-to at:
>
http://users.rcn.com/python/download/Descriptor.htm#invoking-descriptors
I suspect that it may be simply a performance issue, in other words, it
was considered too slow to check for instance property/discriptors --
although *why* is not clear to me.

Best Regards,
Martin

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


{SPAM} Remote debugging with boa constructor

2005-03-14 Thread Gijs Korremans
Hi,

I'm a newby on the Python language but I have to modify an excisting pyhon 
application which runs as a Windows NT service (on 2003 server). I've heared 
that it's possible to debug an application with boa constructor over the 
internet, I tried some things what I found on the internet but it doesn't work. 
Does anybody know how to do this?
Debugging is working on a local pc.

tnx

Gijs

--
This message has been scanned for viruses and
dangerous content by Network Sentry, and is
believed to be clean.
http://www.networksentry.co.za

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


Re: [Python-Dev] RELEASED Python 2.4.1, release candidate 1

2005-03-14 Thread Richie Hindle

[Martin]
> However, I just noticed that the python24.dll is in c:\python24. Could
> it be that you have another one in \windows\system32?

I do, yes.

> If so, could it
> also be that the installer has told you that the target directory 
> exists, and asked whether you want to proceed anyway?

It probably did, yes.

> In that case, your 2.4 installation was a per-user installation, and the
> 2.4.1c1 installation was a per-machine (allusers) installation. These
> are mutually not upgradable, so you should now have the option of
> uninstalling both in add-and-remove programs.

I'd be surprised if the existing 2.4 was per-user, because I usually ask
for all-users.  It's possibly that it was an all-users installation but I
copied the DLL into C:\Python24 for some reason [...digs around...] yes, I
think that must be the case.  It has a creation date much later than
C:\python24\Lib, for example.

The python24.dll in C:\windows\system32 is 2.4.1c1.  In which case, I
think it all worked perfectly but didn't take into account my manual
addition of python24.dll to C:\python24 - which is fair enough, really.

[ I only see "Python 2.4.1c1" in the Add/Remove list, and no other Python
  2.4 entries (apart from the likes of "Python 2.4 ctypes-0.9.2") but
  that's to be expected. ]

Thanks for looking into this, and sorry to take up your time with
something that boils down to user error.

-- 
Richie Hindle
[EMAIL PROTECTED]

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


Re: injecting "set" into 2.3's builtins?

2005-03-14 Thread Pete Forman
Skip Montanaro <[EMAIL PROTECTED]> writes:

 > Stephen> I have:
 > Stephen> try:
 > Stephen> set
 > Stephen> except NameError:
 > Stephen> from sets import Set as set
>
 > Stephen> in my code in a few places.
>
 > Yes, but then pychecker complains about a statement with no apparent effect,
 > hence the extra verbiage.
>
 > My question wasn't about a less ugly way to type what I type now.  It was
 > about whether injecting "set" into the builtins (so I can dispense with the
 > above cruft altogether) is likely to cause problems.  I think not, certainly
 > based on what little surveying I've done at work.  I was hoping someone else
 > had already tried this and could report on their experience.

This is what I use to allow my 2.4 code to run on 2.3.

if not 'set' in dir(__builtins__):
from sets import Set as set, ImmutableSet as frozenset

-- 
Pete Forman-./\.-  Disclaimer: This post is originated
WesternGeco  -./\.-   by myself and does not represent
[EMAIL PROTECTED]-./\.-   opinion of Schlumberger, Baker
http://petef.port5.com   -./\.-   Hughes or their divisions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Add Properties to Instances?

2005-03-14 Thread Bengt Richter
On 14 Mar 2005 01:19:23 -0800, "Martin Miller" <[EMAIL PROTECTED]> wrote:

>In answer to my question about instance properties not working, Bengt
>Richter suggest using:
>> > >>> class InstProp(object):
>> > ... def __getattribute__(self, attr):
>> > ... p = object.__getattribute__(self, attr)
>> > ... if isinstance(p, property): return p.__get__(self)
>> > ... return p
>
>and more generally for any descriptor object:
>
>>  >>> class InstProp(object):
>>  ... def __getattribute__(self, attr):
>>  ... p = object.__getattribute__(self, attr)
>>  ... if hasattr(p, '__get__'): return p.__get__(self,
>type(self))
>>  ... return p
>
>Both the above makes the '__get__' method of any property attributes of
>the instance to be used. However, it does not cause attempts to be made
>to access their "__set__' methods when assigning to them (which should
>fail in my case because my properties don't have such a method because
>they are read-only).
>
>Just overriding '__getattribute__' alone is insufficent to make
>instance property/descriptor attributes fully function. To do so also
>requires overriding the __setattr__ method so it checks for a '__set__'
>method and then uses it if one is found (or delegates it to
>object.__setattr__ if not).
>
>Similarily, an override for '__delattr__' would also be need for
>complete property functionality, I believe.
>
As I said in my first post,
"""
If you want robust writeable and/or deleteable properties, you will have
to do a little more work, but it can be done.
"""

I'm still leaving it as an exercise ;-)

>For just making instance attributes read-only, it seems to be that the
>simplist solution would be to override __setattr__ and make it check to
>see if the attribute is write protected or not, which is really all I
>need for the specific task I'm trying to accomplish (which is
>esstentially what Jeremy Bowers said in his reply).
>
>What still puzzles me, though, is why all the above to make properties
>work on instances is necessary in the first place. It's certainly not
>clear (to me) from what is said in the How-to at:
>>
>http://users.rcn.com/python/download/Descriptor.htm#invoking-descriptors
>I suspect that it may be simply a performance issue, in other words, it
>was considered too slow to check for instance property/discriptors --
>although *why* is not clear to me.

I suspect the desired semantics re precedence have evolved to make normal
programs easily implementable, and that probably drove the implementation:
"""
For objects, the machinery is in object.__getattribute__ which transforms
b.x into type(b).__dict__['x'].__get__(b, type(b)).
The implementation works through a precedence chain that gives (my added 
[1,2,3])

[1] data descriptors priority over instance variables,
[2] instance variables priority over non-data descriptors,
[3] and assigns lowest priority to __getattr__ if provided.

The full C implementation can be found in PyObject_GenericGetAttr() in 
Objects/object.c.
"""

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web framework

2005-03-14 Thread Josef Meile
Hi Joe,
Not wrong. I am aware of this, but it's not like that many development
tools can work through FTP or WebDav... Besides, how to have the
source code under source control if it's stuck in the ZODB?
I guess you are reffering to "Python Scripts" and "ZClasses", which
indeed are stuck in the ZODB. But in fact you can write external python
products for zope, which reside on your file system. What is stuck in
the ZODB would be the instances of those products.
Regards,
Josef
--
http://mail.python.org/mailman/listinfo/python-list


Re: Passing values to another script using CGI

2005-03-14 Thread Fuzzyman
Hello Mike,

Mike Wimpe wrote:
> Without creating a form, how do i pass a value to another script?
>
> I would like to pass:
>
> group = "Oranges"
>
> to another script or at least just 'group' and initialize it in the
> first script.
>

Do you want to pass it *from* a CGI script or *two* a CGI script.

If you are calling a remote script (and if you're not it's an odd
question !) then you can just build the query manually.

(When you hit submit the browser builds a request query from the values
in the form. All you need to do is generate the query yoruself instead
of having hte browser do it).

In order to do this you need to understand how parameters are passed to
a CGI script. It can be done either using the 'GET' method or the
'POST' method and the values need to be properly escaped.

The urllib.urlencode function will take a dictionary of parameters and
values and return a query string. If you use urllib2.urlopen to fetch
http://www.someserver.com/cgi-bin/yourscript.py + '?' + query_string
then your CGI will be called with the relevant parameters.

Regards,

Fuzzy
http://www.voidspace.org.uk/python/cgi.shtml


> script1:
> '''
> 
> 
> 
> group = "Oranges"
> '''
>
> script2:
> 
> print ''' Oh you like '''+group+'''.'''
> 
> thanks,
> 
> Mike

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


Re: Working on a log in script to my webpage

2005-03-14 Thread Fuzzyman

Pete. wrote:
> Hi all.
>
> Unfortunaly it looks like I dont have to skill to make a secure log
in, cant
> figure out how the code has to look like, so guess my webpage has to
live
> with a security issue.
>
> Thanks for the effort you put into teaching me the use of cookies.
>

I've written a library called 'login_tools' that does login/user
management for CGI scripts. It doesn't use a database to store logins
though.

You can fins it at (with online example) :
http://www.voidspace.org.uk/python/logintools.html

If you want any help setting it up or working with it then feel free to
email me about it. It's possible to plug it in to existing CGI scripts
with literally two lines of code

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

> Best wishes
> Pete
>
> "Pete." <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > Thanks.
> >
> > But I would really like to do this from scratch, so that I can
learn it, I
> > dont think I need that much more, before it works.
> >
> > I found an example with asp, where the save the session if the
password is
> > correct. It isnt that long a code, so was wondering if it isnt
possible to
> > make something like that in python. Cause when this code is applied
to the
> > loginform, CODE2 will only have to be applied to every following
page and
> > everything is good.
> >
> > code is from:
> >
http://tutorialized.com/tutorial/Creating-a-Members-Area-in-ASP/2234
> > CODE1
> > Set objRS = objConn.Execute (strSQL)
> >  '// see if there are any records returned
> >  If objRS.EOF Then
> >  'no username found
> >  strError = "- Invalid username or password" &
vbNewLine
> >  Else
> >  'check password
> >  If objRS("password")=Request.Form("password") Then
> >   'username/password valid
> >   'save session data
> >   Session("loggedin") = True
> >   Session("userid") = objRS("id")
> >   'redirect to members area
> >   Response.Redirect ("default.asp")
> >   Response.End
> >  Else
> >   'invalid password
> >   strError = "- Invalid username or password" &
vbNewLine
> >
> > CODE2<%
> > If Session("loggedin") <> True Then Response.Redirect "login.asp"
> > %>
> > 
> > 
> > Members Area
> > 
> > 
> > Members Area
> > Welcome to our members area!
> >  In my code I have allready tested if the username and
password is
> > correct, so I just need to do the cookie thing :D
> >
> > Thanks all, hope all my questions dosnt make you tired, I just
really
> > wanna figure this out, and I am doing this as a little hobby of
mine, so I
> > dont have anyone else to ask, hope that is okay...
> >
> >
> >
> > "Kent Johnson" <[EMAIL PROTECTED]> wrote in message
> > news:[EMAIL PROTECTED]
> >> Pete. wrote:
> >>> Hi all I am working on a log in script for my webpage.
> >>>
> >>> I have the username and the password stored in a PostgreSQL
database.
> >>
> >> You might want to look at Snakelets and CherryPy.
> >>
> >> Snakelets is "a very simple-to-use Python web application server."
One of
> >> the features is "Easy user authentication and user login
handling."
> >> http://snakelets.sourceforge.net/
> >>
> >> CherryPy is "a pythonic, object-oriented web development
framework" that
> >> seems to be popular. A recipe for password-protected pages in
CherryPy is
> >> here:
> >> http://www.cherrypy.org/wiki/PasswordProtectedPages
> >>
> >> Kent
> >
> >

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


Re: Web framework

2005-03-14 Thread Diez B. Roggisch
> Not wrong. I am aware of this, but it's not like that many development
> tools can work through FTP or WebDav ..  

If your tools can't, then you can still use ftp clients to push the files to
the server. Actually lots of web-development is done by working locally on
the files, then publishing these to the server. Think of the horror to
create apache modules with certain lib dependencies (e.g. oracle) under
windows. Some people I know even abuse CVS for uploading their files to the
server - which renders CVS pretty useless.

And quite a few tools _are_ capable of directly using ftp as storage
backend. (x)emacs for example.

> Besides, how to have the 
> source code under source control if it's stuck in the ZODB?

You can still fetch it using webdav and ftp and stick it into CVS/SVN. 


-- 
Regards,

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


Listbox fill=BOTH expand=YES (Tkinter)

2005-03-14 Thread Harlin Seritt
I am trying the following:

Listbox(parent).pack(fill=BOTH, expand=YES)

I notice that the listbox will fill on the X axis but will not on the Y
axis unlike other widgets. Is there any way to force this?

thanks,

Harlin

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


Re: Generating data types automatically

2005-03-14 Thread Torsten Bronger
HallÃchen!

Thomas Heller <[EMAIL PROTECTED]> writes:

> Torsten Bronger <[EMAIL PROTECTED]> writes:
>
>> I have to generate a lot of data types (for ctypes by the way).
>> An example is
>>
>> ViUInt32  = u_long
>> ViPUInt32 = POINTER(ViUInt32)
>> ViAUInt32 = ViPUInt32
>>
>> [...]
>
> Others have answered your question already, but I would like to
> note one thing: The POINTER() function caches its results, so you
> could (and should, imo) write 'POINTER(ViUInt32)' instead
> everywhere in your code.  Calling POINTER(ViUInt32) *allways*
> returns the same type.

Actually I don't think that we will use them (ViP...) at all, since
we'll make use of "byref" whereever they occur in an args list.

But they are in the spec that we try to mimic, and as long as I
don't know for sure that nobody uses them, they don't hurt.

TschÃ,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Listbox fill=BOTH expand=YES (Tkinter)

2005-03-14 Thread Martin Franklin
Harlin Seritt wrote:
I am trying the following:
Listbox(parent).pack(fill=BOTH, expand=YES)
I notice that the listbox will fill on the X axis but will not on the Y
axis unlike other widgets. Is there any way to force this?
thanks,
Harlin
Harlin,
It should expand (and fill ) in both directions have you checked it's
parents packing options?
Martin

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


Re: Python-list Digest, Vol 18, Issue 208

2005-03-14 Thread John Roth
"Charles Hartman" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
I know this isnt that big of a problem,
but i cannot think of one reason why they would not allow numbers 
preceded with a 0 to have a number
higher then a 7 in them...
And it seems very inconsistant to me...

Is there a reason for this?
I *love* questions I can answer! Answer: because that's how you tell 
Python you're entering an octal number. (Parallel to 0x for hexadecimals.) 
So beware of 010, which isn't the number of fingers you presumably have, 
unless you don't count the thumbs.
That's a reason, but I don't consider it a good reason.
I cannot, in fact, think of a single time when I've wanted
to enter an octal number. Hex numbers, yes, but  not
octal.
I personally don't think the frequency of use warrents
the special case syntax and the resultant confusion
with novices.
John Roth
Charles Hartman
--
http://mail.python.org/mailman/listinfo/python-list


Re: Wishlist item: itertools.flatten

2005-03-14 Thread Leif K-Brooks
Michael Spencer wrote:
if hasattr(item,"__iter__"): # Avoids iterating over strings
That's probably the cleanest way to avoid strings, but it's 
unfortunately not a good idea IMHO. Many objects (IndexedCatalog's 
Result objects are what I'm concerned about, but there are undoubtedly 
others) still rely entirely on the old-style sequence iteration protocol 
even though they're proper containers, so checking for __iter__ wouldn't 
work on them.  Explicitly doing isinstance(item, basestring) is probably 
the best option until older objects move to the new iteration protocol.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Who Knows of a Good Computational Physics Textbook?

2005-03-14 Thread beliavsky
Sean Richards wrote:
> This may be of interest
>
> http://farside.ph.utexas.edu/teaching/329/lectures/lectures.html

The information at
http://farside.ph.utexas.edu/teaching/329/lectures/node7.html about
scientific programming languages is out of date, since g95
http://www.g95.org is a free Fortran 95 compiler for all platforms (and
is already used in some courses), and Intel Fortran 95 for Linux is
free for non-commercial use.

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


will it cause any problems to open a read-only file & not close it?

2005-03-14 Thread Sara Khalatbari
Dear friends
In a code, I'm opening a file to read. Like :
lines = open(filename).readlines()
& I'm never closing it.
I'm not writing in that file, I just read it.

Will it cause any problems if you open a file to read
& never close it?




__ 
Do you Yahoo!? 
Make Yahoo! your home page 
http://www.yahoo.com/r/hs
-- 
http://mail.python.org/mailman/listinfo/python-list


Encodings and printing unicode

2005-03-14 Thread Fuzzyman
How does the print statement decode unicode strings itis passed ? (By
that I mean which encoding does it use).

Under windows it doesn't appear to use defaultencoding. On my system
the default encoding is ascii, yet the terminal encoding is latin1 (or
cp1252 or whatever, but not ascii). This means that print '£' works
fine, yet unicode('£') will raise the UnicodeDecodeError.

However print u'£' will also work fine. (Under pythonce this same
statement raises a UnicodeDecodeError - but the 'terminal' is
different).

In my understanding unicode is an 'internal representation' - if you
want to write a unicode string to a file you have to turn it into a
byte string and specify an encoding (unless you pickle it - which is
cheating). So when you 'print' a unicode string, what is sent to
sys.stdout ? Is a character encoding used ? If so which one... if
not... why not ?

(In this case if defaultencoding was used it *ought* to raise a
UnicodeDecodeError).

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


Re: will it cause any problems to open a read-only file & not close it?

2005-03-14 Thread John Machin

Sara Khalatbari wrote:
> Dear friends
> In a code, I'm opening a file to read. Like :
> lines = open(filename).readlines()
> & I'm never closing it.
> I'm not writing in that file, I just read it.
>
> Will it cause any problems if you open a file to read
> & never close it?

AFAIK, only if you try to have too many files open at one time -- many
appears to be approx 512 on recent Windows (2000 and XP at least).

However it's a very good habit whatever the language to close / delete
/ deallocate / ... any resource as soon as you no longer need it.

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


optparse alternative

2005-03-14 Thread Henry Ludemann
I've been writing an optparse alternative (using getopt) that is at a
stage where I'd be interested in people's opinions. It allows you to
easily creating command line interfaces to existing functions, using
flags (which are optional) and arguments. It will automatically print a
nicely formatted usage (eg: -h or --help), and easily & automatically
validates parameter existence and type.

You can download it, and read a bit more about it, at


I'm interested in comments and criticisms; I've tried to write it
according to the python coding guildlines.

Example usage of a cmdline usage;

$ python test.py --help
Usage: test.py [OPTIONS] SOMEARG
An example to show usage of command line

Arguments
SOMEARG   Some float argument

Mandatory arguments to long flags are mandatory for short options
too
-h, --helpShow this help page
-s, --setflag Set the flag

Email bug reports to [EMAIL PROTECTED]

Source for the above example;

def someFunc(someArg, someFlag = False):
print "Flag value =", someFlag
print "Arg value =", someArg

from cmdline.Command import Command
command = Command(someFunc, "An example to show usage of command
line", "Email bug reports to [EMAIL PROTECTED]")
command.addFlag('s', 'setflag', 'Set the flag', 'someFlag')
command.addArgument('SOMEARG', 'Some float argument', 'someArg',
float)
command.invoke()

Normal use of test.py would have given

$ python test.py 3
Flag value =  False
Arg value = 3.0

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


Re: urllib's functionality with urllib2

2005-03-14 Thread Fuzzyman

Monty wrote:
> Hello,
> Sorry for this maybe stupid newbie question but I didn't find any
> answer in all my readings about python:
>
> With urllib, using urlretrieve, it's possible to get the number of
> blocks transferred and the total size of the file.
>
> Is it possible to get those informations with urllib2 ?
>
> ( I have to use urllib2 and a Request Object with headers, urlretieve
> doesn't work. Well, at least, all my attempts with urllib were
> denied...)
>

urllib2.urlopen(req)  returns a handle on the URL. This handle has
various properties - if a content length header was sent it will
include that.

If you read from the url in a loop you can do this :

. h = urllib2.urlopen(req)
. print h.info()
. page = ''
. count = 0
. n = 100   # number of bytes to read at a time
. while True:
.a = h.read(n)
.if not a: break
.count += len(a)  # len(a) may not be same as n for final read
.page += a# prob. better to append to a list and do
''.join(a) afterwards
.print 'Now transferred %s bytes.' % count

Does this help ?

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

> Thanks for any help,
> 
> Monty

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


Re: Licensing Python code under the Python license

2005-03-14 Thread Daniel Dittmar
Leif K-Brooks wrote:
Harlin Seritt wrote:
If this is for making money, make it either a proprietary license or
BSD.
If you're giving it away and expect nothing for it except maybe fame,
do GPL.

You're kidding, right? How does the BSD license possibly offer more 
protection for a commercial program than the GPL does?
The BSD license offers less protection than the GPL. But it gives more 
rights to the buyer of the software, so it might be an easier sell.

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


urllib (and urllib2) read all data from page on open()?

2005-03-14 Thread Alex Stapleton
The entire page is downloaded immediately whether you want it to or not when
you do an http request using urllib. This seems slightly broken to me.

Is there anyway to turn this behaviour off and have the objects read method
actually read data from the socket when you ask it to?

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


Re: Licensing Python code under the Python license

2005-03-14 Thread Leif K-Brooks
Harlin Seritt wrote:
If this is for making money, make it either a proprietary license or
BSD.
If you're giving it away and expect nothing for it except maybe fame,
do GPL.
You're kidding, right? How does the BSD license possibly offer more 
protection for a commercial program than the GPL does?
--
http://mail.python.org/mailman/listinfo/python-list


Re: will it cause any problems to open a read-only file & not close it?

2005-03-14 Thread Fuzzyman

Sara Khalatbari wrote:
> Dear friends
> In a code, I'm opening a file to read. Like :
> lines = open(filename).readlines()
> & I'm never closing it.
> I'm not writing in that file, I just read it.
>
> Will it cause any problems if you open a file to read
> & never close it?
>
>

Under CPython the filehandle will be automatically garbage collected.
Under JPython (Jython) it won't be... It's a very useful shortcut
though *sigh*

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

>
>
> __
> Do you Yahoo!?
> Make Yahoo! your home page 
> http://www.yahoo.com/r/hs

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


Re: Apparently, I don't understand threading

2005-03-14 Thread Jeff Epler
Ah -- I'm sorry I was off-target, and I'm glad someone else had what may
be better advice for you.

Jeff


pgptOZnkOhiE1.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

How do I pass structures using a C extension?

2005-03-14 Thread [EMAIL PROTECTED]
Hi.

I trying to write an extension module to call some C libraries so I can
use them in Python. Several of the library functions pass pointers to
structures as arguments. I was thinking that I could create a class for
each structure, but I'm not sure how to get the data back and forth.
The example the "Extending and Embedding the Python Interpreter" manual
has examples of passing strings and ints using
PyArg_ParseTupleAndKeywords(), but it's not clear to me if I can even
pass structs around like this.

I'm just learning how to do extensions, so any help is greatly
appreciated.

Thanks.


Tim Williams

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


{SPAM} start a python application as a win NT service

2005-03-14 Thread Gijs Korremans
Hi,

I'm using windows 2003 small business server and I want to install my python 
programm as a NT (it's just an old name) service. Does anybody know how to do 
this?


Kind regards, 


Gijs Korremans
R&D Department

Global Supply Chain Services (pty) Ltd.
P.O. Box 1263
Rivonia 2128
South Africa
Tel: +27 (0)11 802 1329
Fax: +27 (0)11 802 6528
E-mail: [EMAIL PROTECTED]

--
This message has been scanned for viruses and
dangerous content by Network Sentry, and is
believed to be clean.
http://www.networksentry.co.za

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


Re: How do I pass structures using a C extension?

2005-03-14 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> Hi.
> 
> I trying to write an extension module to call some C libraries so I can
> use them in Python. Several of the library functions pass pointers to
> structures as arguments. I was thinking that I could create a class for
> each structure, but I'm not sure how to get the data back and forth.
> The example the "Extending and Embedding the Python Interpreter" manual
> has examples of passing strings and ints using
> PyArg_ParseTupleAndKeywords(), but it's not clear to me if I can even
> pass structs around like this.
> 
> I'm just learning how to do extensions, so any help is greatly
> appreciated.

There are several ways you can accomplish this. You could use the module
"struct" to create byte-string representations of your structs and pass
these to your extension. In C, you just cast the string-pointer to your
struct and pass it. Disadvantages are: low security, and cumbersome on the
python side. Another way would be to pass the structures as python
structures - tuples and/or lists. Then manually disassemble these is the
extension (PyArg_ParseTupleAndKeywords and co. help you a great deal here)
and create an instance of the desired struct. A third way could be to
create an extension type that resembles your struct and use that to create
the "real" struct by getting the types instance values.

HTH
-- 
Regards,

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


Re: How do I pass structures using a C extension?

2005-03-14 Thread Jaime Wyant
You need to check out swig.  It is the *only* way to setup a `c'
library for use with python.

http://www.swig.org/

jw


On 14 Mar 2005 05:25:03 -0800, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> Hi.
> 
> I trying to write an extension module to call some C libraries so I can
> use them in Python. Several of the library functions pass pointers to
> structures as arguments. I was thinking that I could create a class for
> each structure, but I'm not sure how to get the data back and forth.
> The example the "Extending and Embedding the Python Interpreter" manual
> has examples of passing strings and ints using
> PyArg_ParseTupleAndKeywords(), but it's not clear to me if I can even
> pass structs around like this.
> 
> I'm just learning how to do extensions, so any help is greatly
> appreciated.
> 
> Thanks.
> 
> 
> Tim Williams
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error sending path to Win OS

2005-03-14 Thread Earl Eiland
A couple of you commented that I should be using os.path.join. 
Accordingly, I rewrote my code.  Unfortunately, I still have the same
problem.  the following code snippet

Results.SetOriginal(os.path.getsize(os.path.join(InputDirectory , x)))
y = str(x.split('.')[0]) + '.rk'
print InputDirectory, y
raw_input()
Results.SetArchive(os.path.getsize(os.path.join(InputDirectory, y)))

is executed from the command line with
C:\Documents and Settings\eeiland\Desktop> ..\Thesis\Plan2\Compressor.py
Test_Data\ Test_Output\Results
Test_Data\ Book1.rk, where InputDirectory (in the above snippet) =
'Test_Data\' (I've also tried 'Test_Data', with the same results).

x (in the above snippet) is an element of the list generated by
os.listdir(InputDirectory).

Output upon execution is as follows: 
Test_Data\ Book1.rk

Traceback (most recent call last):
  File "C:\Documents and Settings\eeiland\Thesis\Plan2\Compressor.py",
line 60,
in ?
Results.SetArchive(os.path.getsize(os.path.join(InputDirectory, y)))
  File "C:\Python24\lib\ntpath.py", line 229, in getsize
return os.stat(filename).st_size
OSError: [Errno 2] No such file or directory: 'Test_Data\\Book1.rk'

What am I doing wrong?

Earl


On Sat, 2005-03-12 at 15:16, Michael Hoffman wrote:
> Earl Eiland wrote:
> > os.path.getsize(Inputdirectory + '\\' + Filename) works, but
> > os.path.getsize(Inputdirectory + '\\' + Filename.split('.') + '.ext')
> > Fails reporting "no such file or directory
> > InputDirectory\\Filename.ext".
> 
> No, that should be a TypeError. This will be easier if you copy and
> paste your Python session instead of making stuff up.
> 
> > os.path.getsize(Inputdirectory + r'\' + Filename.split('.') + '.ext')
> > generates a syntax error.
> 
> 'r"\" is not a valid string literal (even a raw string cannot end in an
> odd number of backslashes). Specifically, a raw string cannot end in a
> single backslash (since the backslash would escape the following quote
> character). Note also that a single backslash followed by a newline is
> interpreted as those two characters as part of the string, not as a
> line continuation.'
> 
> http://docs.python.org/ref/strings.html
> -- 
> Michael Hoffman

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


Re: error sending path to Win OS

2005-03-14 Thread Earl Eiland
A couple of you commented that I should be using os.path.join. 
Accordingly, I rewrote my code.  Unfortunately, I still have the same
problem.  the following code snippet

Results.SetOriginal(os.path.getsize(os.path.join(InputDirectory , x)))
y = str(x.split('.')[0]) + '.rk'
print InputDirectory, y
raw_input()
Results.SetArchive(os.path.getsize(os.path.join(InputDirectory, y)))

is executed from the command line with
C:\Documents and Settings\eeiland\Desktop> ..\Thesis\Plan2\Compressor.py
Test_Data\ Test_Output\Results
Test_Data\ Book1.rk, where InputDirectory (in the above snippet) =
'Test_Data\' (I've also tried 'Test_Data', with the same results).

x (in the above snippet) is an element of the list generated by
os.listdir(InputDirectory).

Output upon execution is as follows: 
Test_Data\ Book1.rk

Traceback (most recent call last):
  File "C:\Documents and Settings\eeiland\Thesis\Plan2\Compressor.py",
line 60,
in ?
Results.SetArchive(os.path.getsize(os.path.join(InputDirectory, y)))
  File "C:\Python24\lib\ntpath.py", line 229, in getsize
return os.stat(filename).st_size
OSError: [Errno 2] No such file or directory: 'Test_Data\\Book1.rk'

What am I doing wrong?

Earl


On Sat, 2005-03-12 at 15:16, Michael Hoffman wrote:
> Earl Eiland wrote:
> > os.path.getsize(Inputdirectory + '\\' + Filename) works, but
> > os.path.getsize(Inputdirectory + '\\' + Filename.split('.') + '.ext')
> > Fails reporting "no such file or directory
> > InputDirectory\\Filename.ext".
> 
> No, that should be a TypeError. This will be easier if you copy and
> paste your Python session instead of making stuff up.
> 
> > os.path.getsize(Inputdirectory + r'\' + Filename.split('.') + '.ext')
> > generates a syntax error.
> 
> 'r"\" is not a valid string literal (even a raw string cannot end in an
> odd number of backslashes). Specifically, a raw string cannot end in a
> single backslash (since the backslash would escape the following quote
> character). Note also that a single backslash followed by a newline is
> interpreted as those two characters as part of the string, not as a
> line continuation.'
> 
> http://docs.python.org/ref/strings.html
> -- 
> Michael Hoffman

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


Re: will it cause any problems to open a read-only file & not close it?

2005-03-14 Thread Daniel Dittmar
Fuzzyman wrote:
Sara Khalatbari wrote:
Will it cause any problems if you open a file to read
& never close it?
Under CPython the filehandle will be automatically garbage collected.
Under JPython (Jython) it won't be... 
Isn't it rather that CPython will close the file as soon as the last 
reference is dropped, which is probably right after the read returns?

Whereas Jython/Java will close the file, when the garbage collector 
actually reclaims the object, which will be later. Or much later.

> It's a very useful shortcut
> though *sigh*
It isn't that difficult to write a small function to that effect.
It would perhaps be wise to acknowledge the existence of Jython and 
IronPython by allowing an additional flag for open to the effect "close 
when the end of the file is reached". This would prevent similar 
problems with iter (open (...)), which can't be wrapped quite as easily.

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


Re: urllib (and urllib2) read all data from page on open()?

2005-03-14 Thread Fuzzyman
Certianly under urllib2 - handle.read(100) will read the next 100 bytes
(up to) from the handle. Which is the same beahviour as the read method
for files.

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


Re: {SPAM} start a python application as a win NT service

2005-03-14 Thread lbolognini
Hi there,

these guys did it:
http://www.cherrypy.org/wiki/WindowsService

not sure if it can help.

Lorenzo

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


Re: How do I pass structures using a C extension?

2005-03-14 Thread qui le bile
[EMAIL PROTECTED] a écrit :
Hi.
I trying to write an extension module to call some C libraries so I can
use them in Python. Several of the library functions pass pointers to
structures as arguments. I was thinking that I could create a class for
each structure, but I'm not sure how to get the data back and forth.
The example the "Extending and Embedding the Python Interpreter" manual
has examples of passing strings and ints using
PyArg_ParseTupleAndKeywords(), but it's not clear to me if I can even
pass structs around like this.
I'm just learning how to do extensions, so any help is greatly
appreciated.
Thanks.

Tim Williams
You might be interested in the recently announced ctypes 0.9.5
 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Encodings and printing unicode

2005-03-14 Thread Kent Johnson
Fuzzyman wrote:
How does the print statement decode unicode strings itis passed ? (By
that I mean which encoding does it use).
sys.stdout.encoding
Under windows it doesn't appear to use defaultencoding. On my system
the default encoding is ascii, yet the terminal encoding is latin1 (or
cp1252 or whatever, but not ascii). This means that print '£' works
fine, yet unicode('£') will raise the UnicodeDecodeError.
This uses sys.defaultencoding
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Encodings and printing unicode

2005-03-14 Thread Fuzzyman

Kent Johnson wrote:
> Fuzzyman wrote:
> > How does the print statement decode unicode strings itis passed ?
(By
> > that I mean which encoding does it use).
>
> sys.stdout.encoding
> [snip..]

Aha... that's the missing piece of information. Thank you.

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


RE: urllib (and urllib2) read all data from page on open()?

2005-03-14 Thread Alex Stapleton
Except wouldn't it of already read the entire file when it opened, or does
it occour on the first read()? Also will the data returned from
handle.read(100) be raw HTTP? In which case what if the encoding is chunked
or gzipped?

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Behalf Of
Fuzzyman
Sent: 14 March 2005 14:01
To: python-list@python.org
Subject: Re: urllib (and urllib2) read all data from page on open()?


Certianly under urllib2 - handle.read(100) will read the next 100 bytes
(up to) from the handle. Which is the same beahviour as the read method
for files.

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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

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


Re: urllib (and urllib2) read all data from page on open()?

2005-03-14 Thread Fuzzyman

Alex Stapleton wrote:
> Except wouldn't it of already read the entire file when it opened, or
does
> it occour on the first read()?

Don't know, sorry. Try looking at the source code - it should be
reasonably obvious.

> Also will the data returned from
> handle.read(100) be raw HTTP? In which case what if the encoding is
chunked
> or gzipped?
>

No - you get html - with the http stuff already handled (at least to
the best of my knowledge).

Regards,


Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


RE: urllib (and urllib2) read all data from page on open()?

2005-03-14 Thread Swaroop C H
--- Alex Stapleton <[EMAIL PROTECTED]> wrote:
> Except wouldn't it of already read the entire file when it opened,
> or does it occour on the first read()? Also will the data returned 
> from handle.read(100) be raw HTTP? In which case what if the 
> encoding is chunked or gzipped?

Maybe the httplib module can help you.
>From http://docs.python.org/lib/httplib-examples.html :

>>> import httplib
>>> conn = httplib.HTTPConnection("www.python.org")
>>> conn.request("GET", "/index.html")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK
>>> data1 = r1.read()
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print r2.status, r2.reason
404 Not Found
>>> data2 = r2.read()
>>> conn.close()

As far as I can understand, you can read() data only when you want
to.

Caveat:
There's a warning that says "This module defines classes which
implement the client side of the HTTP and HTTPS protocols. It is
normally not used directly -- the module urllib uses it to handle
URLs that use HTTP and HTTPS."

HTH,

Swaroop C H
Blog: http://www.swaroopch.info
Book: http://www.byteofpython.info
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: urllib (and urllib2) read all data from page on open()?

2005-03-14 Thread Alex Stapleton
Whilst it might be able to do what I want I feel this to be a flaw in urllib
that should be fixed, or at least added to a buglist somewhere so I can at
least pretend someone other than me cares.

-Original Message-
From: Swaroop C H [mailto:[EMAIL PROTECTED]
Sent: 14 March 2005 14:45
To: Alex Stapleton
Subject: RE: urllib (and urllib2) read all data from page on open()?


--- Alex Stapleton <[EMAIL PROTECTED]> wrote:
> Except wouldn't it of already read the entire file when it opened,
> or does it occour on the first read()? Also will the data returned
> from handle.read(100) be raw HTTP? In which case what if the
> encoding is chunked or gzipped?

Maybe the httplib module can help you.
>From http://docs.python.org/lib/httplib-examples.html :

>>> import httplib
>>> conn = httplib.HTTPConnection("www.python.org")
>>> conn.request("GET", "/index.html")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK
>>> data1 = r1.read()
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print r2.status, r2.reason
404 Not Found
>>> data2 = r2.read()
>>> conn.close()

As far as I can understand, you can read() data only when you want
to.

Caveat:
There's a warning that says "This module defines classes which
implement the client side of the HTTP and HTTPS protocols. It is
normally not used directly -- the module urllib uses it to handle
URLs that use HTTP and HTTPS."

HTH,

Swaroop C H
Blog: http://www.swaroopch.info
Book: http://www.byteofpython.info

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


Re: About Databases...

2005-03-14 Thread Ruben Baumann
<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Hello NG,

   I am still quite a newbie with Python (I intensely use wxPython, anyway).
I would like to know what are, in your opinions, the best/faster databases
that I could use in Python (and, of course, I should be able to "link" 
everything
with a wxPython GUI)? Specifically, I work on Reservoir Simulation, and
usually I have to store a discrete/huge amount of data (it depends on the
oil field). As you may have understood, I know almost NOTHING about 
databases
;-)
In general, my data will be numeric (floats, integers). Will a binary 
storage
(if it is possible) reduce the size of the DB? And what about speed in 
storing/retrieving
data?

Thank you a lot for every suggestion.

Andrea.
==
Hello Andrea.

One thing you should consider, maybe the MOST important - What kinds of 
reports are you/your bosses expecting to get out of your application?  Are 
you going to write the reports by hand?  They can be a pretty expensive 
proposition in terms of development time and energy.

Most RDBMS's meet your criteria of speed, numeric data, etc.  I would 
strongly encourage you to look into a database that can be accessed easily 
by some kind of report writer such as Crystal Reports, or MS-Access, or some 
of the other fine report writers out there.  Unless of course you plan to do 
all the heavy work of hand writing all your reports.  Your bosses may ask 
you to graph the data as well.  Oracle(if you can afford it), MS-SQLServer, 
MySQL, PostgreSQL, Even the Free MS-MSDE/SQL Express would work for you. 
Most report writers have hooks to these DBMS's, or can use ODBC to get to 
the data.

Granted, you have said that you know almost NOTHING about databases, but it 
sounds to me like your app is a prime candidate for one, so maybe it's time 
to learn. ;-)   And, in my experience, sometimes the smallest project can 
wind up a major project depending on how important or critical the need for 
the data and it's presentation is. And no matter what reports you produce, 
you'll always be called upon to produce more!

Good Luck!

Ruben 


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


Re: Itertools wishlists

2005-03-14 Thread Steven Bethard
Ville Vainio wrote:
A simpler API:
def flatten(sequence, atomic_test = lambda o: isinstance(o,basestring)):
  """ don't recurse into iterables if atomic_test -> True """
Yes, this is also the API I would have suggested.  Simple, but flexible 
enough to handle the odd cases with the occasional user-defined iterable 
non-containers.

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


Re: PEP 309 (Partial Function Application) Idea

2005-03-14 Thread Chris Perkins
Steven Bethard <[EMAIL PROTECTED]> wrote:
> 
> getting attributes with defaults[1]:
>  objs.sort(key=lambda a: getattr(a, 'lineno', 0))
>  objs.sort(key=getattr(__, 'lineno', 0)
> 

Yes, this exact example is one of the (very) few that I found in the
standard library where the syntax actually helps.

> Places where you might be able to use it (with some changes):
> 
> using bound methods[1][2]:
>  map(lambda x: x.strip(), lst)
>  map(str.strip(), lst) #!! doesn't work for unicode
>  map(methodcaller('strip'), lst) # proposed by Alex Martelli
>  __.strip() # note that calling strip on __ would have to
> # return a curryable looking for one arg...
> 

Yes, the bound method problem is what convinced me to give up on this.
One can hardly write "strip()" (yes, that's four dots).
But note that there is a library out there that does precisely this
(and much more, if I remember) - I believe it's in David Mertz's
Xoltar toolkit. It does allow you to write "_.strip()" and get a
curried callable (He uses "_", a single underscore, as the magic
thingy, which is odd considering its established meaning in
interactive mode).

If we could add an object to the builtins (or elsewhere) called "__"
that works as I proposed for "...", and also behaves like the things
in David Mertz's library (sorry, don't remember exactly where to find
it, or what it's called, and don't have time to look it up right now),
then this might really get interesting. Then we could do any of:
getattr(__, 'lineno', 0)
__.strip()
__.foo().bar(__)

> adding method to an instance[1]:
>  self.plural = lambda n: int(n != 1)

and _maybe_ even:
self.plural = int(__ != 1)


But wait - on second thought, "__" is a legal identifier now, unlike
"...", so we can't have the compiler messing around with expressions
like foo(x, __), can we.  OK, now I really give up on the whole idea!


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


Re: [OT] Who Knows of a Good Computational Physics Textbook?

2005-03-14 Thread Scott David Daniels
Look into Ruth Chabay's physics books for a possibly appropriate
choice and surpisingly on-topic choice.  That is, unless you are
talking computational physics at the level of "ab initio
chemistry" and friends.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: {SPAM} start a python application as a win NT service

2005-03-14 Thread elbertlev
> I'm using windows 2003 small business server and I want to install my
python programm as a NT (it's just an old name) service. Does anybody
know how to do this?

1. you need win32 extensions installed;
2. you need py2exe (optional if you want to install the service on the
machine with no Python)
3. an example can be found in
\Python23\Lib\site-packages\win32\Demos\service

Good luck

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


Re: optparse alternative

2005-03-14 Thread Steven Bethard
Henry Ludemann wrote:
I've been writing an optparse alternative (using getopt) that is at a
stage where I'd be interested in people's opinions.
Looks interesting, but is it really that different from optparse?
I do like the fact that you can specify a type with a conversion 
function.  (In optparse, AFAIK, to add a new type you have to write your 
own subclass of Option that screws with Option.TYPES and 
Option.TYPE_CHECKER, which I've always thought was kinda nasty.)

But I wonder if it wouldn't be better to extend optparse with the 
functionality instead of writing an entirely new module...

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


Re: Building Python 2.4 with icc and processor-specific optimizations

2005-03-14 Thread Michael Hoffman
Michael Hoffman wrote:
Just out of curiosity, I was wondering if anyone has
compiled Python 2.4 with the Intel C Compiler and its
processor specific optimizations. I can build it fine
with OPT="-O3" or OPT="-xN" but when I try to combine
them I get this as soon as ./python is run:
"""
case $MAKEFLAGS in \
*-s*)  CC='icc -pthread' LDSHARED='icc -pthread -shared' OPT='-DNDEBUG 
-O3 -xN' ./python -E ./setup.py -q build;; \
*)  CC='icc -pthread' LDSHARED='icc -pthread -shared' OPT='-DNDEBUG -O3 
-xN' ./python -E ./setup.py build;; \
esac
'import site' failed; use -v for traceback
Traceback (most recent call last):
  File "./setup.py", line 6, in ?
import sys, os, getopt, imp, re
  File "/usr/local/src/Python-2.4/Lib/os.py", line 130, in ?
raise ImportError, 'no os specific module found'
ImportError: no os specific module found
make: *** [sharedmods] Error 1
"""

Also, if I run ./python, I have this interesting result:
"""
$ ./python
'import site' failed; use -v for traceback
Python 2.4 (#34, Mar 12 2005, 18:46:28)
[GCC Intel(R) C++ gcc 3.0 mode] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import sys
 >>> sys.builtin_module_names
('__main__', '__builtin__', '__builtin__', '__builtin__', '__builtin__', 
'__builtin__', '__builtin__', '__builtin__', '__builtin__', 
'__builtin__', '__builtin__', '__builtin__', '__builtin__', 
'exceptions', 'gc', 'gc')
"""

Whoa--what's going on? Any ideas?
Further investigation reveals that the function that sets
sys.builtin_module_names sorts the list before turning it into a
tuple. And binarysort() in Objects/listobject.c doesn't work when
optimized in that fashion. Adding #pragma optimize("", off)
beforehand solves the problem. Why that is, I have no idea. Is
anyone else curious?
Also, if anyone is looking for a way to squeeze a little extra time
out of the startup, perhaps sorting the list at build-time,
rather than when Python starts would be good. Although probably
not worth the trouble. ;-)
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Escaping filename in http response

2005-03-14 Thread Fuzzyman
I know I *could* look this up in the relevant RFC... but I thought
someone might know it off the top of their head.

I'm offering files for download via a CGI. I am inserting the filename
into the relevant http header. Where the filename contains spaces
firefox truncates it - which is probably correct behaviour for firefox
- but annoying :-)

Which is the right function to escape the filename urllib.quote or
urllib.quote_plus ?

It's probably quote_plus... (and I'll probably try both later...
but someone might answer before that)

:-)

Thanks
Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

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


python reading excel thru ADO ?

2005-03-14 Thread Chris Curvey
Windows-specific question for you all...
I've been reading http://www.mayukhbose.com/python/ado/ad-connection.php 
, which seems to infer that I can read an Excel file using the ADO 
interface with Python on Windows.  Unfortunately, the usual problem with 
ADO -- connection strings -- is raising it's ugly head.

Has anyone made this work, and would you share the connection string 
that you used?

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


Re: Web framework

2005-03-14 Thread Joe
On Mon, 14 Mar 2005 11:18:10 +0100, Josef Meile <[EMAIL PROTECTED]>
wrote:
>I guess you are reffering to "Python Scripts" and "ZClasses", which
>indeed are stuck in the ZODB. But in fact you can write external python
>products for zope, which reside on your file system. What is stuck in
>the ZODB would be the instances of those products.

Right, but it's still a pain. Incidently, this is the reason for
Zope-inspired frameworks like CherryPy, ie. Zope with ol' fashioned
dev tools.

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


Re: optparse alternative

2005-03-14 Thread Steven Bethard
Henry Ludemann wrote:
I've been writing an optparse alternative (using getopt) that is at a
stage where I'd be interested in people's opinions.
Some more detailed comments:
* The more I think about it, the more I like that you're basically 
constructing options to match a function signature.  But I can imagine 
that this might be too restrictive for some uses.  It might be worth 
having an alternate interface that provides an options object like 
optparse does.

* Any reason why you aren't using new-style classes?
* I think the code would be easier to navigate in a single module.
* Your code alternates between underscore_names and camelCaseNames. 
Might be better to stick with one or the other.  (PEP 8 suggests the 
former.)

* File specific comments:
Argument.py:
Drop the get_name method; name attribute is already accessible.  (The 
property builtin makes getters and setters generally unnecessary.)

CommandArgument.py:
Drop the get_param_name method; param_name attribute is already accessible
Flag.py:
__init__ should have defaults where applicable (e.g. the comments say 
you can provide None for short_flag, but it doesn't default to this). 
Should also probably produce an error if neither short_flag nor 
long_flag is set.  (Or do this in Command._add_options)

In get_value, use "self.argument is None" not "self.argument == None".
get_flag_name should default to long_flag, not short_flag
Command.py:
add_flag should call _validate_param_name *before* _add_options (in case 
an exception is raised and caught).

In _get_params,
for arg_index in range(len(method_args)):
arg = method_args[arg_index]
could be replaced with
for arg_index, arg in enumerate(method_args):
MulipleLines.py:
Can you use the (standard library) textwrap module instead?  Seems like 
they do about the same thing, but I haven't looked in too much detail.

Hope these comments are at least marginally useful. ;)
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Escaping filename in http response

2005-03-14 Thread Richard Brodie

"Fuzzyman" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

> Which is the right function to escape the filename urllib.quote or
> urllib.quote_plus ?

Neither. Just drop quotes around it, after having sanitized it
(assuming it's plain ASCII). Alternatively you could use the
email package for MIME stuff like this.


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


Re: how to delete the close button (the X on the right most corner of the window) on a window

2005-03-14 Thread jrlen balane
I am using BOA Constructor in building a GUI


On 13 Mar 2005 21:19:07 -0800, Harlin Seritt <[EMAIL PROTECTED]> wrote:
> What GUI toolkit are you using? I think this is the point Jeremy is
> making.
> 
> Harlin Seritt
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Escaping filename in http response

2005-03-14 Thread Fuzzyman
Nice one - thanks.

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


[Fwd: RE: [PyCON-Organizers] volunteers]

2005-03-14 Thread Steve Holden
PyCon delegates:
Here's your chance to achieve fame and fortune (or at least a certain 
degree of notoriety).

If you'd like to help out by chairing one or more sessions please update 
the Wiki page referenced in Michael Chermside's attached email.

regards
 Steve
 Original Message 
Subject: RE: [PyCON-Organizers] volunteers
Date: Mon, 14 Mar 2005 10:45:26 -0500
From: Chermside, Michael <[EMAIL PROTECTED]>
To: David Goodger <[EMAIL PROTECTED]>, <[EMAIL PROTECTED]>
CC: [EMAIL PROTECTED]
AMK writes:
BTW, should we be asking for volunteers to chair sessions?
David Goodger replies:
If this is still needed, I volunteer to coordinate the volunteers.
Sounds like David just drafted himself...
I located the 2004 signup sheet and created a similar signup wiki page
at http://www.python.org/moin/PyConDC2005/SessionChairs
David, you should probably replace your name with an email link. Or
if you don't ACTUALLY feel like volunteering, then let me know and
I'll do it.
And people who are interested in chairing sessions (mostly timekeeping
and helping make things run smoothly) should go to the above wiki
page and sign up, then let the volunteer coordinator know.
-- Michael Chermside

This email may contain confidential or privileged information. If you 
believe you have received the message in error, please notify the sender 
and delete the message without copying or disclosing it.

___
Pycon-organizers mailing list
[EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/pycon-organizers
--
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


super with only one argument

2005-03-14 Thread Steven Bethard
When would you call super with only one argument?  The only examples I 
can find of doing this are in the test suite for super.  Playing around 
with it:

py> class A(object):
... x = 'a'
...
py> class B(A):
... x = 'b'
...
py> s = super(B)
py> s.x
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'super' object has no attribute 'x'
So I can't access class attributes with a single-argument super.
You can see that there are some interesting attributes on a super object:
py> for name in dir(s):
...if not hasattr(object, name):
...print name, getattr(s, name)
...
__get__ 
__self__ None
__self_class__ None
__thisclass__ 
Looks like I can call the descriptor machinery directly to get an attribute:
py> s.__get__(B).x
'a'
py> s.__get__(B, B()).x
'a'
But this doesn't seem horribly useful.  And __self__, __self_class__ and 
__thisclass__ are readonly, so I can't bind a super object to an 
instance once it's been created.

So what's the use case?
Thanks in advance,
STeVe
P.S. The context here is that I'm trying to submit a patch to clarify 
the docs on super a bit.  But I realized that I don't actually 
understand its behavior with only a single argument...
--
http://mail.python.org/mailman/listinfo/python-list


getting data with proper encoding to the finish

2005-03-14 Thread Ksenia Marasanova
Hi,

I have a little problem with encoding. Was hoping maybe anyone can
help me to solve it.

There is some amount of data in a database (PG) that must be inserted
into Excel sheet and emailed. Nothing special, everything works.
Except that non-ascii characters are not displayed properly.
The data is stored as XML into a text field. When I use pgsql it's
displayed good in the terminal. Now I run my script and print data
with "print" statement, still goed. Then I use pyXLWriter to write the
sheet, and Python email package to email it... and the resulting sheet
is not good:

Рis displayed instead of à (for example)

The most important question that I'd like to ask, is what is the
proper way to debug it?! How can I determine where it goes wrong
(maybe by calculating character code or something?) I know very little
about how encoding works, I use it, but I don't really understand
it... any dummy-proof pointers are also appreciated :)

Thanks...

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


RE: Itertools wishlists

2005-03-14 Thread Robert Brewer
Steven Bethard wrote:
> Ville Vainio wrote:
> > A simpler API:
> > 
> > def flatten(sequence, atomic_test = lambda o: 
> isinstance(o,basestring)):
> >   """ don't recurse into iterables if atomic_test -> True """
> 
> Yes, this is also the API I would have suggested.  Simple, 
> but flexible enough to handle the odd cases with the occasional 
> user-defined iterable non-containers.

If there are two or three common atomic_test's they could also be placed
into itertools globals (with better names, of course ;):

def is_string(item):
return isinstance(item, basestring)

def flatten(seq, atomic_test = is_string):
...


Perhaps atomic_test could allow a tuple or list of tests and combine
them...?


Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Getting the process list on win98

2005-03-14 Thread Ron
I've written a screen saver which opens multiple copies on windows 98. 
I'm trying to check the process list to determine if it is already running.

So far all the example win32 routines I've found, through google, only 
work on newer xp and nt versions of windows. This is the current attempt 
to get the process list on windows 98:

def GetProcessNameList():
from win32com.client import GetObject
WMI = GetObject('winmgmts:')
processes = WMI.InstancesOf('Win32_Process')
names = []
for process in processes:
names += [process.Properties_('Name').Value]
return names
def IsRunning( filename ):
n = 0
for process in GetProcessNameList():
if process.lower() == filename.lower():
n += 1
return n
Then in the startup section:
filename = os.path.basename(sys.argv[0])
# Wait for preview window to exit.
t = clock()
while IsRunning( filename) > 1 and clock() < t + 3:
sleep(.01)
# Start screen saver if only self is running.
if IsRunning( filename)==1:
saver = Screensaver()
saver.launchScreenSaver()
Results in this error on windows 98, works fine on windows xp:
Traceback (most recent call last):
  File "Aztec.pyw", line 255, in ?
  File "Aztec.pyw", line 38, in IsRunning
  File "Aztec.pyw", line 29, in GetProcessNameList
  File "win32com\client\__init__.pyc", line 73, in GetObject
  File "win32com\client\__init__.pyc", line 88, in Moniker
pywintypes.com_error: (-2147221014, 'Moniker cannot open file', None, None)
The program is in python v2.3 and packaged using pyexe, and inno setup.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python reading excel thru ADO ?

2005-03-14 Thread Chris Curvey
Chris Curvey wrote:
Windows-specific question for you all...
I've been reading http://www.mayukhbose.com/python/ado/ad-connection.php 
, which seems to infer that I can read an Excel file using the ADO 
interface with Python on Windows.  Unfortunately, the usual problem with 
ADO -- connection strings -- is raising it's ugly head.

Has anyone made this work, and would you share the connection string 
that you used?

Thanks!
-Chris
Chalk up a brain fart for me!  I was doing "connection.open()", not 
"connection.Open()", and the error message made me think that there was 
a problem with the connection string.

Thanks all!
-Chris
P.S.  The proper URL above ends with "ado-connection.php"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Itertools wishlists

2005-03-14 Thread Steven Bethard
Robert Brewer wrote:
Steven Bethard wrote:
Ville Vainio wrote:
A simpler API:
def flatten(sequence, atomic_test = lambda o: 
isinstance(o,basestring)):
 """ don't recurse into iterables if atomic_test -> True """
Yes, this is also the API I would have suggested.  Simple, 
but flexible enough to handle the odd cases with the occasional 
user-defined iterable non-containers.
If there are two or three common atomic_test's they could also be placed
into itertools globals (with better names, of course ;):
def is_string(item):
return isinstance(item, basestring)
def flatten(seq, atomic_test = is_string):
...
Perhaps atomic_test could allow a tuple or list of tests and combine
them...?
Did you have other atomic tests in mind?  All the use cases I've ever 
seen have always been with strings.  (And I've never created any class 
whose items are instances of the class.)

I don't see much benefit in complicating the API of flatten unless 
there's a really good use case for multiple atomic tests (that can't 
just as easily be solved by writing your own function that does the 
appropriate complex atomicity test).  I also have the feeling that any 
complicated atomictiy test is more than a simple and-ing of several tests...

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


Re: Itertools wishlists

2005-03-14 Thread Ville Vainio
> "Steven" == Steven Bethard <[EMAIL PROTECTED]> writes:

Steven> complex atomicity test).  I also have the feeling that any
Steven> complicated atomictiy test is more than a simple and-ing
Steven> of several tests...

I also have the feeling that if the atomicity criterion was any more
complex in the API, the proposal would be shot down immediately on the
grounds of not being fundamental enough as concept.

-- 
Ville Vainio   http://tinyurl.com/2prnbOB
-- 
http://mail.python.org/mailman/listinfo/python-list


GET MORE FOR YOUR BUCK

2005-03-14 Thread ml
The biggest store online

www.thebuckstore.com
http://www.thebuckstore.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: super with only one argument

2005-03-14 Thread Michele Simionato
I asked myself the same question and I am not convinced
that using 'super' with one argument really makes sense
(i.e. IMO it is more a liability than an asset). BTW, I have a set
of notes on the tricky aspects of 'super' you may be interested in.

Michele Simionato

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


win32 shell extension (virtual drive)

2005-03-14 Thread Tiziano Bettio
Hi there
I'm looking for a simple solution of a win32 shell extension (virtual
drive).
It should make available a new drive with letter, which will be
read-only. Instead of a network drive or similar it then should query a
server application for directory/file listing.
Would be nice to have a lib or similar for that.
Any hints??
tizi
--
http://mail.python.org/mailman/listinfo/python-list


Re: Wishlist item: itertools.flatten

2005-03-14 Thread Michael Spencer
Leif K-Brooks wrote:
Michael Spencer wrote:
if hasattr(item,"__iter__"): # Avoids iterating over strings

That's probably the cleanest way to avoid strings, but it's 
unfortunately not a good idea IMHO. Many objects (IndexedCatalog's 
Result objects are what I'm concerned about, but there are undoubtedly 
others) still rely entirely on the old-style sequence iteration protocol 
even though they're proper containers, so checking for __iter__ wouldn't 
work on them.  Explicitly doing isinstance(item, basestring) is probably 
the best option until older objects move to the new iteration protocol.
Sure, the preceding part of my post:
One issue is specifying iterable types which should be atomic (notably strings).  This uses a simple hardwired test for that.
...makes it clear that 'hasattr(item,"__iter__")' is not claiming to be a 
general atomicity test.

Using something like:
if not isinstance(item, basestring):
try:
iterator = iter(item)
etc...
...defines a rule that works for your case, but it also means that any 
non-basestring class that implements __getitem__ gets flattened.  That may be 
what you want...or not.

I think flatten is a special-case function, and it is therefore most practical 
to define its atomicity rules on a case-by-case basis.

Michael


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


Re: How do I pass structures using a C extension?

2005-03-14 Thread [EMAIL PROTECTED]
Thanks for all the replies so far.  I'm starting to look at SWIG, but
the libraries I want access to are all static. I created a small
interface file and a setup.py file, but when I build it, I get
undefined symbols.  It sounds like the pack/unpack struct method is a
little to messy for my tastes. I was looking at the example for
defining a new type, but I wasn't sure how to pass the structure. I
need to look more into the PyArg_ParseTupleAndKeywords and creating a
list to pass into that.

I haven't looked at the ctypes module yet, but it looks like it not one
of the modules Python comes with, so I'm a little reluctant to use it.

Here's my set.py and interface file for my module:

# setup.py 
#!/bin/env python
import sys, os
from distutils.core import setup, Extension

OTB_HOME='/vps/otbknox/williams/OTB_2.0'
OTB_INCLDIR=[
os.path.join(OTB_HOME, 'include', 'global'),
os.path.join(OTB_HOME, 'include', 'libinc'),
os.path.join(sys.prefix,'include','python2.3'),
OTB_HOME
]
OTB_LIBDIR=[os.path.join(OTB_HOME, 'lib'),
os.path.join(sys.prefix, 'lib', 'python2.3')]
OTB_LIBS=['cmdline']

setup (name = "OTB_cmdline",
   version="1.0",
   author="Tim Williams",
   ext_modules=[Extension('_OTB_cmdline',
  sources=['OTB_cmdline.i'],
  include_dirs=OTB_INCLDIR,
  library_dirs=OTB_LIBDIR,
  libraries=OTB_LIBS,

runtime_library_dirs=[os.path.join(OTB_HOME,'lib')]
  )]
   )
#

# module.i ##
%module OTB_cmdline
%{
#include 
#include 
#include 
%}

extern void cmd_process_options (
int argc,
argv_t argv,
int *leftover_argc,
argv_t * leftover_argv,
CMD_OPTION * options,
uint32 sizeof_options,
int32 verbose);

###

Here's the output of the build:

python setup.py build --force
running build
running build_ext
building '_OTB_cmdline' extension
swigging OTB_cmdline.i to OTB_cmdline_wrap.c
swig -python -o OTB_cmdline_wrap.c OTB_cmdline.i
/usr/bin/gcc33 -fno-strict-aliasing -DNDEBUG -g -O3 -Wall
-Wstrict-prototypes -fPIC
-I/vps/otbknox/williams/OTB_2.0/include/global
-I/vps/otbknox/williams/OTB_2.0/include/libinc
-I/project/c4i/Users_Share/williams/Linux/include/python2.3
-I/vps/otbknox/williams/OTB_2.0
-I/project/c4i/Users_Share/williams/Linux/include/python2.3 -c
OTB_cmdline_wrap.c -o build/temp.linux-i686-2.3/OTB_cmdline_wrap.o
OTB_cmdline_wrap.c:187: warning: `SWIG_Python_TypeDynamicCast' defined
but notused
OTB_cmdline_wrap.c:199: warning: `SWIG_Python_TypeName' defined but not
used
OTB_cmdline_wrap.c:205: warning: `SWIG_Python_TypeQuery' defined but
not used
OTB_cmdline_wrap.c:444: warning: `SWIG_Python_addvarlink' defined but
not used
OTB_cmdline_wrap.c:551: warning: `SWIG_Python_MustGetPtr' defined but
not used
OTB_cmdline_wrap.c:559: warning: `SWIG_Python_ConvertPacked' defined
but not used
gcc -pthread -shared build/temp.linux-i686-2.3/OTB_cmdline_wrap.o
-L/vps/otbknox/williams/OTB_2.0/lib
-L/project/c4i/Users_Share/williams/Linux/lib/python2.3-Wl,-R/vps/otbknox/williams/OTB_2.0/lib
-lcmdline -o build/lib.linux-i686-2.3/_OTB_cmdline.so


After copying the _OTB_cmdline.so file to the directory where
OTB_cmdline.py  is,  here's what happens when I try to import it:

#
Python 2.3.2 (#10, Feb 24 2005, 10:59:54)
[GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import  OTB_cmdline
Traceback (most recent call last):
  File "", line 1, in ?
  File "OTB_cmdline.py", line 5, in ?
import _OTB_cmdline
ImportError: ./_OTB_cmdline.so: undefined symbol: cmd_process_options


Can I only make extensions with shared libraries?

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


Re: optparse alternative

2005-03-14 Thread Michael Hoffman
Henry Ludemann wrote:
I've been writing an optparse alternative (using getopt) that is at a
stage where I'd be interested in people's opinions.
Thanks for the work and letting us see it!
As far as I can tell, your module has one functional advantage over
optparse--it validates arguments as well as options. The rest seems to
be cosmetics, and personally I prefer the cosmetics of optparse. For
one thing, it uses the variable/function naming style found throughout
most of the stdlib. optparse has also been widely used and tested for
the last four years.
I think you would be better off trying to extend optparse to deal with
non-option arguments, and you can tap into the installed base of
existing optparse users and even get your code included in the stdlib
if Greg Ward agrees. Whereas that's really unlikely for an entirely
new module--there just isn't the need for a THIRD way to do the same
thing.
Just a suggestion.
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: optparse alternative

2005-03-14 Thread Henry Ludemann
Thanks for the comments...
Steven Bethard wrote:
Looks interesting, but is it really that different from optparse?
In the sense that they both do the same thing, no, not really. But the
way they do it is quite different; optparse bases itself on setting
variables, while this module is for invoking functions. I like this way
a better, as it acts as a more 'usual' client of the code, in the sense
that it uses publically exposed interfaces rather then internal
variables for passing the information. That said, the reason I started
this was that at the time I wasn't aware of optparse; my search through
the help needed to be a bit more thorough. When I found optparse, I
decided to continue on with this approach (mostly because I was having
fun with it).
I do like the fact that you can specify a type with a conversion 
function.  (In optparse, AFAIK, to add a new type you have to write 
your own subclass of Option that screws with Option.TYPES and 
Option.TYPE_CHECKER, which I've always thought was kinda nasty.)
Yeah, it works quite nicely; as it is a general function, you can use
your own methods for creating arbitrary objects (so long as they take
one parameter (a string)).
But I wonder if it wouldn't be better to extend optparse with the 
functionality instead of writing an entirely new module...
The way of getting the data through to the program is quite different
(method vs data), so that would be a fairly radical change / addition
for optparse.
--
http://mail.python.org/mailman/listinfo/python-list


Re: a program to delete duplicate files

2005-03-14 Thread David Eppstein
In article <[EMAIL PROTECTED]>,
 "John Machin" <[EMAIL PROTECTED]> wrote:

> Just look at the efficiency of processing N files of the same size S,
> where they differ after d bytes: [If they don't differ, d = S]

I think this misses the point.  It's easy to find the files that are 
different.  Just a file size comparison will get most of them, and most 
of the rest can be detected in the first few kbytes.  So I think it's 
safe to assume both of these filtering mechanisms would be incorporated 
into a good duplicate detection code, and that any remaining tests that 
would be performed are between files that are very likely to be the same 
as each other.

The hard part is verifying that the files that look like duplicates 
really are duplicates.  To do so, for a group of m files that appear to 
be the same, requires 2(m-1) reads through the whole files if you use a 
comparison based method, or m reads if you use a strong hashing method.  
You can't hope to cut the reads off early when using comparisons, 
because the files won't be different.

The question to me is: when you have a group of m>2 likely-to-be-equal 
files, is 2(m-1) reads and very little computation better than m reads 
and a strong hash computation?  I haven't yet seen an answer to this, 
but it's a question for experimentation rather than theory.

-- 
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a program to delete duplicate files

2005-03-14 Thread David Eppstein
In article <[EMAIL PROTECTED]>,
 Patrick Useldinger <[EMAIL PROTECTED]> wrote:

> Shouldn't you add the additional comparison time that has to be done 
> after hash calculation? Hashes do not give 100% guarantee.

When I've been talking about hashes, I've been assuming very strong 
cryptographic hashes, good enough that you can trust equal results to 
really be equal without having to verify by a comparison.

-- 
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Itertools wishlists

2005-03-14 Thread Raymond Hettinger
> Steven> complex atomicity test).  I also have the feeling that any
> Steven> complicated atomictiy test is more than a simple and-ing
> Steven> of several tests...

"Ville Vainio"
> I also have the feeling that if the atomicity criterion was any more
> complex in the API, the proposal would be shot down immediately on the
> grounds of not being fundamental enough as concept.

Would this meet your needs?

def flatten(iterable, atomic_iterable_types=(basestring,)):
iterstack = [iter(iterable)]
while iterstack:
for elem in iterstack[-1]:
if not isinstance(elem, atomic_iterable_types):
try:
it = iter(elem)
except TypeError:
pass
else:
iterstack.append(it)
break
yield elem
else:
iterstack.pop() # only remove iterator when it is exhausted


Raymond Hettinger


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


Re: optparse alternative

2005-03-14 Thread Henry Ludemann

* The more I think about it, the more I like that you're basically 
constructing options to match a function signature.  But I can imagine 
that this might be too restrictive for some uses.  It might be worth 
having an alternate interface that provides an options object like 
optparse does.

It is matching options to a function signiture, and for complex methods, 
this might be too restrictive (for example, you'd get methods with 10 - 
20 params). That said, many cases don't have this many things that can 
be set.

Although your point about providing an alternate interface is a good one...
* Any reason why you aren't using new-style classes?

Ignorance. I'll look into it...
* I think the code would be easier to navigate in a single module.

It might be easier to navigate (eg: when you want to go to a method 
implmentation), but from a maintenance point of view I feel modular code 
is easier... Mostly this is instint from other languages (mostly c++).

* Your code alternates between underscore_names and camelCaseNames. 
Might be better to stick with one or the other.  (PEP 8 suggests the 
former.)

Yeah, I coded it before I looked at PEP8. Initially it was all camel 
case, and I attempted to retrofit it. It seems like classes should still 
be CamelCase, yes?

* File specific comments:
Argument.py:
Drop the get_name method; name attribute is already accessible.  (The 
property builtin makes getters and setters generally unnecessary.)

CommandArgument.py:
Drop the get_param_name method; param_name attribute is already 
accessible

Flag.py:
__init__ should have defaults where applicable (e.g. the comments say 
you can provide None for short_flag, but it doesn't default to this). 
Should also probably produce an error if neither short_flag nor 
long_flag is set.  (Or do this in Command._add_options)

In get_value, use "self.argument is None" not "self.argument == None".
get_flag_name should default to long_flag, not short_flag
Command.py:
add_flag should call _validate_param_name *before* _add_options (in 
case an exception is raised and caught).

In _get_params,
for arg_index in range(len(method_args)):
arg = method_args[arg_index]
could be replaced with
for arg_index, arg in enumerate(method_args):

Will do...
MulipleLines.py:
Can you use the (standard library) textwrap module instead?  Seems 
like they do about the same thing, but I haven't looked in too much 
detail.

Doh! Yep, they do the same thing. This is another case of my not 
checking the standard library well enough.

Hope these comments are at least marginally useful. ;)

Yes, very useful. Thanks very much for spending the time to go over it...
--
http://mail.python.org/mailman/listinfo/python-list


py2app can't find boot_app.py

2005-03-14 Thread Bob Swerdlow
I'm trying to move my application from bundlebuilder to py2app.  I upgraded 
to PyObjC 1.2, which include py2app 1.7, but I got the following error.  I 
saw a note on the py2app site that earlier versions need to be removed 
before the upgrade, so I deleted the py2app directory and downloaded and 
installed it separately, but got the same result.  How do I get it to find 
this boot_app.py file?

Thanks,
Bob

Excerpts from the py2app run:

% python setup.py py2app
running py2app
...

Traceback (most recent call last):
   File "/tmp/tmptCCn9S.py", line 218, in ?
 direct=1)
   File
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
python2.3/site-packages/py2app/py2app/util.py", line 208, in
byte_compile
 if force or newer(mod.filename, cfile):
   File
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
python2.3/distutils/dep_util.py", line 22, in newer
 raise DistutilsFileError, "file '%s' does not exist" % source
distutils.errors.DistutilsFileError: file 'boot_app.py' does not exist
error: command '/usr/bin/python' failed with exit status 1



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


Re: a program to delete duplicate files

2005-03-14 Thread Patrick Useldinger
David Eppstein wrote:
When I've been talking about hashes, I've been assuming very strong 
cryptographic hashes, good enough that you can trust equal results to 
really be equal without having to verify by a comparison.
I am not an expert in this field. All I know is that MD5 and SHA1 can 
create collisions. Are there stronger algorithms that do not? And, more 
importantly, has it been *proved* that they do not?

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


Re: urllib (and urllib2) read all data from page on open()?

2005-03-14 Thread Bengt Richter
On Mon, 14 Mar 2005 14:48:25 -, "Alex Stapleton" <[EMAIL PROTECTED]> wrote:

>Whilst it might be able to do what I want I feel this to be a flaw in urllib
>that should be fixed, or at least added to a buglist somewhere so I can at
>least pretend someone other than me cares.
>
Someone cares about top-posting. Please don't ;-)

>-Original Message-
>From: Swaroop C H [mailto:[EMAIL PROTECTED]
>Sent: 14 March 2005 14:45
>To: Alex Stapleton
>Subject: RE: urllib (and urllib2) read all data from page on open()?
>
>
>--- Alex Stapleton <[EMAIL PROTECTED]> wrote:
>> Except wouldn't it of already read the entire file when it opened,
>> or does it occour on the first read()? Also will the data returned
>> from handle.read(100) be raw HTTP? In which case what if the
>> encoding is chunked or gzipped?
>
>Maybe the httplib module can help you.
>>From http://docs.python.org/lib/httplib-examples.html :
>
>>>> import httplib
>>>> conn = httplib.HTTPConnection("www.python.org")
>>>> conn.request("GET", "/index.html")
>>>> r1 = conn.getresponse()
>>>> print r1.status, r1.reason
>200 OK
>>>> data1 = r1.read()
>>>> conn.request("GET", "/parrot.spam")
>>>> r2 = conn.getresponse()
>>>> print r2.status, r2.reason
>404 Not Found
>>>> data2 = r2.read()
>>>> conn.close()
>
>As far as I can understand, you can read() data only when you want
>to.
>
>Caveat:
>There's a warning that says "This module defines classes which
>implement the client side of the HTTP and HTTPS protocols. It is
>normally not used directly -- the module urllib uses it to handle
>URLs that use HTTP and HTTPS."
>
>HTH,
>
>Swaroop C H
>Blog: http://www.swaroopch.info
>Book: http://www.byteofpython.info
>

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a program to delete duplicate files

2005-03-14 Thread Patrick Useldinger
David Eppstein wrote:
The hard part is verifying that the files that look like duplicates 
really are duplicates.  To do so, for a group of m files that appear to 
be the same, requires 2(m-1) reads through the whole files if you use a 
comparison based method, or m reads if you use a strong hashing method.  
You can't hope to cut the reads off early when using comparisons, 
because the files won't be different.
If you read them in parallel, it's _at most_ m (m is the worst case 
here), not 2(m-1). In my tests, it has always significantly less than m.

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


Re: optparse alternative

2005-03-14 Thread Henry Ludemann

As far as I can tell, your module has one functional advantage over
optparse--it validates arguments as well as options.
Functionality wise, that is probably about it. It is more from a 
seperation of command line / functionality code that I wrote this; that 
the command line code should be seperate from the actual functional code.

The rest seems to be cosmetics, and personally I prefer the cosmetics 
of optparse.
All to their own... I actually wrote this before I was aware of 
optparse, and so didn't consider the benefits / disadvantages of that 
way of doing it. It's simply a different approach. That said, what I 
like about this approach is that it is non-obtrusive on the functional code.

For one thing, it uses the variable/function naming style found 
throughout
most of the stdlib. 
True... I originally wrote the code in camel case, and have attempted to 
change it to the standard from PEP 8. I guess I missed a few things :-)

optparse has also been widely used and tested for
the last four years.
Again, true, but then again, this module (unlike optparse) uses the 
standard getopt module for all command line parsing, which has been 
around for even longer. So the bugs are all in the method invoking (my 
code), and not in the parsing. 

I think you would be better off trying to extend optparse to deal with
non-option arguments, and you can tap into the installed base of
existing optparse users and even get your code included in the stdlib
if Greg Ward agrees. Whereas that's really unlikely for an entirely
new module--there just isn't the need for a THIRD way to do the same
thing.
Yeah, a third module would be a bit redundent. I had actually written 
most of this module before I became aware of optparse (it was one of 
those bash the head against the wall moments when I found it), but 
decided to continue with this version because I liked the cosmetics of 
it (it seemed less intrusive on the functional code). Once it was more 
or less finished, I decided to clean it up and post it in the hope it 
might be useful to someone else, and perhaps more, to get any comments 
that could improve it. And besides, variety is the spice of life :-)

Just a suggestion.
Thanks for your comments...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Itertools wishlists

2005-03-14 Thread Ville Vainio
> "Raymond" == Raymond Hettinger <[EMAIL PROTECTED]> writes:

Steven> complex atomicity test).  I also have the feeling that any
Steven> complicated atomictiy test is more than a simple and-ing
Steven> of several tests...

Raymond> "Ville Vainio"

>> I also have the feeling that if the atomicity criterion was any
>> more complex in the API, the proposal would be shot down
>> immediately on the grounds of not being fundamental enough as
>> concept.

Raymond> Would this meet your needs?

Raymond> def flatten(iterable, atomic_iterable_types=(basestring,)):

Yes, completely.

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optparse alternative

2005-03-14 Thread Michael Hoffman
Henry Ludemann wrote:
I had actually written most of this module before I became aware
> of optparse (it was one of those bash the head against the wall
> moments when I found it),
I've been there :)
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: Itertools wishlists

2005-03-14 Thread bearophileHUGS
Thank you for your answers, Raymond Hettinger.

>The options also suggest that the abstraction is not as basic or
universal as we would hope.<

I don't understand, but this is normal.


> ll = open("namefile").read().split()
> r = partition(map(float, ll), 4)

>If you need that to be flattened one level, it would have been better
to do all the splits at once:<

Uhm, my purpose was the opposite, as you can see from the alternative
version. It was an example of using partition(), that is kind of
opposite of flatten().


>Generalizing the two results, it may be fair to say that the desire to
flatten is a code smell indicating that structure is being
unnecessarily destroyed or that earlier processing introduced unwanted
structure.<

Probably for my programming style flatten() is useful, but this is a
very subjective thing (and I've already coded my flatten that I use not
much frequently, without the level parameter inspired by a similar
Matemathica one), I've also implemented little other things from the
Delphi and Logo language, for my own use in Python.
For me it's not easy to improve/extend Python, maybe I have to stop
trying it, and I have just to use this language as you people are
giving us...

Than you, a bearish hug,
Bearophile

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


Re: A Font Dialog (Tkinter)

2005-03-14 Thread Raseliarison nirinA
"Harlin Seritt" wrote:

> Is there a way to call up the Font dialog box (at least in the
> Windows API) from Tkinter or another module?
>

i'll use the tkFont module and the same way as IDLE calls it.
looking at the source code may help you:

>>> import tkFont, idlelib.configDialog, inspect
>>> print inspect.getsource(tkFont)
>>> print
inspect.getsource(idlelib.configDialog.ConfigDialog.CreatePageFontTab)

> thanks,
>
> Harlin Seritt
>

hope this helps

--
nirinA
--



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


Re: Listbox fill=BOTH expand=YES (Tkinter)

2005-03-14 Thread Raseliarison nirinA
"Martin Franklin" wrote:

> Harlin Seritt wrote:
> > I am trying the following:
> >
> > Listbox(parent).pack(fill=BOTH, expand=YES)
> >
> > I notice that the listbox will fill on the X axis but will not on
> > the Y axis unlike other widgets. 
> > Is there any way to force this?
> >
> > thanks,
> >
> > Harlin
> >
>
> Harlin,
>
> It should expand (and fill ) in both directions have you checked
> it's parents packing options?
>
> Martin
>

is YES a valid flag for expand?
maybe expand=1

--
nirinA


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


Re: Listbox fill=BOTH expand=YES (Tkinter)

2005-03-14 Thread Harlin Seritt
That was it Martin. I forgot to expand the parent.

Thanks!

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


Re: (Newbie) Restricting inherited methods to operate on element from same subclass

2005-03-14 Thread andy2O
Bruno Desthuilliers wrote:
> You've already got the technical answer. About a possible design
flaw,
> it would seem to me that restricting the join() operation on specific

> subclasses breaks the LSP. OTOH, Python being dynamically typed,
> inheritence is merely an implementation detail, so that may not be
such
> a big deal after all... Anyway, you may want to document this point
to
> make it clear for the next person that'll have to work this code.
>
> My 2 cents

OK, thanks - I see your point.

I was in effect implementing mutable objects, similar in some sense to
lists, by extending an immutable class similar to Python's tuples. I
think instead I should copy the Python type hierarchy, with the
list-like and tuple-like classes each defined as sub-classes of a
'sequence' class. In this case the type checking could go away.

I'm learning object-orientated programming and dynamic typed languages
the hard way at the moment, by trial and error. Can you, or anyone
suggest a good book which will guide me? Is there a classic text on
this? The coverage of OOP in 'Learning Python' is useful, but I could
do with something more in-depth.

Thanks again,
Andy.

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


Conversion to string: how do `s work?

2005-03-14 Thread Chris Lasher
I'm working my way through _Learning_Python_ 2nd ed., and I saw
something peculiar which is not explained anywhere in the text.

print " " + file + " size=" + `size`

The `s appear to somehow automagically convert the integer to a string
for concatenation. How does this work? Is this just a shortcut for
str(size)? Is it considered bad practice to use `s?

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


yum repository

2005-03-14 Thread Donald L. Dietmeyer
What yum repository do you use to pick up
python rpms?
   Don
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beware complexity

2005-03-14 Thread Ron
Philip Smith wrote:
I wonder if anyone has any thoughts not on where Python should go but where 
it should stop?
My feelings on this is, it's a problem of organization and 
documentation.  Do both of these well, and things will be manageable.

I would like to see a bit cleaner file organization framework. I think 
keeping the different parts/modules/utilities/etc.  Seperate and in 
their own place would solve a lot of distribution/installation problems.

Having a central distribution place for people to download third party 
modules in a standard install/uninstall package format would also help.

# Example directory structure.
python24
main
core# interpreter, dll's, and min.
tools   # test scripts
examples
docs
standard_modules# modules included in distribution
module name
core# standard module dlls
tools
examples
docs
next module name
core
tools
examples
docs

extend_modules  # 3rd party extension modules
"module name"
core# dlls
tools   # helpfull scripts
examples
docs

tools
idle
core
tools
examples
docs
py2exe
core
tools
examples
docs
document_reader 
# script to read and search all doc files
# and run related examples scripts.
core
tools
examples
docs
Ron
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there a problem on this simple code

2005-03-14 Thread jrlen balane
why is it that here:

1)rx_data = ser.read(10)
(rx_command, rx_msg_no, rx_no_databyte, temp1, temp2, pyra1,
pyra2, voltage, current, rx_checksum) = unpack('10B', rx_data)
print rx_command, rx_msg_no, rx_no_databyte, temp1, temp2, pyra1,
pyra2, voltage, current, rx_checksum
 
>>> type (rx_command)


but here:

2)rx_data_command = ser.read()
(rx_command) = unpack('1B', rx_data_command)

>>> type (rx_command)


how can i make rx_command of type 'int' if i am to use 2)?

@sir John
the reason why my first post all starts with '70' , which is what i
really wanted to happen, is that it is buffered. the microcontroller
sends data at a very fast rate, that the program just retrieve data
from the buffer. so basically, they are not "real time". but there are
also cases where the command is in other position. the good thing is,
it remains in that position throughout...

i want to make the program show data in "real time" so everytime i am
able to read data, i immediately use flushInput(), to erase data from
the buffer.

so i what i want to do now is to search for the rx_command first
('70') just so i know where my data should start.

the checksum will be validated, but first, i must know where my checksum is!
if (rx_checksum != -(temp1 + temp2 + pyra1 + pyra2 + voltage + current
+  rx_command +   rx_message_no + rx_no_databyte) & 0xff):
#then discard message, loop again to search for rx_command

plase help...

On 13 Mar 2005 13:06:16 -0800, John Machin <[EMAIL PROTECTED]> wrote:
> 
> Jan Rienyer Gadil wrote:
> > @ sir Peter
> > so you mean that it is correct (at least on the unpack() part)
> 
> No he doesn't mean that at all. All it means is that minor scuffles
> have broken out among the spectators. Don't worry about them, batons &
> water cannon will fix them; you concentrate on the football match :-)
> 
> >
> > when i run this program on IDLE , Python 2.3 (enthought edition),
> > nothing is outputted on the shell, until i decide to close the shell,
> > wherein it tells me if i would like to kill a process...
> 
> So you did some elementary debugging, like putting in some print
> statements at various places, as shown below, and what happened?
> 
> >
> > import serial
> > import string
> 
> Redundant.
> 
> > import time
> > from struct import *
> >
> > ser = serial.Serial()
> >
> > ser.baudrate = 9600
> > ser.port = 0
> > ser
> 
> What is the above line meant to do? It actually does nothing.
> 
> > ser.close()
> > ser.open()
> >
> > command = 67
> > message_no = 1
> > total_data = 2
> >
> > item = 1
> 
> Redundant.
> >
> 
> print "DEBUG: before outer loop"
> 
> 
> > for item in range(1, 30001, 250):
> 
> print "DEBUG: inside outer loop; item =", repr(item)
> 
> >data_hi, data_lo = divmod(item, 0x100)
> >checksum = -(data_hi + data_lo + 0x46) & 0xff
> 
> You obviouly haven't taken the advice to generalise your checksum
> calculation.
> 
> >ser.write(pack('6B', command, message_no, total_data, data_lo,
> > data_hi, checksum))
> >
> >rx_data1=0
> 
> print "DEBUG: before inner loop"
> 
> >while (rx_data1 != 0x46):
> >rx_data1 = ser.read(1)
> >(rx_command) = unpack('1B', rx_data1)
> 
> print "DEBUG: inside inner loop; rx_data1 =", repr(rx_data1), ";
> rx_command =", repr(rx_command)
> 
> And if you had have done that, you would/should have realised that you
> have a:
> !! CODING BUG !!
> ser.read(1) will return a STRING, so even if you get the byte you are
> looking for, rx_data1 will refer to 'F' == chr(70) == chr(0x46) ==
> '\x46' none of which are == 0x46, and you will loop forever (if the
> hardware is continuously outputting data) or hang waiting for data from
> the hardware.
> 
> !! DESIGN BUG !!
> HOWEVER, as Dennis and I have been trying to tell you, it is WRONG to
> be looping trying to sync on the first character in the packet. You
> need to fix your data loss problem, not try to kludge your way around
> it. I'll say it again, but only once: go back to the code of your
> original posting. That code was not losing data. Among whatever else is
> needed to revert to the first-shown code, put back the sleep() between
> iterations.
> As advised earlier, make sure that you use separate rx_command and
> tx_command so that you don't accidentally start sending 70 as the
> command.
> Then show us what happened.
> 
> > rx_data2=ser.read(9)
> > (rx_msg_no, rx_no_databyte, temp1, temp2, pyra1, pyra2, voltage,
> >  current, rx_checksum) = unpack('9B', data)
> 
> !! CODING BUG !!
> You read into "rx_data2" but unpack from "data". The result, when you
> reach it after fixing the earlier bug, will be either an exception or
> an utter nonsense, depending on what "data" is bound to at the time (if
> anything).
> 
> >  print rx_command, rx_msg_no, rx_no_databyte, temp1, temp2,
> pyra1,
> >  pyra2, voltage, current, rx_checksum
> >
> 
> You obviously haven't taken the advice from Dennis and myself to
>

Re: a program to delete duplicate files

2005-03-14 Thread Bengt Richter
On Mon, 14 Mar 2005 10:43:23 -0800, David Eppstein <[EMAIL PROTECTED]> wrote:

>In article <[EMAIL PROTECTED]>,
> "John Machin" <[EMAIL PROTECTED]> wrote:
>
>> Just look at the efficiency of processing N files of the same size S,
>> where they differ after d bytes: [If they don't differ, d = S]
>
>I think this misses the point.  It's easy to find the files that are 
>different.  Just a file size comparison will get most of them, and most 
>of the rest can be detected in the first few kbytes.  So I think it's 
>safe to assume both of these filtering mechanisms would be incorporated 
>into a good duplicate detection code, and that any remaining tests that 
>would be performed are between files that are very likely to be the same 
>as each other.
>
>The hard part is verifying that the files that look like duplicates 
>really are duplicates.  To do so, for a group of m files that appear to 
>be the same, requires 2(m-1) reads through the whole files if you use a 
>comparison based method, or m reads if you use a strong hashing method.
What do you mean by "a comparison based method" ? Are you excluding the
possibility of parallel reading and comparing? The problem then becomes
verifying that m buffers containing corresponding segments of the files
are equal. You could do that by comparing hashes of the buffers (or updated
running hashes for the whole files so far read), or you could compare the
buffers in parallel byte by byte if that turns out efficient to implement
in the given language and os environment. Small buffers would probably
not be efficient for disk access, but too large might not be good either.
Maybe some automatic tuning algorithm could be developed to optimize
comparison operations in the shadow of i/o. But does the OS accept hints
about read-ahead buffering? Are the disks SCSI raid or USB external or
networked? Can automatic tuning achieve an optimum disregarding all that?

What is it that we're trying to optimize? Time to classify the
whole file set into groups of equivalent files? (note that there can be
multiple groups that are internally equal but uneqal to members of other 
groups).

The problem of limitation on the number of simultaneously open files could
be virtualized away, and only have impact when the limit is actually 
encountered.
  
>You can't hope to cut the reads off early when using comparisons, 
>because the files won't be different.
So the worst case will be reading all through to the end once in parallel.
But pre-hashing guarantees the worst case for all -- unless disk access patterns
happen to make that the most efficient way to get everything read and compared
when most are equal.
>
>The question to me is: when you have a group of m>2 likely-to-be-equal 
>files, is 2(m-1) reads and very little computation better than m reads 
>and a strong hash computation?  I haven't yet seen an answer to this, 
>but it's a question for experimentation rather than theory.
ISTM 2(m-1) reads is not necessary, so "the question" to me doesn't involve 
that ;-)

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


OS X and Tkinter

2005-03-14 Thread Mike Tuller
I recently purchased a book to learn python, and am at a part where I  
want to start working with GUIs. I have an OS X system, and am using  
the default python installed on the system. I have installed Tcl/Tk  
Aqua from http://tcltkaqua.sourceforge.net/.

When I run the file called gui.py that contains this:
from Tkinter import *
root = Tk()
root.title("Simple GUI")
root.geometry("200x100")
I get this back:
python gui.py
Traceback (most recent call last):
  File "gui.py", line 1, in ?
from Tkinter import *
  File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/lib-tk/Tkinter.py", line 38, in ?
import _tkinter # If this fails your Python may not be configured  
for Tk
ImportError: No module named _tkinter

I have looked everywhere on the net, and can't figure out how to  
configure python so that Tkinter will work with it. Any help would be  
appreciated.

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


Re: Listbox fill=BOTH expand=YES (Tkinter)

2005-03-14 Thread Harlin Seritt
either YES, True, or 1 should work.

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


Re: Determining the length of strings in a list

2005-03-14 Thread Michael Spencer
[EMAIL PROTECTED] wrote:
I have a dictionary.  Each key contains a list.  I am using the
contents of the list to build a portion of a command line.
However, before I can build the command line, I have to make sure that
the command isn't too long.
Depending on how you join the list items, you may just be able to use join 
followed by stdlib textwrap to do this in one step (note I've wrapped this 
example at width 20 rather than 200 to make the resulting list easier to read):

 >>> source = ["some", "text", "fragments", "in", "a", "list"] * 10
 >>> import textwrap
 >>> textwrap.wrap(" ".join(source),20)
 ['some text fragments', 'in a list some text', 'fragments in a list', 'some 
text fragments', 'in a list some text', 'fragments in a list', 'some text 
fragments', 'in a list some text', 'fragments in a list', 'some text fragments', 
'in a list some text', 'fragments in a list', 'some text fragments', 'in a list 
some text', 'fragments in a list']

This works because the join separator is whitespace, which textwrap ignores.  If 
however, you need a non-whitespace separator, then textwrap can lead to ugly 
results with a leading or trailing separator:

 >>> textwrap.wrap(", ".join(source),20)
 ['some, fragments, of,', 'text, some,', 'fragments, of, text,', 'some, 
fragments, of,', 'text, some,', 'fragments, of, text,', 'some, fragments, of,', 
'text, some,', 'fragments, of, text,', 'some, fragments, of,', 'text, some,', 
'fragments, of, text,', 'some, fragments, of,', 'text, some,', 'fragments, of, 
text']

If you care about this, you may be able to tweak textwrap.TextWrapper to handle 
this, or you could use your own function, like:

def iterjoin(iterable, separator = " ", width = 70):
"""joins an iterable of strings into strings with width <= maxlen
Not (yet) rejected for inclusion in itertools ;-)"""
accumulator = []
len_accumulator = 0
len_sep = len(separator)
for item in iterable:
item = item.expandtabs()
len_item = len(item)
trial_len = len_accumulator + len_sep + len_item
if trial_len > width:
yield separator.join(accumulator)
accumulator = [item]
len_accumulator = len_item
else:
# continue to build the command
accumulator.append(item)
len_accumulator = trial_len
if accumulator:
yield separator.join(accumulator)
 >>> list(iterjoin(source, ", ", width = 20))
 ['some, fragments', 'of, text, some', 'fragments, of, text', 'some, fragments, 
of', 'text, some', 'fragments, of, text', 'some, fragments, of', 'text, some', 
'fragments, of, text', 'some, fragments, of', 'text, some', 'fragments, of, 
text', 'some, fragments, of', 'text, some', 'fragments, of, text']
 >>>

Now you can simply iterate over each list in your dictionary:
for k in d:
for command in iterjoin(d[k], your_separator_here, width = 200)
HTH
Michael

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


command line args

2005-03-14 Thread [EMAIL PROTECTED]
Hello,

I have the following commands:
testb -s 
testb -s  -o 
testb -s  -o 

How do i split the commands so that all three are valid. And how do i
check for missing arguments?  

Thanks,
-Joe

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


  1   2   >