Re: distutils on Windows with VC++ 8

2006-09-22 Thread Rob Williscroft
Martin v. Löwis wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

> [EMAIL PROTECTED] schrieb:
>> I'm trying to install two different packages which wrap C or C++ code
>> and which make use of distutils.build_ext, which barfs because my only
>> compiler is too new.  Trying this both on Python 2.4.3 and 2.5.
>> Evidently there is a requirement that the compiler used to build the
>> C/C++ in the installation must be the same as was used to build
>> Python?  Am I understanding that correctly?  
> 
> Yes.
> 
>> What's the workaround?
> 
> There are several work-arounds, but they all come down to
> "get a copy of the one of the supported compilers". The options
> are:
> - get a copy of VS 2003 on Ebay

Download the 1.1 SDK:

http://www.microsoft.com/downloads/details.aspx?familyid=9B3A2CA6-
3647-4070-9F41-A333C6B9181D&displaylang=en>

yes it does have 90 odd megabytes of stuff you don't want but the C/C++
compiler is in there.

> - use cygwin/mingw (should work for C, might not work for
>   C++ if you use MFC or some other MS-compiled library)
> - find the VS 2003 Toolkit; Microsoft took it off the net,
>   but Google may still be able to help

I think the VS 2003 toolkit is a framework for extending Visual Studio 
2003, IOW a bunch of .NET dlls, some examples and a helpfile (no 
compiler).

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Strange behaviour of 'is'

2006-09-22 Thread Duncan Booth
Steve Holden <[EMAIL PROTECTED]> wrote:

> Absolutely correct. It would be more interesting to discuss how the 
> output from these statements varied between (say) CPython, Jython and 
> Iron Python. At the moment the discussion is indeed about insignificant 
> implementation trivia.

CPython seems to collapse identical float values if they are in the same 
compilation unit:

>>> x = 2.
>>> y = 2.
>>> x is y
False
>>> x = 2.; y = 2.
>>> x is y
True
>>> y = [2., 2.]
>>> y[0] is y[1]
True

IronPython doesn't collapse them even when they are in expression:

IronPython 1.0.60816 on .NET 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.
>>> x = 2.
>>> y = 2.
>>> x is y
False
>>> x = 2.; y = 2.
>>> x is y
False
>>> y = [2., 2.]
>>> y[0] is y[1]
False

JPython seems to behave in a similar manner to CPython:

Python command console - JPython 2.1

>>> x = 2.
>>> y = 2.
>>> x is y
0

>>> x = 2.; y = 2.
>>> x is y
1

>>> y = [2., 2.]
>>> y[0] is y[1]
1

>>> 

Sorry, I don't have a more recent Jython implementation to hand to complete 
the comparison.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I inherit member variables?

2006-09-22 Thread LorcanM
Thanks Bruno,

That is a more natural way to do it. The code looks a lot cleaner now.


 Lorcan.

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


Re: new string method in 2.5 (partition)

2006-09-22 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Gabriel
Genellina wrote:

> ... a python string has both a length *and* a null terminator (for
> ease of interfacing C routines ...

How does that work for strings with embedded nulls? Or are the C routines
simply fooled into seeing a truncated part of the string?
-- 
http://mail.python.org/mailman/listinfo/python-list


what is the best practice to separate Pygtk and long running thread code

2006-09-22 Thread seb
Hi,

I am using pygtk for the first times.

I am wondering what would be the best "pattern" to interface pygtk with
a thread.

The thread is collecting informations (over the network for example) or
is doing some long calculations.

I would like also to separate the gui part to the action part so that I
should be easier to maintain.


What should be the best practice in order to achieve this ?
***

What I use now is :



1)
the gui is launching the "action" evrey 1 sec and is checking for
message using a queue every second also.

gui.py

etc ...
class window1(SimpleGladeApp):
[EMAIL PROTECTED] class window1 }
[EMAIL PROTECTED] init window1.__init__ {
def __init__(self, path='gui.glade',
 root='window1',
 domain=app_name, kwargs={}):
path = os.path.join(glade_dir, path)
SimpleGladeApp.__init__(self, path, root, domain, **kwargs)
self.q=Queue.Queue()
self.action=act.action(self.q)
gobject.timeout_add (1000,self.action.go) # this is the action
asked
gobject.timeout_add (1000,self.process) # check if a new message is
available in the queue

def process (self):
dir (self.q)
if self.q.empty() == False :
print "from main ",self.q.get()
return True

 ...etc 

2)
The action part is making somehow the interface between the running
thread and the gui :
It puts the new information in the queue for the gui to process it
later.


action.py

import os
import gui
import time
import Queue
import Spethread # thread that always run in the background

class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args,
**kwargs)
return cls._instance


class action(Singleton):
def __init__(self, queue):
self.q=queue
self.thread_seb=Spethread.worker()
self.thread_seb.start()
self.go()

def go(self):
if self.thread_seb:
reponse=self.thread_seb.status()
self.q.put(reponse)
else :
self.q.put("le thread n'existe plus ")
return True

def stop(self):
self.thread_seb.die()


3)
The thread part is "just" a thread that should from time to time
time.Sleep in order for action to query if it has some new messages.

Spethread.py

import threading
import time

class worker(threading.Thread):

def __init__(self):
threading.Thread.__init__(self)
self.value=0
self.go_on=1

def run(self):
print "self.go_on=",self.go_on
while self.go_on == 1:
self.value=int(time.time())
res=2
for i in range(0, 100):
res=res^i
print res
time.Sleep(0.01)
def status(self):
return self.value


def die(self):
print "die request"
self.go_on=0


Thanks in advance for sharing this informations.
Sebastien.

PS :
the entire gui.py

[EMAIL PROTECTED] python gui.py {
[EMAIL PROTECTED] header gui.py {
#!/usr/bin/env python
# -*- coding: UTF8 -*-

# Python module gui.py
# Autogenerated from gui.glade
# Generated on Wed Sep 20 22:03:00 2006

# Warning: Do not modify any context comment beginning with # @--
# They are required to keep user's code
# Doing so will make it unable for kefir to help you further manage
your project

[EMAIL PROTECTED] header gui.py }
[EMAIL PROTECTED] app gui {
import os
import gobject
import gtk
import action as act
import Queue

from SimpleGladeApp import SimpleGladeApp, bindtextdomain

app_name = 'gui'
app_version = '0.0.1'

glade_dir = ''
locale_dir = ''

bindtextdomain(app_name, locale_dir)

[EMAIL PROTECTED] app gui }
[EMAIL PROTECTED] window window1 {
[EMAIL PROTECTED] class window1 {
class window1(SimpleGladeApp):
[EMAIL PROTECTED] class window1 }
[EMAIL PROTECTED] init window1.__init__ {
def __init__(self, path='gui.glade',
 root='window1',
 domain=app_name, kwargs={}):
path = os.path.join(glade_dir, path)
SimpleGladeApp.__init__(self, path, root, domain, **kwargs)
self.q=Queue.Queue()
self.action=act.action(self.q)
gobject.timeout_add (1000,self.action.go)
gobject.timeout_add (1000,self.process)
[EMAIL PROTECTED] init window1.__init__ }
[EMAIL PROTECTED] new window1.new {
def new(self):
print 'A new %s has been created' % self.__class__.__name__
[EMAIL PROTECTED] new window1.new }
[EMAIL PROTECTED] custom window1 {
#   Write your own methods here
[EMAIL PROTECTED] custom window1 }
[EMAIL PROTECTED] callback window1.on_bu

Re: new string method in 2.5 (partition)

2006-09-22 Thread Duncan Booth
Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:

> In message <[EMAIL PROTECTED]>, Gabriel
> Genellina wrote:
> 
>> ... a python string has both a length *and* a null terminator (for
>> ease of interfacing C routines ...
> 
> How does that work for strings with embedded nulls? Or are the C routines
> simply fooled into seeing a truncated part of the string?
> 
If passed to a C library function it would mean that the C code would 
generally only use up to the first embedded null. However the Python 
standard library will usually check for nulls first so it can throw an 
error:

>>> with open('test.txt', 'r') as f:
... print f.read()
...
Hello world

>>> with open('test.txt\x00junk', 'r') as f:
... print f.read()
...
Traceback (most recent call last):
  File "", line 1, in 
TypeError: file() argument 1 must be (encoded string without NULL 
bytes), not str
>>>

What actually happens is that Python argument parsing code will reject 
values with embedded nulls if asked to convert a parameter to a C string 
('s', 'z', 'es', or 'et' formats), but will allow them if converting to a C 
string and a length ('s#', 'z#', 'es#', or 'et#').
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I need some help with a regexp please

2006-09-22 Thread Ant

John Machin wrote:
...
> A little more is unfortunately not enough. The best advice you got was
> to use an existing e-mail address validator.

We got bitten by this at the last place I worked - we were using a
regex email validator (from Microsoft IIRC), and we kept having
problems with specific email addresses from Ireland. There are stack of
Irish email addresses out there of the form paddy.o'[EMAIL PROTECTED] -
perfectly valid email address, but doesn't satisfy the usual naive
versions of regex validators.

We use an even worse validator at my current job, but the feeling the
management have (not one I agree with) is that unusual email addresses,
whilst perhaps valid, are uncommon enough not to worry about

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


Re: Python and CORBA

2006-09-22 Thread Eric Brunel
On Thu, 21 Sep 2006 15:11:07 +0200, Diez B. Roggisch <[EMAIL PROTECTED]>  
wrote:
> AFAIK Fnorb also had license issues - I'm not entirely sure of that, but
> better check it.

The earlier versions seem to have been somewhat proprietary, but the  
latest one should be as free as Python is. Extract from the license  
agreement (just before the legalese starts):

"""
The intent of this license is to grant you the same freedoms to use fnOrb
that you enjoy under the Python 2.2 License  
(http://www.python.org/2.2/license.html).
"""

So there should be no problem with that (AFAICT, but I'm no lawyer...)

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Don't use regular expressions to "validate" email addresses (was: I need some help with a regexp please)

2006-09-22 Thread Ant

Ben Finney wrote:
...
> The best advice I've seen when people ask "How do I validate whether
> an email address is valid?" was "Try sending mail to it".

There are advantages to the regex method. It is faster than sending an
email and getting a positive or negative return code. The delay may not
be acceptable in many applications. Secondly, the false negatives found
by a reasonable regex will be few compared to the number you'd get if
the smtp server went down, or a remote relay was having problems
delivering the message etc etc.

>From a business point of view, it is probably more important to reduce
the number of false negatives than to reduce the number of false
positives - every false negative is a potential loss of a customer.
False positives? Who cares really as long as they are paying ;-)

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


Re: Don't use regular expressions to "validate" email addresses (was: Ineed some help with a regexp please)

2006-09-22 Thread Bruno Desthuilliers
bruce wrote:
> so ben...
> 
> if you were creating a web app with an email form... rather than try to
> check if the email is valid...

Ever bothered to read the relevant rfc ?

> you'd create something to allow anyone to
> potentially spam the hell out of a system...

I'm sorry, but I fail to see how validating (or not) an email address
could prevent using a webmail form for spamming. Care to elaborate ?

> my two cents worth... try to verify/validate that the email is valid, 

If it doesn't have an @ somewhere in it, it's not a valid mail address.
Else, it may or not be a valid email address - and then the only
reliable way to know is to send a mail to that address.

> and
> possibly belongs to the user...

How do you intend to check this ?

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


Re: Don't use regular expressions to "validate" email addresses

2006-09-22 Thread John Machin

Ben Finney wrote:
> Steve Holden <[EMAIL PROTECTED]> writes:
>
> > Ben Finney wrote:
> > > The best advice I've seen when people ask "How do I validate
> > > whether an email address is valid?" was "Try sending mail to it".
> > >
> > That only applies if it's a likely-looking email address. If someone
> > asks me to send mail to "splurge.!#$%*&[EMAIL PROTECTED]><{}_)" I will
> > probably assume that it isn't worth my time trying.
>
> You, as a human, can possibly make that decision, if you don't care
> about turning away someone who *does* have such an email address. How
> can an algorithm do so? There are many valid email addresses that look
> as bizarre as the example you gave.
>
> > > The sending system's mail transport agent, not regular
> > > expressions, determines which part is the domain to send the mail
> > > to.
> > >
> > > The domain name system, not regular expressions, determines what
> > > domains are valid, and what host should receive mail for that
> > > domain.
> > >
> > > Most especially, the receiving mail system, not regular
> > > expressions, determines what local-parts are valid.
> > >
> > Nevertheless, I am *not* going to try delivery to (for example) a
> > non-local address that doesn't contain an "at@ sign.
>
> Would you try delivery to an email address that contains two or more
> "@" symbols? If not, you will be denying delivery to valid RFC2821
> addresses.
>
> This is, of course, something you're entitled to do. But you've then
> consciously chosen not to use "is the email address valid?" as your
> criterion, and the original request for such validation becomes moot.
>

What proportion of deliverable e-mail addresses have more than one @ in
them?
It may be a good idea, if the supplier of the e-mail address is a human
and is on-line, to run a plausibility check -- does it look like the
vast majority of addresses? Sure,
"[EMAIL PROTECTED]@[EMAIL PROTECTED]" may be valid and deliverable,
but "[EMAIL PROTECTED]@pastetwice.unorg" may be valid and
undeliverable. IMHO a quick "Please check and confirm" dialogue would
be warranted.

Cheers,
John

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


Re: Don't use regular expressions to "validate" email addresses (was:Ineed some help with a regexp please)

2006-09-22 Thread Fredrik Lundh
Bruno Desthuilliers wrote:

>> if you were creating a web app with an email form... rather than try to
>> check if the email is valid...
>
> Ever bothered to read the relevant rfc ?

or the perl faq:

http://faq.perl.org/perlfaq9.html#How_do_I_check_a_val

 



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


Re: I need some help with a regexp please

2006-09-22 Thread John Machin

Ant wrote:
> John Machin wrote:
> ...
> > A little more is unfortunately not enough. The best advice you got was
> > to use an existing e-mail address validator.
>
> We got bitten by this at the last place I worked - we were using a
> regex email validator (from Microsoft IIRC), and we kept having
> problems with specific email addresses from Ireland. There are stack of
> Irish email addresses out there of the form paddy.o'[EMAIL PROTECTED] -
> perfectly valid email address, but doesn't satisfy the usual naive
> versions of regex validators.
>
> We use an even worse validator at my current job, but the feeling the
> management have (not one I agree with) is that unusual email addresses,
> whilst perhaps valid, are uncommon enough not to worry about

Oh, sorry for the abbreviation. "use" implies "source from believedly
reliable s/w source; test; then deploy" :-)

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


Re: Building things with setup.py

2006-09-22 Thread James Stroud
Robert Kern wrote:
> James Stroud wrote:
>> I did build my own python 2.5, yesterday, requiring me to rebuild all 
>> extensions.
> 
> Do other extensions build correctly? If so, it's beginning to look like 
> a problem in numpy.distutils .

It seems that every thing has built without incident (numarray, numeric, 
mxtexttools, pil, reportlab, just to name a few), with the exception, 
strangely enough, of python2.5 itself. Python required hiding previous 
python installations.

>> Everything I do is compiled by hand as joe-user. I'm in a situation 
>> where I can't do RPM (and I don't have root on my work machine 
>> (theoretically ;-)) so, to be a good joe-user, everything I add goes 
>> into the prefix:
>>
>> $HOME/Programs
>>
>> This is the listing from $HOME/Programs/lib/python2.5/config:
>>
>> euler 6% ls
>> total 4092
>> 8 config.c   12 install-sh*   44 Makefile   8 python.o 
>> 8 Setup.config
>> 8 config.c.in  3960 libpython2.5.a12 makesetup*24 Setup 
>> 8 Setup.local
>>
>> The build process, by the way, required my copying libpython2.5.a to 
>> $HOME/Programs/lib.
> 
> Hmm. That doesn't quite sound right, but it's been a while since I 
> compiled the interpreter from source.

Sorry. To clarify, making libpython2.5a available in a $LD_LIBRARY_PATH 
was necessary to build numpy and scipy.

>> The text files Setup.config and Setup.local do not seem to have 
>> terribly specific information in them. Which file in particular should 
>> I inspect?
> 
> Makefile has most of that information. You can verify that distutils is 
> finding it like so:
> 
>  >>> from distutils import sysconfig
>  >>> sysconfig.get_makefile_filename()
> '/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/config/Makefile'
>  
> 
>  >>> d = sysconfig.parse_makefile(_)
>  >>> import pprint
>  >>> pprint.pprint(d)
> {'AR': 'ar',
>  ...
> }

This output from the check is here:
http://www.jamesstroud.com/build-scipy-logs/distutil-check.txt

I'm not sure if this is relevant to what you see in the check, but I 
installed scipy_distutils AFTER installing scipy.

>> I did not capture output from the build and I could not find a file 
>> with the word "log" in it that appears to be a build log. The jist of 
>> the problem is that first it can't find symbols from libpython2.5, 
>> then from   libthread, etc. Then, it complains about no "MAIN__" when 
>> linking the .so files with g77 and no "main" with gcc (which is 
>> curious), so I must include the -shared flag, after including 
>> -llibrary type flags for all of the libraries it doesn't know about.
> 
> What versions of gcc and g77 are you using?

euler 2% g77 -v
Reading specs from 
/auto_nfs/data10/users/jstroud/Programs/bin/../lib/gcc/i686-pc-linux-gnu/3.4.2/specs
Configured with: ./configure --prefix=/data1/users/jstroud/Programs : 
(reconfigured) ./configure --prefix=/data1/users/jstroud/Programs
Thread model: posix
gcc version 3.4.2
euler 3% gcc -v
Reading specs from 
/auto_nfs/data10/users/jstroud/Programs/bin/../lib/gcc/i686-pc-linux-gnu/3.4.2/specs
Configured with: ./configure --prefix=/data1/users/jstroud/Programs : 
(reconfigured) ./configure --prefix=/data1/users/jstroud/Programs
Thread model: posix
gcc version 3.4.2

>> If its necessary, I can run setup.py build again and send the output 
>> to a file and post that to scipy-dev if you think it might be helpful.
> 
> Yes, that is what I intended.
> 

This is posted here:
http://www.jamesstroud.com/build-scipy-logs/build-scipy-py2.5-euler.txt

For symmetry, similar output for numpy is posted here:
http://www.jamesstroud.com/build-scipy-logs/build-numpy-py2.5-euler.txt

Please let me know if I can be of any further help with these issues.

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


Re: Building things with setup.py

2006-09-22 Thread James Stroud
Martin v. Löwis wrote:
> James Stroud schrieb:
>> This is annoying. I am trying to build scipy right now but every .so
>> file requires my adding "-lpython2.5 -lpthread -lm -lutil -ldl -shared"
>> to the ld flags.
> 
> That shouldn't be necessary. Linking without this should work just fine.

Unfortunately, this was not my experience.

> That way, since you made libpython2.5.a a static library, you link an
> entire Python interpreter into each and every extension module. This
> should not be done.

Actually, a straight configure, make, install of the python2.5 source 
produced this library.

> What happens if you omit these flags?

Please see my last message to Robert Kern.

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


Re: Can I inherit member variables?

2006-09-22 Thread Bruno Desthuilliers
Gabriel Genellina wrote:
> At Thursday 21/9/2006 09:14, Bruno Desthuilliers wrote:
> 
>> > When you construct an object instance, it is of a certain type from
>> that
>> > precise moment, and you can't change that afterwards.
>>
>> Err... Actually, in Python, you can. It's even a no-brainer.
> 
> Yes, but trying to explain that to a beginner would just make things
> worse...

Agreed. But this newsgroup is not only read by beginners, and the last
part of your statement happens to be false. The first part is ok, and
would have been enough IMHO.

> You must grab the inheritance concept first.

Mmm... It's clear that the OP didn't get the concept right...

OTHO, inheritance (not subtyping...) is a very overrated concept IMHO
and really not central to OO - at least with dynamically typed languages
(or using type inference). It's in fact nothing more than a special case
of composition/delegation. What's really important here is polymorphic
dispatch, which shouldn't (and, in Python, doesn't) rely on
implementation inheritance.

I really think that insisting on implementation inheritance is the wrong
way to teach OO. But I may not be a good teacher !-)


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


Re: Tkinter button not working as expected

2006-09-22 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I've created a short test program that uses tkFileDialog.askdirectory
> to help the user input a path into a tk entry widget.  The problem I'm
> having is that when I run the code as listed below, the getPath
> function is called when the program initially runs, not when the button
> is pressed.

the right side of an assignment is always evaluated before it is assigned, so

self.button["command"] = self.getPath(t)

will call self.getPath(t) and then assign the return value to button["command"].
quite obvious, if you think about it, right ?

the easiest way to fix this is to add a local function that calls getPath, and
use that as the button callback:

def callback():
self.getPath(t)
self.button["command"] = callback

(if you want, you can inline the getPath code in the callback).

 



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


Re: Is it possible to save a running program and reload next time ?

2006-09-22 Thread [EMAIL PROTECTED]
Hans Georg Krauthaeuser wrote:
> [EMAIL PROTECTED] wrote:
>   
>> Hans Georg Krauthaeuser wrote:
>> 
>>> [EMAIL PROTECTED] wrote:
>>>  
>>>   
 Can objects be saved and reloaded by "Pickle"  ?  I have tried but no
 success.

 
 
>>> Yes, that's the intended use of pickle/cPickle. There are examples in
>>> the docs:
>>>
>>> http://docs.python.org/lib/module-pickle.html
>>>
>>> What have you tried and what didn't work?
>>>
>>> Hans Georg
>>>   
>>>   
>> My program is a genetic algorithm based program, so I thought I just
>> need to save a generation object of the population and reload it later
>> then my program could continue. But after I saved a generation object
>> from within python using cPickle and reload it from another program, it
>> said that some class object couldn't be found. Now I realized that a
>> program cannot be suspended and reloaded by just simply dumping and
>> loading using cPickle/Pickle.
>>
>> I will try stackless python later.
>>
>> Thanks a lot .
>>
>> Regards,
>>
>> xiaojf
>>
>> 
> I use pickle to periodically save measured data for measurements that
> take several days to finish. Actually, I save a class instance with the
> data, the measurement methods and additional informations what method
> was called and with what parameters. If the measurement crashes due to
> some reasons, I recreate the class instance from the pickle file, call
> the appropriate method with the saved parameters. Then, the method has
> to look what data is already there and will continue to measure the rest.
>
> I have no idea whether that will help you in your situation.
>
> Anyway, I wish you all the best.
>
> Hans Georg
>   
I just realized another serious problem.

Random values are extensively used in my program, so the program may 
probably not continue to run from an absolutely identical state where it 
stopped. 

Can the state of the random value generator be saved ?

Regards,

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


Re: Don't use regular expressions to "validate" email addresses

2006-09-22 Thread Ben Finney
"John Machin" <[EMAIL PROTECTED]> writes:

> What proportion of deliverable e-mail addresses have more than one @
> in them?

I don't know. Fortunately, I don't need to; I don't "validate" email
addresses by regular expression.

What proportion of deliverable email addresses do you want to discard
as "not valid"?

-- 
 \   "Theology is the effort to explain the unknowable in terms of |
  `\  the not worth knowing."  -- Henry L. Mencken |
_o__)  |
Ben Finney

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


Re: Building things with setup.py

2006-09-22 Thread James Stroud
Robert Kern wrote:
> James Stroud wrote:
>> I did build my own python 2.5, yesterday, requiring me to rebuild all 
>> extensions.
> 
> Do other extensions build correctly? If so, it's beginning to look like 
> a problem in numpy.distutils .

Actually, I just found that MySQLdb had a similar problem with zlib, but 
instead of bonking during linking, it complained about the compress 
symbol when trying to import into python. The fix was adding "-lz" for 
the linking step, after which it imported just fine.

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


Re: Don't use regular expressions to "validate" email addresses

2006-09-22 Thread John Machin

Ben Finney wrote:
> "John Machin" <[EMAIL PROTECTED]> writes:
>
> > What proportion of deliverable e-mail addresses have more than one @
> > in them?
>
> I don't know. Fortunately, I don't need to; I don't "validate" email
> addresses by regular expression.
>
> What proportion of deliverable email addresses do you want to discard
> as "not valid"?

None. Re-read my post. I was suggesting suggesting an "are you sure" in
the case of weird or infrequent ones. Discarding wasn't mentioned.

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


Re: Is it possible to save a running program and reload next time ?

2006-09-22 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> Can the state of the random value generator be saved ?

Yes. You can pickle random._inst or your own random.Random instance.

Peter 

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


CONSTRUCT - New/Old Style Classes, build-in/extension types

2006-09-22 Thread Ilias Lazaridis
Another topic [1] has raised the need of a deeper teach-in.

Where can I find _compact_ documentation about

 * Differece between New Style / Old Style Classes

Are there any documents available (again: compact ones) which describe
unification attemps subjecting

 * New Style Classes
 * Old Style Classes
 * Build In Types
 * Extension Types

(note: I am aware about search engines. I ask for documentation which
other developers have found useful)

.

[1]
CONSTRUCT - Adding Functionality to the Overall System
http://groups.google.com/group/comp.lang.python/browse_thread/thread/4618ccef252c82cd

--
http://lazaridis.com

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


Re: byte count unicode string

2006-09-22 Thread Paul Rubin
willie <[EMAIL PROTECTED]> writes:

>  >>> ustr = buf.decode('UTF-8')
>  >>> type(ustr)
> 
> Is it a "unicode object that contains a UTF-8 encoded
> string object?"

No, it's just unicode, which is a string over a certain character set.
UTF-8 is a way to encode unicode strings as byte strings.

You should read the wikipedia article about unicode, it will help you
understand.

http://en.wikipedia.org/wiki/Unicode
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CONSTRUCT - New/Old Style Classes, build-in/extension types

2006-09-22 Thread Fredrik Lundh
Ilias Lazaridis wrote:

> note: I am aware about search engines.

but you're incapable of using them, or ?

> I ask for documentation which other developers have found useful

most recent Python books contains good discussions of the things you're
asking for.  maybe you should buy a book ?

 



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


Re: CONSTRUCT - New/Old Style Classes, build-in/extension types

2006-09-22 Thread Ben Finney
"Ilias Lazaridis" <[EMAIL PROTECTED]> writes:

> Where can I find _compact_ documentation about

Can you tell us what is lacking about the documentation at
http://www.python.org/doc/> ? Specifically, what problems have
you found in understanding these topics from the documentation
available at that site?

-- 
 \"The World is not dangerous because of those who do harm but |
  `\  because of those who look at it without doing anything."  -- |
_o__)  Albert Einstein |
Ben Finney

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


Re: distutils on Windows with VC++ 8

2006-09-22 Thread NoelByron
I use the Visual C++ Toolkit 2003 to compile Python extension for
Python 2.4. Once installed, it works well. With and without distutils.
I also have a installation of Visual Studio 2005 on the same machine.

See:
http://www.vrplumber.com/programming/mstoolkit/
for more information.

There are a lot of tools 'missing' in VTK 2003 for example nmake or
cvtres. If you need them, you can copy them from your VS 2005
installation. BTW VTK 2003 does not come with debugging versions of the
runtime libs. That means you can not build debug releases this way.

HTH,
Noel

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


Re: Don't use regular expressions to "validate" email addresses (was: Ineed some help with a regexp please)

2006-09-22 Thread Damjan
>> you'd create something to allow anyone to
>> potentially spam the hell out of a system...
> 
> I'm sorry, but I fail to see how validating (or not) an email address
> could prevent using a webmail form for spamming. Care to elaborate ?

The best way would be to implement some limiting features. Try two times
from the same IP address in less than 10 minutes and you are banned for the
day. Or some such.


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


Re[2]: unicode mystery/problem

2006-09-22 Thread Petr Jakeš
John, thanks for your extensive answer.
>> Hi,
>> I am using Python 2.4.3 on Fedora Core4 and  "Eric3" Python IDE
>> .
>> Below mentioned code works fine in the Eric3 environment. While trying
>> to start it from the command line, it returns:
>>
>> Traceback (most recent call last):
>>   File "pokus_1.py", line 5, in ?
>> print str(a)
>> UnicodeEncodeError: 'ascii' codec can't encode character u'\xc1' in
>> position 6: ordinal not in range(128)

JM> So print a works, but print str(a) crashes.

JM> Instead, insert this:
JM>import sys
JM>print "default", sys.getdefaultencoding()
JM>print "stdout", sys.stdout.encoding
JM> and run your script at the command line. It should print:
JM> default ascii
JM> stdout x
  in the command line it prints:  *
default ascii
stdout UTF-8
JM> here, and crash at the later use of str(a).
JM> Step 2: run your script under Eric3. It will print:
JM> default y
JM> stdout z

  in the Eric3 it prints:  
if the # -*- Eencoding: utf_8 -*- is set than:

default utf_8
stdout
unhandled AttributeError, "AsyncFile instance has no attribute
'encoding' "

if the encoding is not set than it prints:

DeprecationWarning: Non-ASCII character '\xc3' in file
/root/eric/analyza_dat_TPC/pokus_1.py on line 26, but no encoding
declared; see http://www.python.org/peps/pep-0263.html for details 
execfile(sys.argv[0], self.debugMod.__dict__)

default latin-1
stdout
unhandled AttributeError, "AsyncFile instance has no attribute
'encoding' "

JM> and then should work properly. It is probable that x == y == z ==
JM> 'utf-8'
JM> Step 3: see below.

>>
>> == 8< =
>> #!/usr/bin python
>> # -*- Encoding: utf_8 -*-

JM> There is no UTF8-encoded text in this short test script. Is the above
JM> encoding comment merely a carry-over from your real script, or do you
JM> believe it is necessary or useful in this test script?
Generally, I am working with string like u'DISKOV\xc1 POLE' (I am
getting it from the database)

My intention to use >> # -*- Encoding: utf_8 -*- was to suppress
DeprecationWarnings if I use utf_8 in the code (like u'DISKOV\xc1 POLE')

>>
>> a= u'DISKOV\xc1 POLE'
>> print a
>> print str(a)
>> == 8< =
>>
>> Even it looks strange, I have to use str(a) syntax even I know the "a"
>> variable is a string.

JM> Some concepts you need to understand:
JM> (a) "a" is not a string, it is a reference to a string.
JM> (b) It is a reference to a unicode object (an implementation of a
JM> conceptual Unicode string) ...
JM> (c) which must be distinguished from a str object, which represents a
JM> conceptual string of bytes.
JM> (d) str(a) is trying to produce a str object from a unicode object. Not
JM> being told what encoding to use, it uses the default encoding
JM> (typically ascii) and naturally this will crash if there are non-ascii
JM> characters in the unicode object.

>> I am trying to use ChartDirector for Python (charts for Python) and the
>> method "layer.addDataSet()" needs above mentioned syntax otherwise it
>> returns an Error.

JM> Care to tell us which error???
you can see the Error description and author comments here:
http://tinyurl.com/ezohe

>>
>> layer.addDataSet(data, colour, str(dataName))
I have try to experiment with the code a bit.
the simplest code where I can demonstrate my problems:
#!/usr/bin python
import sys
print "default", sys.getdefaultencoding()
print "stdout", sys.stdout.encoding
   
a=['P\xc5\x99\xc3\xad','Petr Jake\xc5\xa1']
b="my nice try %s" % ''.join(a).encode("utf-8")
print b

When I run it from the command line i am getting:
sys:1: DeprecationWarning: Non-ASCII character '\xc3' in file pokus_1.py on 
line 26, but no encoding declared; see http://www.python.org/peps/pep-0263.html 
for details

default ascii
stdout UTF-8

Traceback (most recent call last):
  File "pokus_1.py", line 8, in ?
b="my nice try %s" % ''.join(a).encode("utf-8")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 1: ordinal 
not in range(128)



JM> The method presumably expects a str object (8-bit string). What does
JM> its documentation say? Again, what error message do you get if you feed
JM> it a unicode object with non-ascii characters?

JM> [Step 3] For foo in set(['x', 'y', 'z']):
JM> Change str(dataName) to dataName.encode(foo). Change any debugging
JM> display to use repr(a) instead of str(a). Test it with both Eric3 and
JM> the command line.

JM> [Aside: it's entirely possible that your problem will go away if you
JM> remove the letter u from the line a= u'DISKOV\xc1 POLE' -- however if
JM> you want to understand what is happening generally, I suggest you don't
JM> do that]

JM> HTH,
JM> John


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


Re: Don't use regular expressions to "validate" email addresses

2006-09-22 Thread Steve Holden
Ben Finney wrote:
> "John Machin" <[EMAIL PROTECTED]> writes:
> 
> 
>>What proportion of deliverable e-mail addresses have more than one @
>>in them?
> 
> 
> I don't know. Fortunately, I don't need to; I don't "validate" email
> addresses by regular expression.
> 
> What proportion of deliverable email addresses do you want to discard
> as "not valid"?
> 
Just as a matter of interest, are you expecting that you'll find out 
about the undeliverable ones? Because in many cases nowadays you wont, 
since so many domains are filtering out "undeliverable mail" messages as 
an anti-spam defence.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Strange behaviour of 'is'

2006-09-22 Thread Steve Holden
Duncan Booth wrote:
> Steve Holden <[EMAIL PROTECTED]> wrote:
> 
> 
>>Absolutely correct. It would be more interesting to discuss how the 
>>output from these statements varied between (say) CPython, Jython and 
>>Iron Python. At the moment the discussion is indeed about insignificant 
>>implementation trivia.
> 
> 
> CPython seems to collapse identical float values if they are in the same 
> compilation unit:
> 
> 
x = 2.
y = 2.
x is y
> 
> False
> 
x = 2.; y = 2.
x is y
> 
> True
> 
y = [2., 2.]
y[0] is y[1]
> 
> True
> 
> IronPython doesn't collapse them even when they are in expression:
> 
> IronPython 1.0.60816 on .NET 2.0.50727.42
> Copyright (c) Microsoft Corporation. All rights reserved.
> 
x = 2.
y = 2.
x is y
> 
> False
> 
x = 2.; y = 2.
x is y
> 
> False
> 
y = [2., 2.]
y[0] is y[1]
> 
> False
> 
> JPython seems to behave in a similar manner to CPython:
> 
> Python command console - JPython 2.1
> 
> 
x = 2.
y = 2.
x is y
> 
> 0
> 
> 
x = 2.; y = 2.
x is y
> 
> 1
> 
> 
y = [2., 2.]
y[0] is y[1]
> 
> 1
> 
> 
> 
> Sorry, I don't have a more recent Jython implementation to hand to complete 
> the comparison.

Perfectly all right: you make the point very well that the behavior is 
an implementation artifact and not a language feature.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: I need some help with a regexp please

2006-09-22 Thread Ant

John Machin wrote:
> Ant wrote:
> > John Machin wrote:
> > ...
> > > A little more is unfortunately not enough. The best advice you got was
> > > to use an existing e-mail address validator.
> >
> > We got bitten by this at the last place I worked - we were using a
> > regex email validator (from Microsoft IIRC)
...
> Oh, sorry for the abbreviation. "use" implies "source from believedly
> reliable s/w source; test; then deploy" :-)

I actually meant that we got bitten by using a regex validator, not by
using an existing one. Though we did get bitten by an existing one, and
it being from Microsoft we should have known better ;-)

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


Re: send with timeout socket

2006-09-22 Thread Steve Holden
Stéphane Ninin wrote:
>   Hello,
> 
> I have a few questions regarding sockets with timeouts.
> 
> Assuming you set a timeout t on a socket s and then call:
> 
> 
> 1) s.sendall
> Is the socket.timeout exception thrown when
> not the data was sent in the given time t 
> or if nothing was sent ?
> 
> 2) Similar question for s.send:
> Is the socket.timeout exception thrown when 
> nothing was sent or ... ?
> 
> 
>   What I am actually trying to do is this:
> 
> I have a thread which uses a socket to communicate with a socket server,
> the socket sends data to the server, but it shouldnot block on the send,
> so I want to do something like this:
> 
> def sendall(self,data):
> while data:
> n = self.send(data)
> data = data[n:]
>try:
>self.request.send(data)
> except socket.timeout, e:
>if self.isTerminated():
>   return
> 
> but I am not sure this would work the way I want.
> 
It wouldn't even compile, as your indentation is shot.

Plus, if the first send attempt (the one before the try) sends all the 
data you then try to send an empty string, which seems a little weird: I 
don't see the point of the try/except.

> (self.isTerminated just checks is some event 
> has been set by another thread)
> 
> 
>  Thanks for comments/suggestions/answers,
> 
>  
Sending sockets will usually only block when the sliding window is full 
(the sender has sent as much data as the remote receiver has indicated 
it can safely receive without loss) and no acknowledgment has been 
received from the remote receiver.

Rather than a timeout it would seem sensible, if you don't want the 
sending socket to block, to use a non-blocking socket. That way you get 
a socket.error if a send would otherwise block.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


noob question

2006-09-22 Thread xandeer
where is a good open-source project website?
thank-you
(sorry for being so annoying)(if I'm annoying)(if not then I'm not
sorry)

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


Re: Writing Video conference software for Windows

2006-09-22 Thread Paolo Pantaleo
Thnx everybody for the precious help :)

Someone said about VNC... I'll take a look, but since it is an
exercise I need to do it, I can't just say someone else arelady did
that :)

Everything seems quite useful. I forgot two specifications:

1. Screen should be split in small squares and only the changing
squares must be transmitted (Ok it shouldn't be too difficult)

2. The comunication must be in multicast

I will spend some time testing the resources.

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


Re: what is the best practice to separate Pygtk and long running thread code

2006-09-22 Thread Thomas Guettler
seb wrote:

> Hi,
>
> I am using pygtk for the first times.
>
> I am wondering what would be the best "pattern" to interface pygtk with
> a thread.
>
> The thread is collecting informations (over the network for example) or
> is doing some long calculations.

Hi,

I would use several *processes*. If your scripts runs on Unix/Linux
you can use select() on the filedescriptors of the processes you created
with popen. On Windows you need to poll them, but maybe this is
better than threads, too. With idle_add you can get data from
the subproceses. It gets called if there are no actions in the
event-loop.

HTH,
 Thomas

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

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


Secure MultiRobot Management

2006-09-22 Thread Raja
Hi,
   I am currently doing my final year project "Secure mobile Robot
Management" . I have done the theoretical aspects of it till now and
now thinking of coding it .

I would like to code in Python , but i am new to Python Network
Programming .
Some of features of my project are:

1.  Each robot can send data to any other robot.
2. Each robot can receive data from any other robot.
3.  Every Robot has atleast 1 other bot in its communication range.
4.  maximum size of a data packet is limited to 35 bytes
5.  each mobile robot maintains a table with routes
6.  all the routes stored in the routing table include a ï¬eld named
life-time.
7.  Route Discovery Process initiated if there is no known route to
other bot.
8. There is no server over here .
9. every bot should be able to process the data from other bots and
both multicast/unicast
 need to be supported.

Assume the environment is gridded mesh and bots exploring the area.
They need to perform a set of tasks (assume finding some locations
which are dangerous or smthing like that).

My main concern is how to go about modifying the headers such that
everything fits in 35bytes .
I would like to know how to proceed and if any links or resources in
this regard. How to modify the headers ? ie. all in 35 bytes .

Thank You, 
Raja.

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


Python Network Programming

2006-09-22 Thread Raja Rokkam
Hi,   I am currently doing my final year project "Secure mobile Robot Management" . I have done the theoretical aspects of it till now and now thinking of coding it .I would like to code in Python , but i am new to Python Network Programming . 
Some of features of my project are: 1.  Each robot can send data to any other robot.2. Each robot can receive data from any other robot.3.  Every Robot has atleast 1 other bot in its communication range.
4.  maximum size of a data packet is limited to 35 bytes5.  each mobile robot maintains a table with routes6.  all the routes stored in the routing table include a ï¬eld named life-time.7.  Route Discovery Process initiated if there is no known route to other bot.
8. There is no server over here . 9. every bot should be able to process the data from other bots and both multicast/unicast     need to be supported.Assume the environment is gridded mesh and bots exploring the area. They need to perform a set of tasks (assume finding some locations which are dangerous or smthing like that).
My main concern is how to go about modifying the headers such that everything fits in 35bytes . I would like to know how to proceed and if any links or resources in this regard. How to modify the headers ? ie. all in 35 bytes . 
Thank You, Raja.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Threading

2006-09-22 Thread Bryan Olson
Calvin Spealman wrote:
> I repeat this all the time, but the best advice I can give you about
> using threads is to not use threads at all.

Might as well get with the times and ignore that advice.

> I would point you to good
> references like Threads Considered Harmful
> (http://www.kuro5hin.org/story/2002/11/18/22112/860)

Note that it's "poster boy" for multiple processes
now uses multiple threads.

> and The Problem
> with Threads 
> (http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-1.html
> - With Link to PDF).

The author's alternatives to threads are not available
in Python. Many Pythoners do similar things with threads,
such as use the message-passing style via the queue module.

> It might seem an inappropriate response to your
> question to simply tell you that you should not do what you are asking
> how to do, but its just the case that most often anyone without
> exposure to threads has little or no understanding on just how bad
> they are for many of the tasks they will be used for. Threads are
> difficult to control, impossible to predict, and simply one of the
> most over used, least understood causes of buggy, unmaintainable
> software in the whole spectrum of development techniques.

Threads require some study and understanding, but they work
great once one learns to use them.

> As alternatives, look into what tasks can spawn into other processes,

Unfortunately one cannot share Python objects between processes.
POSH may change that, but it looks to be stuck in alpha.

> asyncronous programming (a'la Twisted -
> http://www.twistedmatrix.com/),

I find asynchronous programming much harder to manage than
threads, except for fairly simple applications where neither
one is hard.

> and co-routine and similar facilities,
> such as the tasklets of Stackless and two-way generators now included
> with Python.

Those fail at simple things such as having two of them each
waiting at a blocking call.


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


bulding python containing static extension

2006-09-22 Thread hobel
Hi,

I want to build python on a plattform without dynamic linking
containing a third party extension, is this possible?

Bulding python itself is no problem, with the proper Modules/Setup
configuration.

But does anybody know how to integrate e.g. numpy as well?
Is it possible?
Any pointers/hints?

Thanks
   Holger

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


Re: Re[2]: unicode mystery/problem

2006-09-22 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Petr Jakeš
wrote:

> I have try to experiment with the code a bit.
> the simplest code where I can demonstrate my problems:
> #!/usr/bin python
> import sys
> print "default", sys.getdefaultencoding()
> print "stdout", sys.stdout.encoding
>
> a=['P\xc5\x99\xc3\xad','Petr Jake\xc5\xa1']
> b="my nice try %s" % ''.join(a).encode("utf-8")

You have two byte strings in the list `a` and try to *encode* them as
utf-8.  That does not work.  You can make the example even a bit simpler::

 'P\xc5\x99\xc3\xadPetr Jake\xc5\xa1'.encode('utf-8')

You cant't *encode* byte strings, just *decode* them.  What happens is
that Python tries to make a unicode string from the byte string to encode
that in utf-8.  But it decodes as ASCII as that is the default.

Don't mix byte strings and unicode strings.  Put an encoding declaration
at the top of your file and convert everything to unicode on the "way in"
and to the proper encoding on the "way out" of your program.

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

Re: noob question

2006-09-22 Thread John Salerno
xandeer wrote:
> where is a good open-source project website?
> thank-you
> (sorry for being so annoying)(if I'm annoying)(if not then I'm not
> sorry)
> 
sourceforge.net
-- 
http://mail.python.org/mailman/listinfo/python-list


"Directory this source file is in (and a sibling)"

2006-09-22 Thread Sion Arrowsmith
I have a module which needs to know what directory it's in, and to
refer to files in a sibling directory, something like App/src/foo.py
wants to read App/data/conf.xml . But I have no idea in what context
foo.py is going to be run -- it could be being run as a script, it
could be being imported as a module by another script from anywhere in
the directory structure, it's even possible someone will have called
execfile on it. The following works for everything I've tried:

thisdir = os.path.dirname(os.path.normpath(__file__))
siblingdir = os.path.normpath(os.path.join(testdir, os.path.pardir, "sibling"))

However, a colleague expressed disgust at this code, but not really
being a Python programmer had no better suggestions. Is there a neater
way of getting what I want?

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Isn't bool __invert__ behaviour "strange"?

2006-09-22 Thread Saizan
Why subclassing bool from int either __invert__ or __neg__ haven't been
overrided to produce a boolean negation? I suspect backwards
compatibility or something alike, but I still wonder..

And since bool can't be subclassed, to have a type like bool but with
boolean negation what do you suggest? A wrapper maybe?


(I would use it so I can evaluate user-defined boolean expression
creating istances of his/her variables in my namespace and than eval()
his/her expression)

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


Re: Re[2]: unicode mystery/problem

2006-09-22 Thread John Machin

Petr Jakeš wrote:
> John, thanks for your extensive answer.
> >> Hi,
> >> I am using Python 2.4.3 on Fedora Core4 and  "Eric3" Python IDE
> >> .
> >> Below mentioned code works fine in the Eric3 environment. While trying
> >> to start it from the command line, it returns:
> >>
> >> Traceback (most recent call last):
> >>   File "pokus_1.py", line 5, in ?
> >> print str(a)
> >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xc1' in
> >> position 6: ordinal not in range(128)
>
> JM> So print a works, but print str(a) crashes.
>
> JM> Instead, insert this:
> JM>import sys
> JM>print "default", sys.getdefaultencoding()
> JM>print "stdout", sys.stdout.encoding
> JM> and run your script at the command line. It should print:
> JM> default ascii
> JM> stdout x
>   in the command line it prints:  *
> default ascii
> stdout UTF-8
> JM> here, and crash at the later use of str(a).
> JM> Step 2: run your script under Eric3. It will print:
> JM> default y
> JM> stdout z
>
>   in the Eric3 it prints:  
> if the # -*- Eencoding: utf_8 -*- is set than:
>
> default utf_8
> stdout
> unhandled AttributeError, "AsyncFile instance has no attribute
> 'encoding' "
>
> if the encoding is not set than it prints:
>
> DeprecationWarning: Non-ASCII character '\xc3' in file
> /root/eric/analyza_dat_TPC/pokus_1.py on line 26, but no encoding
> declared; see http://www.python.org/peps/pep-0263.html for details 
> execfile(sys.argv[0], self.debugMod.__dict__)
>
> default latin-1
> stdout
> unhandled AttributeError, "AsyncFile instance has no attribute
> 'encoding' "
>
> JM> and then should work properly. It is probable that x == y == z ==
> JM> 'utf-8'
> JM> Step 3: see below.
>
> >>
> >> == 8< =
> >> #!/usr/bin python
> >> # -*- Encoding: utf_8 -*-
>
> JM> There is no UTF8-encoded text in this short test script. Is the above
> JM> encoding comment merely a carry-over from your real script, or do you
> JM> believe it is necessary or useful in this test script?
> Generally, I am working with string like u'DISKOV\xc1 POLE' (I am
> getting it from the database)
>
> My intention to use >> # -*- Encoding: utf_8 -*- was to suppress
> DeprecationWarnings if I use utf_8 in the code (like u'DISKOV\xc1 POLE')
>
> >>
> >> a= u'DISKOV\xc1 POLE'
> >> print a
> >> print str(a)
> >> == 8< =
> >>
> >> Even it looks strange, I have to use str(a) syntax even I know the "a"
> >> variable is a string.
>
> JM> Some concepts you need to understand:
> JM> (a) "a" is not a string, it is a reference to a string.
> JM> (b) It is a reference to a unicode object (an implementation of a
> JM> conceptual Unicode string) ...
> JM> (c) which must be distinguished from a str object, which represents a
> JM> conceptual string of bytes.
> JM> (d) str(a) is trying to produce a str object from a unicode object. Not
> JM> being told what encoding to use, it uses the default encoding
> JM> (typically ascii) and naturally this will crash if there are non-ascii
> JM> characters in the unicode object.
>
> >> I am trying to use ChartDirector for Python (charts for Python) and the
> >> method "layer.addDataSet()" needs above mentioned syntax otherwise it
> >> returns an Error.
>
> JM> Care to tell us which error???
> you can see the Error description and author comments here:
> http://tinyurl.com/ezohe

You have two different episodes on that website; adding the one we have
been discussing gives *three* different stories:

Episode 1:

The error description: "TypeError: Error converting argument 1 to type
PCc" -- you should ask him "What is type PCc???" If arg 1 is an
arbitrary str object, which byte values could it possibly be objecting
to?

The author comments: "The error code usually means the filename is not
a text string, ..." (1) Input file or output file? Is it possible that
one or more bytes are not allowable in a filename? (2) Is it possible
for you to give him the exact args that you are passing in (use print
repr(arg) before the call), and for him to tell you the *exact* reason,
not the "usual" reason?

Episode 2: Evidently arg is a str object, but passing in str(arg) and
just plain arg give different results??? I doubt it. print repr(arg)
and type(arg) and see what you've actually got there.

>
> >>
> >> layer.addDataSet(data, colour, str(dataName))
> I have try to experiment with the code a bit.
> the simplest code where I can demonstrate my problems:
> #!/usr/bin python
> import sys
> print "default", sys.getdefaultencoding()
> print "stdout", sys.stdout.encoding
>
> a=['P\xc5\x99\xc3\xad','Petr Jake\xc5\xa1']
> b="my nice try %s" % ''.join(a).encode("utf-8")

So ''.join(a) is a str object, encoded in utf-8 *already*.
Please try to understand:
(1) unicode_object.encode('utf-8') produces a str_object # in utf-8
encoding
(2) str_object.decode('utf-8') produces a unicode object # if
str_object contains valid utf-8.
(3) str_object.encode('anything') is a nonsense; it is th

anybody using python 2.5 that raises error while importing?

2006-09-22 Thread daniel
there's a dll extension used to be imported with no error under version
2.4.3, but the new python complains that the name of the module can't
be found. seems not mentioned in the official documentation, any work
around to fix the issue without switching back to the old version?

tks..
daniel

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


Re: "Directory this source file is in (and a sibling)"

2006-09-22 Thread John Machin

Sion Arrowsmith wrote:
> I have a module which needs to know what directory it's in, and to
> refer to files in a sibling directory, something like App/src/foo.py
> wants to read App/data/conf.xml . But I have no idea in what context
> foo.py is going to be run -- it could be being run as a script, it
> could be being imported as a module by another script from anywhere in
> the directory structure, it's even possible someone will have called
> execfile on it. The following works for everything I've tried:
>
> thisdir = os.path.dirname(os.path.normpath(__file__))
> siblingdir = os.path.normpath(os.path.join(testdir, os.path.pardir, 
> "sibling"))
>
> However, a colleague expressed disgust at this code, but not really
> being a Python programmer had no better suggestions. Is there a neater
> way of getting what I want?

If you plan to have your code executed out of a zip or an egg, you may
have problems because __file__ is not what you want, at least with eggs
and Python 2.[34]. There was a brief thread on this topic on the
distutils SIG mailing list within the last few days.

HTH,
John

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


Re: Writing Video conference software for Windows

2006-09-22 Thread Paolo Pantaleo
2006/9/22, Paolo Pantaleo <[EMAIL PROTECTED]>:
> Thnx everybody for the precious help :)
>
> Someone said about VNC... I'll take a look, but since it is an
> exercise I need to do it, I can't just say someone else arelady did
> that :)
>
> Everything seems quite useful. I forgot two specifications:
>
> 1. Screen should be split in small squares and only the changing
> squares must be transmitted (Ok it shouldn't be too difficult)
>
> 2. The comunication must be in multicast

Twisted supports multicast ( example
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425975)

>
> I will spend some time testing the resources.
>
> PAolo
>


-- 
if you have a minute to spend please visit my photogrphy site:
http://mypic.co.nr
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: anybody using python 2.5 that raises error while importing?

2006-09-22 Thread John Machin

daniel wrote:
> there's a dll extension used to be imported with no error under version
> 2.4.3, but the new python complains that the name of the module can't
> be found. seems not mentioned in the official documentation, any work
> around to fix the issue without switching back to the old version?

Did/does its name end in .dll or in .pyd?
Have you procured a new one (necessary when there's a change of minor
version number) and installed it in the right place?
Can you tell us the name of the module, and the path to the DLL/PYD
that is/was imported by Python 2.4?
Have you contacted the author(s) of the module?
Have you installed Python 2.5 in its own directory e.g. c:\python25
(the default)? Python 2.4, same question? Have you uninstalled 2.4?

Regards,
John

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


Re: Don't use regular expressions to "validate" email addresses

2006-09-22 Thread Tim Williams
> >
> Just as a matter of interest, are you expecting that you'll find out
> about the undeliverable ones? Because in many cases nowadays you wont,
> since so many domains are filtering out "undeliverable mail" messages as
> an anti-spam defence.
>

...and then there is the problem of validating that the valid email
address belongs to the person entering it !!  If it doesn't,  any
correspondence you send to that email address will itself be spam (in
the greater modern definition of spam).

You could allow your form to accept any email address,  then send a
verification in an email  to the address given,  asking the recipient
to click a link if they did in fact fill in the form.  When they click
the link the details from the original form are then verified and can
be activated and processed.

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


Re: Python 2.5 WinXP AMD64

2006-09-22 Thread Bryan Olson
Bjoern Schliessmann wrote:
> Christophe wrote:
> 
>> To be exact, you need a 64bit Windows OS on a 64bit cpu.
> 
> Is there a reason that can be explained in a less-than-2-KB
> posting? :) I mean why Python depends on the processor type that
> much.

The 64-bit version of Python is compiled for 64-bit processors.
32-bit processors don't work the same and won't run the code.

The O.P. has a 64-bit Athlon processor, but is running a 32-bit
OS. The processor emulates its 32-bit predecessor in "legacy
mode", so 32-bit software runs.

Given a 64-bit processor, why can't 64-bit applications run
under a 32-bit Operating System? Because the O.S. provides
the environment in which the application runs. There are
several problems: system calls could be probably be thunked
by a library, but the virtual memory space is a deal breaker.
A 32-bit O.S. deals with 32-bit addresses; it can't support
the address space of a 64-bit app.

Running a 32-bit O.S., the processor stays in 32-bit legacy
mode. Enabling the processor's 64-bit mode is a privileged
operation; the application cannot do it.


Incidentally, the other direction works pretty well: a
64-bit operating system can run 32-bit applications. The
AMD64 architecture, also adopted by Intel, has a
"compatibility mode" for creating 32-bit virtual address
spaces within the native 64-bit address space.

I'm close to the 2KB.
For more, search on "AMD64 Architecture".


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


Re: Writing Video conference software for Windows

2006-09-22 Thread Ravi Teja
> Someone said about VNC... I'll take a look, but since it is an
> exercise I need to do it,

Exercises typically need you to implement, not invent (leave that for a
thesis or a dissertation). Rather than invent VNC, you could just
implement it on your own from the specs.

http://realvnc.com/docs/rfbproto.pdf

> I can't just say someone else arelady did that :)

No. But you can build upon it :-). Few construct software from the
scratch.

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


Re: CONSTRUCT - New/Old Style Classes, build-in/extension types

2006-09-22 Thread Ilias Lazaridis
Ben Finney wrote:
> "Ilias Lazaridis" <[EMAIL PROTECTED]> writes:
> 
>> Where can I find _compact_ documentation about
> 
> Can you tell us what is lacking about the documentation at
> http://www.python.org/doc/> ? Specifically, what problems have
> you found in understanding these topics from the documentation
> available at that site?

Of course:

"
Unifying types and classes in Python 2.2

Python Version: 2.2.3

Guido van Rossum

This paper is an incomplete draft. I am soliciting feedback. If you find 
any problems, please write me at [EMAIL PROTECTED]
"
http://www.python.org/download/releases/2.2.3/descrintro/

-

Weaknesses:

* draft version
* written by the system designer
* size
* code examples uncolored
* code examples missaligned

-

I've looking for a _compact_ analysis of this topic, prefered in 
standard OO jargon. Around 100 lines and 1 diagramm (or 500 lines and 3 
diagramms, but not more).

.

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


Re: send with timeout socket

2006-09-22 Thread Bryan Olson
Stéphane Ninin wrote:
> I have a few questions regarding sockets with timeouts.
> 
> Assuming you set a timeout t on a socket s and then call:
> 
> 
> 1) s.sendall
> Is the socket.timeout exception thrown when
> not the data was sent in the given time t 
> or if nothing was sent ?

Neither; not exactly anyway. It may call send() several
times, and it raises socket.timeout if any of the calls
blocks for longer than the socket's timeout.


> 2) Similar question for s.send:
> Is the socket.timeout exception thrown when 
> nothing was sent or ... ?

Raised when and only when nothing was sent.


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


Does Python provide "Struct" data structure?

2006-09-22 Thread Daniel Mark
Hello all:

I have found a useful module in IPython, named 'from IPython.ipstruct
import Struct".

So I can use it as follows:


from IPython.ipstruct import Struct

mystruct = Struct(echo = 1,
  verb = 'Verbose',
  filedir = 'C:/temp',
  )

print mystruct.filedir
#

I have two following questions:

1> Does Python provide such Struct in this standard libary.
Python has "4.3 struct -- Interpret strings as packed binary data", but
it looks like different
from what I really want to get.

2> Is it safe to use IPython's modules in my python program?
I will pack all my code into an executable application by using py2exe.
The clients would like to use this application without any python
intallation.
What should I pay attention if I include the IPython modules into my
python code and
convert it into executable application by using py2exe?

The setup.py for my application is as follows:
###
from distutils.core import setup
import py2exe

options = {
"bundle_files": 1,
# "ascii": 1, # to make a smaller executable, don't include the
encodings
"compressed": 1, # compress the library archive
}

setup(
# The first three parameters are not required, if at least a
# 'version' is given, then a versioninfo resource is built from
# them and added to the executables.
version = "1.0",
description = "mycode",
name = "mycode",

options = {"py2exe": options},
zipfile = None, # append zip-archive to the executable.

# targets to build
console=['mycode.py'],
  )
###

Does I need to make any modification if I include IPython module in my
code?

Thank you for your helps
-Daniel

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


Re: Isn't bool __invert__ behaviour "strange"?

2006-09-22 Thread Bjoern Schliessmann
Saizan wrote:

> Why subclassing bool from int either __invert__ or __neg__ haven't
> been overrided to produce a boolean negation? 

I wonder what -True or -False should evaluate to.

Regards,


Björn

-- 
BOFH excuse #297:

Too many interrupts

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


Re: Python 2.5 WinXP AMD64

2006-09-22 Thread Bjoern Schliessmann
Bryan Olson wrote:

> The O.P. has a 64-bit Athlon processor, but is running a 32-bit
> OS. The processor emulates its 32-bit predecessor in "legacy
> mode", so 32-bit software runs.

Ah, of course. Thanks for all replies! :)
 
Regards,


Björn

-- 
BOFH excuse #13:

we're waiting for [the phone company] to fix that line

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


Re: Does Python provide "Struct" data structure?

2006-09-22 Thread jay graves
Daniel Mark wrote:
> I have found a useful module in IPython, named 'from IPython.ipstruct
> import Struct".
> So I can use it as follows:
> 
> from IPython.ipstruct import Struct
>
> mystruct = Struct(echo = 1,
>   verb = 'Verbose',
>   filedir = 'C:/temp',
>   )
>
> print mystruct.filedir
> #

Does 'Bunch' fit the bill?
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308

...
jay graves

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


Re: send with timeout socket

2006-09-22 Thread Bryan Olson
Stéphane Ninin wrote:
> Yes, I typed it *really* too fast, it would be more something like this:
>
> def sendall(self, data):
> while data:
> try:
> n = self.request.send(data)
> data = data[n:]
> except socket.timeout, e:
> if self.isTerminated():
> return

And from a previous post:

   (self.isTerminated just checks is some event has been set
by another thread)

Do you want to timeout on inactivity, or do you want to timeout
if sendall() does not complete within a given time?


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


overrideredirect and Text widget

2006-09-22 Thread Sorin Schwimmer
Hi again,Last afternoon I posted a question regarding the loss of keyboard in an undecorated window. Last night I tried again, at home, and the same code worked fine. The difference: it failed under (Gentoo) Linux, it succeeded under Win 2000, both running Python 2.4.x.So, I guess, my question now is how to achieve the desired behaviour under Linux?Thanks for your advice,Sorin-- 
http://mail.python.org/mailman/listinfo/python-list

Global module variables as default parameters

2006-09-22 Thread Christoph Haas
Hi, list...

I wondered if it's possible to use global (module) variables as default 
parameters. A simple working example:


#!/usr/bin/python

globalvar = 123

def test(foo=globalvar):
  print foo

test()


Running this script prints "123". That's what I expected.

Now I'm trying the same thing in a module context. A non-working example:

test.py

#!/usr/bin/python

import TestModule

TestModule.globalvar = 123
TestModule.def1()
TestModule.def2()


TestModule.py

globalvar = 0

def def1():
  print globalvar

def def2(foo=globalvar):
  print foo


Running the test.py script prints "123" and "0". So accessing the globalvar 
in def1() works. But if I try to use the global variable as a default 
parameter in def2() it uses the default "0". What is the difference 
between these two? Are there contexts of default parameters?

Thanks for any enlightenment.

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


Anyone use PyPar (Python MPI implementation) recently?

2006-09-22 Thread [EMAIL PROTECTED]
Has anyone used PyPar ( http://datamining.anu.edu.au/~ole/pypar/ )
recently?

I _do_ want to do MPI (not BSP) but I don't need any advanced MPI
things... and PyPar seemed just up my ally... but alas it doesn't
compile:

###
[umbriel][~/download/pypar_1_9_2]> python setup.py --prefix=$MY_PREFIX
cc: unrecognized option '-showme'
/usr/lib/gcc/i386-redhat-linux/4.1.1/../../../crt1.o: In function
`_start':
(.text+0x18): undefined reference to `main'
collect2: ld returned 1 exit status
distcc[12384] ERROR: compile (null) on localhost failed
/usr/local/mpi/1.2.5/bin/mpicc: line 297: echo: write error: Broken
pipe
/usr/local/mpi/1.2.5/bin/mpicc: line 372: echo: write error: Broken
pipe
+ for arg in '"$@"'
+ '[' 0 = 1 ']'
+ case "$arg" in
+ allargs=' -c'
+ compileargs=' -c'
+ '[' 1 = 1 -a -n '' ']'
+ DoLink=0
+ HasDashC=1
+ for arg in '"$@"'
+ '[' 0 = 1 ']'
+ case "$arg" in
+ allargs=' -c /tmp/tmpP7n2tD.c'
+ '[' -s /tmp/tmpP7n2tD.c ']'
++ expr /tmp/tmpP7n2tD.c : '.*\(\..*\)'
+ ext=.c
+ '[' .c = .c ']'
+ DoCompile=1
+ compileargs=' -c /tmp/tmpP7n2tD.c'
++ basename /tmp/tmpP7n2tD.c .c
+ fname=tmpP7n2tD
+ linkobjs=' tmpP7n2tD.o'
+ for arg in '"$@"'
+ '[' 0 = 1 ']'
+ case "$arg" in
+ allargs=' -c /tmp/tmpP7n2tD.c -o'
+ '[' 1 = 1 ']'
+ compileargs=' -c /tmp/tmpP7n2tD.c -o'
+ for arg in '"$@"'
+ '[' 0 = 1 ']'
+ case "$arg" in
+ allargs=' -c /tmp/tmpP7n2tD.c -o /tmp/tmpP7n2tD.o'
+ '[' -s /tmp/tmpP7n2tD.o ']'
++ expr /tmp/tmpP7n2tD.o : '.*\(\..*\)'
+ ext=.o
+ '[' .o = .c ']'
+ '[' .o = .s ']'
+ '[' .o = .o ']'
+ '[' 1 = 1 ']'
+ compileargs=' -c /tmp/tmpP7n2tD.c -o /tmp/tmpP7n2tD.o'
+ status=0
+ '[' 1 = 1 -o 0 = 1 ']'
+ '[' 1 '!=' 1 ']'
+ eval cc -DUSE_STDARG -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1
-DHAVE_UNISTD_H=1 -DHAVE_STDARG_H=1 -DUSE_STDARG=1 -DMALLOC_RET_VOID=1
-c /tmp/tmpP7n2tD.c -o /tmp/tmpP7n2tD.o -I/usr/local/mpi/1.2.5/include
++ cc -DUSE_STDARG -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1
-DHAVE_UNISTD_H=1 -DHAVE_STDARG_H=1 -DUSE_STDARG=1 -DMALLOC_RET_VOID=1
-c /tmp/tmpP7n2tD.c -o /tmp/tmpP7n2tD.o -I/usr/local/mpi/1.2.5/include
+ status=0
+ '[' 0 '!=' 0 ']'
+ '[' 0 = 1 -o 0 = 1 ']'
+ exit 0
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help

error: option --prefix not recognized
##

This is on Fedora Core5.  I know that MPI and such are setup fine... as
I use them daily in a C++ code.

Thanks for any help!

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


Re: CONSTRUCT - New/Old Style Classes, build-in/extension types

2006-09-22 Thread Ilias Lazaridis
Fredrik Lundh wrote:
> Ilias Lazaridis wrote:
> 
>> note: I am aware about search engines.
> 
> but you're incapable of using them, or ?

-

>> I ask for documentation which other developers have found useful
> 
> most recent Python books contains good discussions of the things you're
> asking for.  maybe you should buy a book ?

I'm interested in online resources, experiences etc..

Maybe you can clarify some things (for me and for readers):

Do I need old style classes?

Does the python standard library use old style classes?

Have those old style classes any benefits?

.

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


I need some help with a regexp please

2006-09-22 Thread Sorin Schwimmer
Hi,My $0.02:re.compile('^\w+([\.-]?\w+)[EMAIL PROTECTED]([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|intl|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$')I picked it up from the Net, and while it may be not perfect (you've got lots of reply's telling you why),it's good enough for me.Good luck,Sorin-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Global module variables as default parameters

2006-09-22 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Christoph Haas
wrote:

> TestModule.py
> 
> globalvar = 0
> 
> def def1():
>   print globalvar
> 
> def def2(foo=globalvar):
>   print foo
> 
> 
> Running the test.py script prints "123" and "0". So accessing the globalvar 
> in def1() works. But if I try to use the global variable as a default 
> parameter in def2() it uses the default "0". What is the difference 
> between these two? Are there contexts of default parameters?

Default parameters are evaluated *once* when the ``def`` is executed.  So
in `def2` the value of `foo` won't be looked up when calling the function
as it is already bound to the value 0.

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


Re: Isn't bool __invert__ behaviour "strange"?

2006-09-22 Thread Saizan

Bjoern Schliessmann wrote:
> Saizan wrote:
>
> > Why subclassing bool from int either __invert__ or __neg__ haven't
> > been overrided to produce a boolean negation?
>
> I wonder what -True or -False should evaluate to.
>
> Regards,
>
>
> Björn
>
> --
> BOFH excuse #297:
>
> Too many interrupts
Well in boolean notation -True == False and  -False == True, actually
you may prefer ¬ or a line over the term, but since there's no such
operator in python I think we should use "-" which is also the operator
used by Bool himself in his formulation for negation which was 1-x.
Now that I think of it 1-x should work as a negation in Python, too,
since True == 1 and False == 0, but it would be a little annoying to
write expressions in this way.

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


Re: Global module variables as default parameters

2006-09-22 Thread Peter Otten
Christoph Haas wrote:

> Hi, list...
> 
> I wondered if it's possible to use global (module) variables as default
> parameters. A simple working example:
> 
> 
> #!/usr/bin/python
> 
> globalvar = 123
> 
> def test(foo=globalvar):
>   print foo
> 
> test()
> 
> 
> Running this script prints "123". That's what I expected.
> 
> Now I'm trying the same thing in a module context. A non-working example:
> 
> test.py
> 
> #!/usr/bin/python
> 
> import TestModule
> 
> TestModule.globalvar = 123
> TestModule.def1()
> TestModule.def2()
> 
> 
> TestModule.py
> 
> globalvar = 0
> 
> def def1():
>   print globalvar
> 
> def def2(foo=globalvar):
>   print foo
> 
> 
> Running the test.py script prints "123" and "0". So accessing the
> globalvar in def1() works. But if I try to use the global variable as a
> default parameter in def2() it uses the default "0". What is the
> difference between these two? Are there contexts of default parameters?

Yes, and that context is the function definition which is executable code,
too. Whatever the variable 'right' in a statement like

def f(left=right): ...

is bound to when the def is executed will become the default for the 'left'
argument. This should become clear when you create more than one function
with the same

>>> fs = []
>>> for i in range(3):
... def f(i=i): print i
... fs.append(f)
...
>>> for f in fs: f()
...
0
1
2

Use a sentinel when you don't want that behaviour:

def f(foo=None):
if foo is None: foo = globalvar
# ...

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


Re: Isn't bool __invert__ behaviour "strange"?

2006-09-22 Thread John Roth

Saizan wrote:
> Why subclassing bool from int either __invert__ or __neg__ haven't been
> overrided to produce a boolean negation? I suspect backwards
> compatibility or something alike, but I still wonder..
>
> And since bool can't be subclassed, to have a type like bool but with
> boolean negation what do you suggest? A wrapper maybe?
>
>
> (I would use it so I can evaluate user-defined boolean expression
> creating istances of his/her variables in my namespace and than eval()
> his/her expression)

The not operator and the bool() builtin produce
boolean results. Since bool is a subclass of int,
all the integer operations will remain integer
operations. This was done for backwards
compatability, and is unlikely to change in the 2.x
series.

I don't remember if this is supposed to change
in 3.0. See PEP 3100 and 3099.

John Roth

John Roth

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


Re: Anyone use PyPar (Python MPI implementation) recently?

2006-09-22 Thread [EMAIL PROTECTED]
Nevermind... I'm an idiot... just didn't specify the right options...

python setup.py  install --prefix=$MY_PREFIX

Works just fine... sigh.

Friedmud

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


XML parser that sorts elements?

2006-09-22 Thread jmike
Hi everyone,

I am a total newbie to XML parsing.  I've written a couple of toy
examples under the instruction of tutorials available on the web.

The problem I want to solve is this.  I have an XML snippet (in a
string) that looks like this:


  hello
  goodbye


and I want to alphabetize not only the attributes of an element, but I
also want to alphabetize the elements in the same scope:


  goodbye
  hello


I've found a "Canonizer" class, that subclasses saxlib.HandlerBase, and
played around with it and vaguely understand what it's doing.  But what
I get out of it is


  hello
  goodbye


in other words it sorts the attributes of each element, but doesn't
touch the order of the elements.

How can I sort the elements?  I think I want to subclass the parser, to
present the elements to the content handler in different order, but I
couldn't immediately find any examples of the parser being subclassed.

Thanks for any pointers!
  --JMike

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


Re: CONSTRUCT - New/Old Style Classes, build-in/extension types

2006-09-22 Thread Steve Holden
Ilias Lazaridis wrote:
> Fredrik Lundh wrote:
> 
>>Ilias Lazaridis wrote:
>>
>>
>>>note: I am aware about search engines.
>>
>>but you're incapable of using them, or ?
> 
> 
> -
> 
> 
>>>I ask for documentation which other developers have found useful
>>
>>most recent Python books contains good discussions of the things you're
>>asking for.  maybe you should buy a book ?
> 
> 
> I'm interested in online resources, experiences etc..
> 
> Maybe you can clarify some things (for me and for readers):
> 
> Do I need old style classes?
> 
No, not for new code.

> Does the python standard library use old style classes?
> 
Yes, because it was easier to leave them as they were than risk 
introducing incompatibilities.

> Have those old style classes any benefits?
> 
> ..
> 
No.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Isn't bool __invert__ behaviour "strange"?

2006-09-22 Thread Carsten Haese
On Fri, 2006-09-22 at 11:25, Saizan wrote:
> Bjoern Schliessmann wrote:
> > Saizan wrote:
> >
> > > Why subclassing bool from int either __invert__ or __neg__ haven't
> > > been overrided to produce a boolean negation?
> >
> > I wonder what -True or -False should evaluate to.
> Well in boolean notation -True == False and  -False == True, actually
> you may prefer ¬ or a line over the term, but since there's no such
> operator in python [...]

It's called "not":

>>> not True
False
>>> not False
True

-Carsten


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


Re: XML parser that sorts elements?

2006-09-22 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> Hi everyone,
> 
> I am a total newbie to XML parsing.  I've written a couple of toy
> examples under the instruction of tutorials available on the web.
> 
> The problem I want to solve is this.  I have an XML snippet (in a
> string) that looks like this:
> 
> 
>   hello
>   goodbye
> 
> 
> and I want to alphabetize not only the attributes of an element, but I
> also want to alphabetize the elements in the same scope:
> 
> 
>   goodbye
>   hello
> 
> 
> I've found a "Canonizer" class, that subclasses saxlib.HandlerBase, and
> played around with it and vaguely understand what it's doing.  But what
> I get out of it is
> 
> 
>   hello
>   goodbye
> 
> 
> in other words it sorts the attributes of each element, but doesn't
> touch the order of the elements.
> 
> How can I sort the elements?  I think I want to subclass the parser, to
> present the elements to the content handler in different order, but I
> couldn't immediately find any examples of the parser being subclassed.

You can sort them by obtaining them as tree of nodes, e.g. using element
tree or minidom.

But you should be aware that this will change the structure of your document
and it isn't always desirable to do so - e.g. html pages would look funny
to say the least if sorted in that way.

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


Re: Does Python provide "Struct" data structure?

2006-09-22 Thread Bjoern Schliessmann
Daniel Mark wrote:

> I have two following questions:
> 
> 1> Does Python provide such Struct in this standard libary.
> Python has "4.3 struct -- Interpret strings as packed binary
> data", but it looks like different from what I really want to get.

Yes, that module is used when you want to deal with C structs in
binary form (e.g. useful at networking with binary protocols).
 
Try using dictionaries or custom, field-only class instances
as "struct".

Regards,


Björn

-- 
BOFH excuse #374:

It's the InterNIC's fault.

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


Re: CONSTRUCT - New/Old Style Classes, build-in/extension types

2006-09-22 Thread Paul Boddie
Ilias Lazaridis wrote:
> Fredrik Lundh wrote:
> > Ilias Lazaridis wrote:
> >
> >> note: I am aware about search engines.
> >
> > but you're incapable of using them, or ?

Well, "Python new-style old-style classes" in Google gives a range of
discussions, but an old version of the definitive guide [1] is found
via one of the later results on the first page (which is some section
of the reference manual). According to that and the newer guide [2],
the official documentation still isn't updated, despite it having been
a good three years since new-style classes first arrived in a real
Python release.

Of course, the lengthening paper trail shouldn't be a surprise to you
or I, but with more "exciting" additions to the language in 2.5, it is
somewhat unnerving that the last major changes still sit partially
documented in "additional documentation" that a beginner wouldn't be
inclined to read through.

> >> I ask for documentation which other developers have found useful
> >
> > most recent Python books contains good discussions of the things you're
> > asking for.  maybe you should buy a book ?
>
> I'm interested in online resources, experiences etc..

And I don't see what's wrong with that.

> Maybe you can clarify some things (for me and for readers):
>
> Do I need old style classes?

No, but you can still use them. I use them a lot.

> Does the python standard library use old style classes?

Yes, I'd imagine, since it would otherwise have needed someone to go
through the library and change everything, and I doubt that anyone is
that interested to do so.

> Have those old style classes any benefits?

That you don't have to write the bizarre conceptual accident that is
"(object)" when declaring a "top-level" class?

Paul

[1] http://www.python.org/doc/newstyle.html
[2] http://www.python.org/doc/newstyle/

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


Re: what is the best practice to separate Pygtk and long running thread code

2006-09-22 Thread seb
Hi Thomas,

I am running WinXP so that casting processes and getting their results
is not so convenient.

I have tested idle add and it does the job : the thread is running
whenever there is no activity on the gui.
I still do not understand how it can be so responsive 'cause the thread
I am using at the moment do not have any time.sleep(ing).

I am afraid I have still to use an intermediate class between the
computing thread and the gui to send data between the two of them but
now about all the computing time is devoided to the thread.

Thanks a lot !!!

Seb.

ps : the only mod that I have done to the gui.py in the init is

 def __init__(self, path='gui.glade',
 root='window1',
 domain=app_name, kwargs={}):
path = os.path.join(glade_dir, path)
SimpleGladeApp.__init__(self, path, root, domain, **kwargs)
self.q=Queue.Queue()
self.action=act.action(self.q)
gobject.idle_add(self.action.go)
#gobject.timeout_add (1000,self.action.go)
gobject.timeout_add (1000,self.process)



Thomas Guettler wrote:
> seb wrote:
>
> > Hi,
> >
> > I am using pygtk for the first times.
> >
> > I am wondering what would be the best "pattern" to interface pygtk with
> > a thread.
> >
> > The thread is collecting informations (over the network for example) or
> > is doing some long calculations.
>
> Hi,
>
> I would use several *processes*. If your scripts runs on Unix/Linux
> you can use select() on the filedescriptors of the processes you created
> with popen. On Windows you need to poll them, but maybe this is
> better than threads, too. With idle_add you can get data from
> the subproceses. It gets called if there are no actions in the
> event-loop.
>
> HTH,
>  Thomas
>
> --
> Thomas Güttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/
> E-Mail: guettli (*) thomas-guettler + de
> Spam Catcher: [EMAIL PROTECTED]

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


Re: Isn't bool __invert__ behaviour "strange"?

2006-09-22 Thread Bjoern Schliessmann
Saizan wrote:

> Well in boolean notation -True == False and  -False == True,
> actually you may prefer ¬ or a line over the term,

(I can't remember reading "-" (minus) for a standard boolean
negation operator anywhere. Even C/C++ uses "!".)

> but since there's no such operator in python I think we should
> use "-" 

Stop! What about the "not" operator? It's Python's operator for
negation.

> which is also the operator used by Bool himself in his formulation
> for negation which was 1-x. 

Boole's original formulation uses some weird mathematical things to
emulate "not", "and" and "or". Focus lies on "mathematical" here.

> Now that I think of it 1-x should work as a negation in Python,
> too, since True == 1 and False == 0, but it would be a little
> annoying to write expressions in this way. 

And "a little" unreadable ;)

Regards,


Björn

-- 
BOFH excuse #445:

Browser's cookie is corrupted -- someone's been nibbling on it.

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


Re: Python programs always open source?

2006-09-22 Thread Magnus Lycka
Ben Finney wrote:
> Leif K-Brooks <[EMAIL PROTECTED]> writes:
> 
 Ben Finney wrote:
> So long as you're not distributing some or all of Python itself,
> or a derivative work, the license for Python has no legal effect
> on what license you choose for your own work.
> 
>> I was replying to Ben Finney's claim that in a hypothetical world
>> where Python was licensed under the GPL, there would still be no
>> restriction on distributing Python programs under a closed-source
>> license.
> 
> My claim (and IANAL) is that it doesn't matter *what* license Python
> is distributed under; unless you do something with Python that is a
> right of the copyright holder, such as distributing part or all of
> Python, the copyright license terms of Python have no legal effect on
> what license you choose for your own work.

As I read the GPL, you should be ok if you don't copy, distribute or
modify Python (if Python was GPL). Those are the activities covered
by the GPL license. Using py2exe to make a binary with both Python
and your own code would be a different matter. Even distributing a CD
with a GPL Python and your python modules would be a problem, since
you would be distributing GPL software with non-GPL software which will
be combined into a program as you run it.

If you just distribute your .py files, it probably doesn't matter if
someone else will run the unholy combination of GPL Python and
nongpl.py. I don't think a judge would consider executing
"gplpython nonglp.py" being copying, distribution or modification.

On the other hand, I think your "doesn't matter *what* license
Python is distributed under"-claim holds. If we are allowed to think
up other evil licenses, they could make claims on all files ever used
with their evil software, and I doubt that you could develop non-
trivial software without ever invoking it.

Still, the important thing is that Python uses a license which is
convenient for both proprietary software development and open source.
-- 
http://mail.python.org/mailman/listinfo/python-list


Question about the article "py2exe compiler" in Python Cookbook by Alexander Semenov

2006-09-22 Thread Daniel Mark
Hello all:

I follow the following tutorial

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/108598
Description:
script for making executables with py2exe
##
from distutils.core import setup
import sys, os, py2exe

name = sys.argv[1]
sys.argv[1] = 'py2exe'
sys.path.append(os.path.dirname(os.path.abspath(name)))

setup(name=name[:-3], scripts=[name])
##

However, I can not get the expected results.

1> save the above script as file makexe.py under the folder
C:\Program Files\Python24\Tools\Scripts

2> add this path to system path

3> C:\> makexe.py myscript.py

What I got from the "dist" folder are as follows:
C:\dist\unicodedata.pyd
C:\dist\w9xpopen.exe
C:\dist\zlib.pyd
C:\dist\bz2.pyd
C:\dist\library.zip
C:\dist\MSVCR71.dll
C:\dist\python24.dll

Suppose I should get an executable file under this folder.

What should I do to solve this problem?


Thank you
-Daniel

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


Re: XML parser that sorts elements?

2006-09-22 Thread jmike

Diez B. Roggisch wrote:

> You can sort them by obtaining them as tree of nodes, e.g. using element
> tree or minidom.
>
> But you should be aware that this will change the structure of your document
> and it isn't always desirable to do so - e.g. html pages would look funny
> to say the least if sorted in that way.
>
> Diez

In this particular case, I need to sort the elements, and the specific
application I'm testing guarantees that the order of the elements "in
the same scope" (this may not be the right term in XML semantics, but
it's what I know how to say) does not matter.  That probably means that
the specific application I'm testing is not using XML in a standard
way, but so be it.

I'm looking at minidom now and I think maybe there's enough
documentation there that I can get a handle on it and do what I need to
do.  Thanks.  (But if anyone else has a specific example I can crib
from, that'd be great.)

--JMike

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


Re: XML parser that sorts elements?

2006-09-22 Thread Paul McGuire
<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi everyone,
>
> I am a total newbie to XML parsing.  I've written a couple of toy
> examples under the instruction of tutorials available on the web.
>
> The problem I want to solve is this.  I have an XML snippet (in a
> string) that looks like this:
>
> 
>  hello
>  goodbye
> 
>
> and I want to alphabetize not only the attributes of an element, but I
> also want to alphabetize the elements in the same scope:
>
> 
>  goodbye
>  hello
> 
>
> I've found a "Canonizer" class, that subclasses saxlib.HandlerBase, and
> played around with it and vaguely understand what it's doing.  But what
> I get out of it is
>
> 
>  hello
>  goodbye
> 
>
> in other words it sorts the attributes of each element, but doesn't
> touch the order of the elements.
>
> How can I sort the elements?  I think I want to subclass the parser, to
> present the elements to the content handler in different order, but I
> couldn't immediately find any examples of the parser being subclassed.
>

I suspect that Canonizer doesn't sort nested elements because some schemas 
require elements to be in a particular order, and not necessarily an 
alphabetical one.

Here is a snippet from an interactive Python session, working with the 
"batteries included" xml.dom.minidom.  The solution is not necessarily in 
the parser, it may be instead in what you do with the parsed document 
object.

This is not a solution to your actual problem, but I hope it gives you 
enough to work with to find your own solution.

HTH,
-- Paul


>>> xmlsrc = """
...   hello
...   goodbye
... 
... """
>>> import xml.dom.minidom
>>> doc = xml.dom.minidom.parseString(xmlsrc)
>>> doc.childNodes
[]
>>> print doc.toprettyxml()





hello




goodbye





>>> [n.nodeName for n in doc.childNodes]
[u'booga']
>>> [n.nodeName for n in doc.childNodes[0].childNodes]
['#text', u'well', '#text', u'blah', '#text']
>>> [n.nodeName for n in doc.childNodes[0].childNodes if n.nodeType == 
>>> doc.ELEMENT_NODE]
[u'well', u'blah']
>>> doc.childNodes[0].childNodes = 
>>> sorted(doc.childNodes[0].childNodes,key=lambda n:n.nodeName)
>>> print doc.toprettyxml()









goodbye


hello



>>> doc.childNodes[0].childNodes = sorted([n for n in 
>>> doc.childNodes[0].childNodes if n.nodeType == 
>>> doc.ELEMENT_NODE],key=lambda n:n.nodeName)
>>> print doc.toprettyxml()



goodbye


hello



>>> 


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


Re: XML parser that sorts elements?

2006-09-22 Thread jmike

Paul McGuire wrote:

...
> Here is a snippet from an interactive Python session, working with the
> "batteries included" xml.dom.minidom.  The solution is not necessarily in
> the parser, it may be instead in what you do with the parsed document
> object.
>
> This is not a solution to your actual problem, but I hope it gives you
> enough to work with to find your own solution.
>
> HTH,
> -- Paul

Whoa.  Outstanding.  Excellent.  Thank you!
  --JMike

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


Re: Isn't bool __invert__ behaviour "strange"?

2006-09-22 Thread Saizan

John Roth wrote:

> The not operator and the bool() builtin produce
> boolean results. Since bool is a subclass of int,
> all the integer operations will remain integer
> operations. This was done for backwards
> compatability, and is unlikely to change in the 2.x
> series.

Ok, shame on me, I completely overlooked "not" and it surprises myself
because it's not like I haven't used it, I just didn't see "not" as an
operator, maybe because i can't find a __not__ method in bool class.
(Is it hidden somewhere or is computed in some other way?)

(However (not x) whould be as annoying as 1-x even if a little more
readable (if you consider lispish parentheses readable):
Input expression: (not (not x)&(not y)!(not (z|v)))
Maybe direct eval is just the wrong way of doing this, I should look
for or make muParser bindings for Python instead..)

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


Re: XML parser that sorts elements?

2006-09-22 Thread Paul McGuire
"Paul McGuire" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]

>
This is what I posted, but it's not what I typed.  I entered some very long 
lines at the console, and the newsgroup software, when wrapping the text, 
prefixed it with '>>>', not '...'.  So this looks like something that wont 
run.
 doc.childNodes[0].childNodes = sorted([n for n in 
 doc.childNodes[0].childNodes if n.nodeType == 
 doc.ELEMENT_NODE],key=lambda n:n.nodeName)
 print doc.toprettyxml()
> 
> 
>
>goodbye
>
>
>hello
>
> 
>


Here's the console session, with '...' continuation lines:

>>> xmlsrc = """
...   hello
...   goodbye
... 
... """
>>> import xml.dom.minidom
>>> doc = xml.dom.minidom.parseString(xmlsrc)
>>> print doc.toprettyxml()





hello




goodbye





>>> [n.nodeName for n in doc.childNodes]
[u'booga']
>>> [n.nodeName for n in doc.childNodes[0].childNodes]
['#text', u'well', '#text', u'blah', '#text']
>>> [n.nodeName for n in doc.childNodes[0].childNodes
...if n.nodeType == doc.ELEMENT_NODE]
[u'well', u'blah']
>>> doc.childNodes[0].childNodes = sorted(
...   doc.childNodes[0].childNodes,key=lambda n:n.nodeName)
>>> [n.nodeName for n in doc.childNodes[0].childNodes
...if n.nodeType == doc.ELEMENT_NODE]
[u'blah', u'well']
>>> print doc.toprettyxml()









goodbye


hello



>>> doc.childNodes[0].childNodes = sorted(
...   [n for n in doc.childNodes[0].childNodes
... if n.nodeType==doc.ELEMENT_NODE],
...   key=lambda n:n.nodeName)
>>> print doc.toprettyxml()



goodbye


hello



>>>



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


Re: Python programs always open source?

2006-09-22 Thread Steve Holden
Magnus Lycka wrote:
> Ben Finney wrote:
> 
>>Leif K-Brooks <[EMAIL PROTECTED]> writes:
>>
>>
>Ben Finney wrote:
>
>>So long as you're not distributing some or all of Python itself,
>>or a derivative work, the license for Python has no legal effect
>>on what license you choose for your own work.
>>
>>>I was replying to Ben Finney's claim that in a hypothetical world
>>>where Python was licensed under the GPL, there would still be no
>>>restriction on distributing Python programs under a closed-source
>>>license.
>>
>>My claim (and IANAL) is that it doesn't matter *what* license Python
>>is distributed under; unless you do something with Python that is a
>>right of the copyright holder, such as distributing part or all of
>>Python, the copyright license terms of Python have no legal effect on
>>what license you choose for your own work.
> 
> 
> As I read the GPL, you should be ok if you don't copy, distribute or
> modify Python (if Python was GPL). 

Since Python *isn't* GPL, can we please move this discussion to 
universe.hypothetical.discuss?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Isn't bool __invert__ behaviour "strange"?

2006-09-22 Thread Bjoern Schliessmann
Saizan wrote:

> (However (not x) whould be as annoying as 1-x even if a little
> more readable (if you consider lispish parentheses readable):
> Input expression: (not (not x)&(not y)!(not (z|v)))

Did you notice that you use bitwise AND and OR here? How about

not (not x) and (not y) or (not (z or v))

(or what is "!" supposed to mean?)

BTW, not's binding is stronger than and's (IIRC). So 

not (not x) and (not y)

mutates to

x and (not y)

Regards,


Björn

-- 
BOFH excuse #392:

It's union rules. There's nothing we can do about it. Sorry.

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


Re: CONSTRUCT - New/Old Style Classes, build-in/extension types

2006-09-22 Thread Steve Holden
Paul Boddie wrote:
> Ilias Lazaridis wrote:
[...]
>>Have those old style classes any benefits?
> 
> 
> That you don't have to write the bizarre conceptual accident that is
> "(object)" when declaring a "top-level" class?
> 
Though of course the easiest way to enforce your classes to new style is 
to begin each module with

__metaclass__ = type

  >>> __metaclass__ = type
  >>> class X: pass
  ...
  >>> X

  >>> X()
<__main__.X object at 0x186c6f0c>
  >>> x = X()
  >>> isinstance(x, object)
True
  >>> type(x), type(X)
(, )
  >>>

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Question about the article "py2exe compiler" in Python Cookbook by Alexander Semenov

2006-09-22 Thread Thomas Heller
Daniel Mark schrieb:
> Hello all:
> 
> I follow the following tutorial
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/108598
> Description:
> script for making executables with py2exe
> ##
> from distutils.core import setup
> import sys, os, py2exe
> 
> name = sys.argv[1]
> sys.argv[1] = 'py2exe'
> sys.path.append(os.path.dirname(os.path.abspath(name)))
> 
> setup(name=name[:-3], scripts=[name])
> ##
> 
> However, I can not get the expected results.

Someone should correct this recipe.  In newer py2exe-versions,
you have to use 'console=[name]' in the above script.

Thomas

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


+1 QOTW

2006-09-22 Thread olsongt
Did anyone else crack up when Larry Wall described python with the
statement:

Python, as the "anti-Perl," is heavily invested in maintaining Order.

In the state of the onion address?

http://www.perl.com/pub/a/2006/09/21/onion.html

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


Re: Isn't bool __invert__ behaviour "strange"?

2006-09-22 Thread Paul McGuire
"Saizan" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> John Roth wrote:
>
>> The not operator and the bool() builtin produce
>> boolean results. Since bool is a subclass of int,
>> all the integer operations will remain integer
>> operations. This was done for backwards
>> compatability, and is unlikely to change in the 2.x
>> series.
>
> Ok, shame on me, I completely overlooked "not" and it surprises myself
> because it's not like I haven't used it, I just didn't see "not" as an
> operator, maybe because i can't find a __not__ method in bool class.
> (Is it hidden somewhere or is computed in some other way?)
>
> (However (not x) whould be as annoying as 1-x even if a little more
> readable (if you consider lispish parentheses readable):
> Input expression: (not (not x)&(not y)!(not (z|v)))
> Maybe direct eval is just the wrong way of doing this, I should look
> for or make muParser bindings for Python instead..)
>
What about __nonzero__?

class IsOdd(object):
def __init__(self,n):
self.val = n

def __nonzero__(self):
return self.val % 2

for i in range(4):
if IsOdd(i):
print i,"is odd"
else:
print i,"is even"

Prints:
0 is even
1 is odd
2 is even
3 is odd


-- Paul


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


Re: Isn't bool __invert__ behaviour "strange"?

2006-09-22 Thread Saizan
Thanks for pointing that out ( the "!" is a misstyped "|"), my classes
of discrete math have warped my mind with a mix of various non-C-style
operators notation, I never use bitwise operation and this is just a
bad day for thinking about things..
However I figured out one thing, Python's logic notation is readable
and complete but not  compact. (which is fine for programming, and
that's the aim, isn't it?)

Bjoern Schliessmann wrote:
> Saizan wrote:
>
> > (However (not x) whould be as annoying as 1-x even if a little
> > more readable (if you consider lispish parentheses readable):
> > Input expression: (not (not x)&(not y)!(not (z|v)))
>
> Did you notice that you use bitwise AND and OR here? How about
>
> not (not x) and (not y) or (not (z or v))
>
> (or what is "!" supposed to mean?)
>
> BTW, not's binding is stronger than and's (IIRC). So
>
> not (not x) and (not y)
>
> mutates to
>
> x and (not y)
>
> Regards,
>
>
> Björn
>
> --
> BOFH excuse #392:
> 
> It's union rules. There's nothing we can do about it. Sorry.

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


Why are the topic and keyword documentation not includded in the chm?

2006-09-22 Thread Brendan
1)Why are the  topic and keyword documentation not included in the
Windows installation chm? I have to have both the html(with the env var
PYTHONDOCS set) and the chm installed? What is the point of that?

2)Is there no simple way to open the chm docs in a browser from within
python?

3)How do I open the online pydoc browser from within python? (Sure I
can open it using the start menu shortcut or from the OS command prompt
with: python C:\python25\lib\pydoc.py -w, but why would I not want to
be able to open it from the python command prompt?)

Why are these issues not made clear somewhere in plain view such as
Getting Started or in the installation notes?

Thanks

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


Re: noob question

2006-09-22 Thread Jay
http://code.google.com/hosting/

xandeer wrote:
> where is a good open-source project website?
> thank-you
> (sorry for being so annoying)(if I'm annoying)(if not then I'm not
> sorry)

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


py2exe compression not working with Python 2.5

2006-09-22 Thread nikie
When I try to compress the output of py2exe like this:

  from distutils.core import setup
  import py2exe

  setup(console=['hello.py'], options={"py2exe": {"compressed": 1}})

I get strange error messages:

Adding zlib.pyd to C:\tests\CanControllerTest\New Folder
(2)\dist\library.zip
Traceback (most recent call last):
  File "setup.py", line 4, in 
setup(console=['hello.py'], options={"py2exe": {"compressed": 1}})
  File "C:\Python25\lib\distutils\core.py", line 151, in setup
dist.run_commands()
  File "C:\Python25\lib\distutils\dist.py", line 974, in run_commands
self.run_command(cmd)
  File "C:\Python25\lib\distutils\dist.py", line 994, in run_command
cmd_obj.run()
  File "C:\Python25\lib\site-packages\py2exe\build_exe.py", line 218,
in run
self._run()
  File "C:\Python25\lib\site-packages\py2exe\build_exe.py", line 285,
in _run
self.create_binaries(py_files, extensions, dlls)
  File "C:\Python25\lib\site-packages\py2exe\build_exe.py", line 591,
in create_
binaries
bytes = zlib_file.read()
AttributeError: 'NoneType' object has no attribute 'read'

This is a standard Python 2.5 installation. Doing the same thing with
2.4 works like a charm.

Did I miss anything?

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


Replacing line in a text file

2006-09-22 Thread CSUIDL PROGRAMMEr
Folks
I am trying to read a file
This file has a line containing string  'disable = yes'

I want to change this line to 'disable = no'

The concern here is that , i plan to take into account the white spaces
also.

I tried copying all file int list and then tried to manipulate that
list

But the search is not working

Any answer

thanks

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


Re: Replacing line in a text file

2006-09-22 Thread Neil Cerutti
On 2006-09-22, CSUIDL PROGRAMMEr <[EMAIL PROTECTED]> wrote:
> Folks
> I am trying to read a file
> This file has a line containing string  'disable = yes'
>
> I want to change this line to 'disable = no'
>
> The concern here is that , i plan to take into account the white spaces
> also.
>
> I tried copying all file int list and then tried to manipulate that
> list
>
> But the search is not working
>
> Any answer

More code, less talk.

Seriously, posting your code and any error messages or unexpected
results you're getting would be helpful. That is, until such time
as Guido finalizes PyESP.

import PyESP
e = ESP.mindread(CSUIDL, "r")
# etc..

-- 
Neil Cerutti
Life is indeed precious, and I believe the death penalty helps
affirm this fact. --Edward Koch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Building things with setup.py

2006-09-22 Thread Robert Kern
James Stroud wrote:
> Robert Kern wrote:
>> James Stroud wrote:

>>> The build process, by the way, required my copying libpython2.5.a to 
>>> $HOME/Programs/lib.
>> Hmm. That doesn't quite sound right, but it's been a while since I 
>> compiled the interpreter from source.
> 
> Sorry. To clarify, making libpython2.5a available in a $LD_LIBRARY_PATH 
> was necessary to build numpy and scipy.

I don't see how that could have affected anything. Static libraries aren't 
looked up in $LD_LIBRARY_PATH. Certainly not for build-time linking.

> I'm not sure if this is relevant to what you see in the check, but I 
> installed scipy_distutils AFTER installing scipy.

scipy_distutils is no longer used. All of its functionality has been folded 
into 
numpy.

What do your environment variables look like when you build?

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

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


Re: Replacing line in a text file

2006-09-22 Thread Tim Chase
> I am trying to read a file
> This file has a line containing string  'disable = yes'
> 
> I want to change this line to 'disable = no'

Sounds like

sed -i 's/disable *= *yes/disable = no/' file.txt

would do what you want.  It doesn't catch word boundaries, so if 
you have something like "foodisable = yes", it will replace this 
too.  Additionally, it only expects spaces around the equal-sign, 
so if you have tabs, you'd have to modify accordingly.

If it must be done in python,

import re
r = re.compile(r"(\bdisable\s*=\s*)yes\b")
outfile = file('out.txt', 'w')
for line in file('in.txt'):
outfile.write(r.sub(r'\1no', line))

Add the re.IGNORECASE option if so desired.  This doesn't have 
the cautions listed above for the sed version.  Wreckless code!

> The concern here is that , i plan to take into account the white spaces
> also.

I'm not sure what you intend by this.  Do you want to disregard 
whitespace?  Do you want to keep leading indentation?

The above python should *just* replace "yes" with "no" in the 
above context, not touching space or anything of the like.

-tkc






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


Re: +1 QOTW

2006-09-22 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Did anyone else crack up when Larry Wall described python with the
> statement:
>
> Python, as the "anti-Perl," is heavily invested in maintaining Order.
>
> In the state of the onion address?
>
> http://www.perl.com/pub/a/2006/09/21/onion.html

There is also this:
'But I think the basic Perl paradigm is "Whatever-oriented programming."'





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


Re: py2exe compression not working with Python 2.5

2006-09-22 Thread Thomas Heller
nikie schrieb:
> When I try to compress the output of py2exe like this:
> 
>   from distutils.core import setup
>   import py2exe
> 
>   setup(console=['hello.py'], options={"py2exe": {"compressed": 1}})
> 
> I get strange error messages:
> 
> Adding zlib.pyd to C:\tests\CanControllerTest\New Folder
> (2)\dist\library.zip
> Traceback (most recent call last):
>   File "setup.py", line 4, in 
> setup(console=['hello.py'], options={"py2exe": {"compressed": 1}})
>   File "C:\Python25\lib\distutils\core.py", line 151, in setup
> dist.run_commands()
>   File "C:\Python25\lib\distutils\dist.py", line 974, in run_commands
> self.run_command(cmd)
>   File "C:\Python25\lib\distutils\dist.py", line 994, in run_command
> cmd_obj.run()
>   File "C:\Python25\lib\site-packages\py2exe\build_exe.py", line 218,
> in run
> self._run()
>   File "C:\Python25\lib\site-packages\py2exe\build_exe.py", line 285,
> in _run
> self.create_binaries(py_files, extensions, dlls)
>   File "C:\Python25\lib\site-packages\py2exe\build_exe.py", line 591,
> in create_
> binaries
> bytes = zlib_file.read()
> AttributeError: 'NoneType' object has no attribute 'read'
> 
> This is a standard Python 2.5 installation. Doing the same thing with
> 2.4 works like a charm.
> 
> Did I miss anything?
> 
Patches for this have been posted to the py2exe-users list.

Thomas

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


  1   2   >