Re: convert list of tuples into several lists

2005-02-10 Thread Steven Bethard
Cappy2112 wrote:
What does the leading * do?
Tells Python to use the following iterable as the (remainder of the) 
argument list:

py def f(x, y):
... print x, y
...
py f([1, 2])
Traceback (most recent call last):
  File interactive input, line 1, in ?
TypeError: f() takes exactly 2 arguments (1 given)
py f(*[1, 2])
1 2
py f(1, [2])
1 [2]
py f(1, *[2])
1 2
Note that whenever the leading * is present, the following list gets 
expanded into the positional arguments of f -- x and y.

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


Re: That horrible regexp idiom

2005-02-10 Thread alex23
Stephen Thorne wrote:
 We've all seen it before. Its a horrible idiom that you would achieve
 in another language by doing:

 if (m = foo_pattern.search(subject))
 { }
 else
 { }

 but it occured to me today, that it is possible to do it in python
 without the extra line.

 ' for m in xsearch(foo_pattern, subject):
 ' pass
 ' else:
 ' pass

 simple, concise, requires no new syntax, and is only a little
confusing[1]!

It won't have quite the same effect though, as the 'else' statement is
*always* called after the 'for' loop completes.

To have the functionality you're after, you need to include a break in
the code block within the loop.

- alex23

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


Re: Is email package thread safe? (fwd)

2005-02-10 Thread Antoon Pardon
Op 2005-02-09, Roman Suzi schreef [EMAIL PROTECTED]:
 On Wed, 9 Feb 2005, Antoon Pardon wrote:

 Op 2005-02-09, Roman Suzi schreef [EMAIL PROTECTED]:

 Just to be sure, is email package of Python 2.3 thread-safe or not
 (to use, for example, in python-milter?)

 Can I assume that everything
 else without such notice is thread-safe?

 I doubt it. There is no indication that the email package uses any
 kind of locking. So multiple thread working on the same message
 will probably screw things up.

 Of course, I do not let threads to work on the same message!

Why should that be: off course? The random module you spoke about
was also only thread unsafe if you called the same random generator
from various threads. Using a randon generator per thread shouldn't
have been a problem. Since you mentioned that, I thought that was
the kind of thread safety you were after.

 I meant that the package doesn't pose other kinds of restrictions.
 Can it work in _any_ situation work on two different messages at the same 
 time, without any interference?

I can't give a guarantee, but there are no global statements and there
doesn't seem to be assignments to cross module variables I think it
would be a safe bet.

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


Re: empty classes as c structs?

2005-02-10 Thread Alex Martelli
Steven Bethard [EMAIL PROTECTED] wrote:

 I'm not sure how much _I_ like them... =) It makes me uneasy that
 
  del b.x
  print b.x
 
 doesn't throw an AttributeError.  OTOH, if you're using namespaces as
 the equivalent of nested scopes, deleting all 'x' attributes is probably
 not what you want...

Right.  Besides, you can easily get such effects today:

 b.x = 15
 print b.x
15
 del b.x
 print b.x
23
 del b.x
Traceback (most recent call last):
  File stdin, line 1, in ?
AttributeError: x


All you need is to have (e.g.) the following few lines before these:

 class B(object):
...   x = 23
... 
 b=B()


 I like the idea of chain, though, so I'll probably add the class with
 just __init__ and __getattribute__ to the current implementation.  I'm
 willing to be persuaded, of course, but for the moment, since I can see
 a few different options, I'm refusing the temptation to guess on the 
 most natural behavior for __delattr__ and __setattr__...  =)

That's probably best in terms of API.  Not too sure about the
implementation (why wouldn't __getattr__ suffice, holding the bunches in
an attribute with a magicname?) but that's a secondary issue.


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


Re: strange behaviour with decorators.

2005-02-10 Thread Antoon Pardon
Op 2005-02-09, Delaney, Timothy C (Timothy) schreef [EMAIL PROTECTED]:
 Antoon Pardon wrote:

 Ah, yes, the penny dropped. The try: except where there because
 originally there were other statements I wanted to test and I
 didn't want the raise exception by the inc(-2) stop the script.
 I completely forget to consider it would also catch the
 error I was expecting.

 A very good example of why you should (almost) never use a bare except:
 ...


Well in this case I would say the fault was not with the bare except:
The intention was to put the following.

except:
  print sys.excepthook(*sys.exc_info())


But I always forget this idiom, one with full except the other
abrviated to exc, one in one word the other with an underscore
I always forget which is which and being in a hurry I just put
a pass thinking I would look it up and replace it later.

But before I did so I tested it a first time and was so surprised
I forgot.
-- 
http://mail.python.org/mailman/listinfo/python-list


deepcopy chokes with TypeError on dynamically assigned instance method

2005-02-10 Thread 5ÛHH575-UAZWKVVP-7H2H48V3
(see end of message for example code)

When an instance has a dynamically assigned instance method, deepcopy
throws a TypeError with the message TypeError: instancemethod
expected at least 2 arguments, got 0.  Tested with Python 2.3.4 on
OpenBSD and Python 2.4 on Win98; same results.  Is this a bug in
deepcopy, how I dynamically assign the instance method or something
else?  (See example code for how I did it.)

If you're curious as to why the deep copy and dynamic assign are
necessary or have implementation suggestions (or alternatives), I bet
you'd like some details.  The TypeError cropped up while coding a
'Point' class representing cartesian coordinates.  I needed to
overload an 'origin' method as both a class method and an instance
method (if Python were more Perlesque... ;-) ).  'origin' returns a
point representing an origin.  The class method requires an argument
for the dimension of the origin, while the instance method uses the
dimension of an instance (ortus overloading).  As the instance
reference isn't bound when the class 'origin' method is defined,
there's no way to use a default argument.  I instead dynamically
assign an instance method to the 'origin' attribute of the instance.

As for the deepcopy, scalars aren't necessarily of a built-in numeric
type, though I generally expect them to be numeric (you could use
lists or strings as scalars, but not many methods would still be
usable).  Point is the base clase for Vector, and I want (e.g.)
vectors of vectors so I can eventually extend Vector to Matrix and
Tensor.  The Point constructor has a single argument: a sequence of
scalars (which, as noted, can be sequences).  In practice, the
sequence itself will be a tuple, a list, a Point or descendant of
Point (so that Point can act as a copy constructor).  To prevent a
copied point from aliasing elements of a different Point, I used
deepcopy.  When the TypeError struck, I switched to a generator, which
works as long as every constructor functions as a copy constructor
(not necessarily true, apparently, of lists, but true of Points).  I
could also implement copy-on-write semantics for coordinates or
implement __deepcopy__ for Point (which will probably be the final
solution).


example code:

from copy import copy,deepcopy
import new

class Foo(list):
Foo

def __init__(self, l=[]):
list.__init__(self, deepcopy(l))
# using generator rather than deepcopy produces no errors. 
#list.__init__(self, [copy(el) for el in l])
# 'copy(el)' in generator results in a deepcopy of sequence
# as long as each object encountered uses a copy constructor
# (which I expect of numeric types) and doesn't implement 
# a shallow __copy__.  Alternative is to use type(el)(el):
#list.__init__(self, [type(el)(el) for el in l])
def bar(self):
return 'bar'
self.bar=new.instancemethod(bar, self, self.__class__)
# also causes deepcopy to choke:
#self.bar = self._bar

def _bar(self):
return 'bar'

#deepcopy has no problem with this
bar = _bar

def __repr__(self):
return self.__class__.__name__+'(['\
+','.join(map(str, self))+'])'

# causes deepcopy to throw a TypeError
Foo(Foo('foo'))

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


Re: Vectors in Visual Python

2005-02-10 Thread Alex Martelli
Arthur [EMAIL PROTECTED] wrote:

 thinking that the visciousness with wihich you were attacking someone
 suggesting a proposal for an optional feature - even if an iill
 adivised proposal for and ill advised optional feature (I frankly
 don't care much about that part of the discussion one way or another)

While in my case it's essentially ALL that I care about in this
discussion: the technical aspects of Python.

 - was unwarranted, and more importantly *unwise* for someone in a

If, like you, I didn't care about the technical aspects of Python, it
sure would be unwise to get upset -- I could let the language go to hell
in a handbasket, as long as I made sure I looked good myself.

Caring deeply and passionately about something greater than oneself,
particularly something which may seem dry and abstract to those who
don't care a whit for it, might no doubt be deemed intrinsically unwise
-- and yet, there is much to be said for such passion.  Without the
ability to get passionate and inflamed, we might perhaps be wiser, but
we'd be Vulcans, not humans.  Moreover, unless some of us felt such
passion for certain technical issues, you guys who don't care would not
get the benefits of the time and energy we freely devote to them -- so
it's unwise, even from a strictly selfish viewpoint, to try to turn us
firebrands into such coolly calculating Vulcans.

 postion of community leadership - considering past, recent, and
 undoubtedly future issues that have and will arise. 
 
 What don't *you* understand about that??

Could you _really_ believe, considering the many years of consistent
history of my posts on this group, that by reviving the issue you could
get *any* other effect but fanning the flames all over again?  THAT is
what I don't understand: whether you're doing that _deliberately_, or
out of almost-unbelievable levels of cluelessness.

 We all have are own kinds of stupidities, it seems to me.

This is no doubt the case.  For example, many of us instinctively brake
and swerve when a small animal jumps into the road in front of the car
they're driving, seriously endangering themselves and the passengers
thereby.  If we were presented the issue in a context giving us time to
reflect and react rationally -- To how much danger to life and limb
would you subject yourself, your wife, and your children, to increase
the likelihood of survival for some stupid cat who can't wait to cross
the road? -- we'd probably react quite differently.  And yet, while it
IS objectively stupid to behave that way, it _is_ one of the stupidities
that make us human.

A _deliberate_ and consistent preference can be disagreed with, but it's
pretty pointless to call it stupid or unwise; there is just no
accounting for tastes.  If you _prefer_ the flame about declarations to
continue for its own sake (or because you believe it makes you look
good, whatever), while not caring about its contents, I may consider
that evil and hateful, but it's neither intelligent nor stupid _per se_.
If your preferences are otherwise, and yet your behavior is easily seen
to be such as to have that effect, then THIS is indeed very stupid.


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


Re: Is Python as capable as Perl for sysadmin work?

2005-02-10 Thread Richie Hindle

[Steve]
 Was it INTERCAL that had the COMEFROM Line number statement instead of
 GOTO? I REALLY like the idea of a COMEFROM statement. I think python should
 have a COMEFROM statement

It does - see http://entrian.com/goto/

(In case you doubt it: yes, it works, but note that it doesn't work at the
interactive prompt, only in a real source file.)

(The fact that I felt obliged to add the first paragraph on that page is
the funniest part of the whole thing.  I really did have people genuinely
thanking me for the module, asking for features, asking for help with
using it, and so on.)

-- 
Richie Hindle
[EMAIL PROTECTED]

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


pyFMOD writing a callback function in Python

2005-02-10 Thread Marian Aldenhövel
Hi,
I am using the FMOD audio-library with the pyFMOD python bindings. pyFMOD uses
ctypes. It is possible to register callback functions with FMOD that are
called at certain points in the processing pipeline or when certain events
happen.
I am expecially interested in the one that fires when a currently playing
stream ends. This is what the declaration in pyFMOD looks like:
  _FSOUND_Stream_SetEndCallback =
 getattr(fmod,[EMAIL PROTECTED])
  _FSOUND_Stream_SetEndCallback.restype = c_byte
  def FSOUND_Stream_SetEndCallback(stream, callback, userdata):
 result = _FSOUND_Stream_SetEndCallback(c_int(stream), c_int(callback),
c_int(userdata))
 if not result: raise fmod_exception()
I cannot make it work, however. I tried:
  def _sound_end_callback(stream,buf,len,userdata):
print _sound_end_callback(): Stream has reached the end.
as simplest possible callback function. I am registering it like this:
  pyFMOD.FSOUND_Stream_SetEndCallback(_currenttrack,_sound_end_callback,0)

And this is how my program dies:
  File d:\projekte\eclipse\workspace\gettone\gettonesound.py, line 175, in 
sound_tick
pyFMOD.FSOUND_Stream_SetEndCallback(_currenttrack,_sound_end_callback,0)
  File c:\programme\Python23\lib\site-packages\pyFMOD.py, line 690, in 
FSOUND_Stream_SetEndCallback
result = _FSOUND_Stream_SetEndCallback(c_int(stream), c_int(callback), 
c_int(userdata))
TypeError: int expected instead of function instance

I am very new to Python and have zero idea what the problem is nor how to
solve it. In some of my other languages I would have to explicitly make a
function pointer and possibly have to cast that to an int to pass it to
SetEndCallback, but that seems very inappropriate in Python...
Ciao, MM
--
Marian Aldenhövel, Rosenhain 23, 53123 Bonn. +49 228 624013.
http://www.marian-aldenhoevel.de
Wir brauchen keine Opposition, wir sind bereits Demokraten.
--
http://mail.python.org/mailman/listinfo/python-list


SAP IDOC with python

2005-02-10 Thread Jaco Smuts
Hello there
I'm tinkering with parsing SAP IDOC's using Python. (initially reading 
possibly creating later on)

I can get a C header file someCode.h from SAP  describing the contents / 
structure of a document. I  wondered if this file in conjunction with 
SWIG will be any use?

Any one got any experience suggestions on this?
thanks in advance
jaco
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python-list Digest, Vol 13, Issue 85

2005-02-10 Thread Dave Beech

- Original Message -
From: [EMAIL PROTECTED]
To: python-list@python.org
Sent: Wednesday, October 06, 2004 6:35 AM
Subject: Python-list Digest, Vol 13, Issue 85


 Send Python-list mailing list submissions to
 python-list@python.org

 To subscribe or unsubscribe via the World Wide Web, visit
 http://mail.python.org/mailman/listinfo/python-list
 or, via email, send a message with subject or body 'help' to
 [EMAIL PROTECTED]

 You can reach the person managing the list at
 [EMAIL PROTECTED]

 When replying, please edit your Subject line so it is more specific
 than Re: Contents of Python-list digest...







 Today's Topics:

1. Re: New to Python: Features (Grant Edwards)
2. Re: Python Macros (Jeff Shannon)
3. Re: Python Macros (Lonnie Princehouse)
4. [ANN] PySQLite 1.0 (Gerhard Haering)
5. Python concatenation Question problem (Kory Wheatley)
6. Re: re bug (Gustavo Niemeyer)
7. Re: Data/File Structure and Algorithm for Retrieving Sorted
   Data Chunk Efficiently (William Park)
8. Re: [ANN] PySQLite 1.0 (Irmen de Jong)
9. Retrieving the full path of Unix apps (Lorin Hochstein)
   10. Re: New to Python: Features (Alex Drummond)
   11. Re: New to Python: Features (Neuruss)







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


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


Re: Python-list Digest, Vol 13, Issue 102

2005-02-10 Thread Dave Beech

- Original Message -
From: [EMAIL PROTECTED]
To: python-list@python.org
Sent: Thursday, October 07, 2004 1:04 AM
Subject: Python-list Digest, Vol 13, Issue 102


 Send Python-list mailing list submissions to
 python-list@python.org

 To subscribe or unsubscribe via the World Wide Web, visit
 http://mail.python.org/mailman/listinfo/python-list
 or, via email, send a message with subject or body 'help' to
 [EMAIL PROTECTED]

 You can reach the person managing the list at
 [EMAIL PROTECTED]

 When replying, please edit your Subject line so it is more specific
 than Re: Contents of Python-list digest...







 Today's Topics:

1. Re: Python Macros (Carlos Ribeiro)
2. Re: Python Macros (gabriele renzi)
3. Re: Python Macros (gabriele renzi)
4. Re: Python Macros (Alex Martelli)
5. Re: Parallelization on muli-CPU hardware? (Nick Craig-Wood)
6. Re: Job postings (Larry Bates)
7. Re: Embedding python with debugging features (Wolfgang Langner)
8. Re: re bug (Gustavo Niemeyer)
9. How to improve extracting data speed (Yong Wang)
   10. Re: Parallelization on muli-CPU hardware? (?? ???)
   11. Re: metaclass and customization with parameters (Gustavo Niemeyer)







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


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


How to quit a Tkinter application

2005-02-10 Thread Brian Colfer
Title: Message



If I set up a menu 
item to Exit and use root.quit the application quits but I get a thread 
terminated abnormaly error.

BTW I'm using Pmw to 
create the menu and items.

primary email: [EMAIL PROTECTED]blog: http://briancolferblog.blogspot.com/Mobile: (415) 
613-3669

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

Re: PyQt and Python 2.4 - also WinXP LnF?

2005-02-10 Thread Phil Thompson
 After quite a while of wxPython I'm getting back into PyQt, mainly due
 to the announcement by Trolltech that they will make a GPL version of
 Qt4 for Windows (and Phil-T said he will make a PyQt to go with it
 eventually!)

 I'm currently using PyQt 3.12 that comes with the BlackAdder demo, it
 seems to work fine with Python 2.3.5 except that it doesn't support the
 WinXP look'n'feel, the QStyle WindowsXP isn't included, and using a
 manifest file doesn't seem to fix this.

 Does anyone know if the latest PyQt (3.13?) is built with this support?
 I thought this had been supported since 3.10 or earlier, is it just the
 BlackAdder build that's broken?

PyQt supports the WindowsXP style if Qt has been built with it enabled.

 I'm writing an XMMS remote control program, so it will be GPL when
 released (if it's ever good enough to release!) so I'm looking at
 buying the commercial PyQt3 or BlackAdder whilst waiting for the GPL
 PyQt4

 Can I use the commercial PyQt without a commercial Qt - I guess I could
 as long as I don't distribute the qt-mt333.dll? I have no use for Qt
 itself, not interested in C++, so it seems a bit much to have to buy a
 license just for a DLL!

No. PyQt is supplied as a source package. You don't have the Qt .h files
needed to compile it. One point of the BlackAdder license is that you
can't use the bundled version of Qt to build C++ applications - even if
that C++ application is another version of PyQt.

 Also, would I have to build it all myself or does Riverbank/TheKompany
 provide binaries like PyQt 3.13 for Python 2.4, as I don't have Visual
 Studio I can't build it myself.

We don't provide binaries, but the free MSVC, Borland and MinGW compilers
are all supported.

 OK, I'm off to check on my build of PyQt on my Fedora2/Python 2.4
 machine ;-)

Phil

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


Re: convert list of tuples into several lists

2005-02-10 Thread Oliver Eichler
Pierre Barbier de Reuille wrote:
 Best answer is : try it :)
 use the timeit module (in the standard lib) to do so ...

Ok,

import timeit

s = \
a,b,c1,c2 = zip(*[(x[2],x[4], x[2]-x[1], x[2] - x[3]) for x in z])


t = timeit.Timer(stmt=s,setup=z = [(1,2,3,4,5)]*1000)
print %.2f usec/pass % (100 * t.timeit(number=10)/10)

s =\
for x in z:
  a = x[2]
  b = x[4]
  c1 = x[2] - x[1]
  c2 = x[2] - x[3]


t = timeit.Timer(stmt=s,setup=z = [(1,2,3,4,5)]*1000)
print %.2f usec/pass % (100 * t.timeit(number=10)/10)

for 30 elements:
[EMAIL PROTECTED]:~/tmp python test.py
32.90 usec/pass
21.53 usec/pass

for 100 elements:
[EMAIL PROTECTED]:~/tmp python test.py
103.32 usec/pass
70.91 usec/pass

for 100 elements:
[EMAIL PROTECTED]:~/tmp python test.py
1435.43 usec/pass
710.55 usec/pass

What do we learn? It might look elegant but it is slow. I guess mainly
because I do the iteration twice with the zip command. The 1000 element run
seems to show what Guido means with abuse of the argument passing
machinery

Learned my lesson :)

Thanks to all

Oliver


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


thread / twisted defered etc...

2005-02-10 Thread Gustavo Rahal
Hi
To practice some programming skills I would like to make a mp3 player 
that fetches lyrics from websites. I want to use PyGTK and gstreamer.
I started some coding and i'm already stuck with the first problem.
Gtk freezes waiting for the lyric to be fetched, which I guess was 
expected. How to solve this and other similar problems (maybe gtk could 
freeze when using gstreamer)?
Someone pointed out defered from twisted package. Is it good a idea? 
What about using the module threading? Could it be a problem to use 
threads with GUI (gtk) apps?

I'm new to python, gtk and gstreamer so if possible detailed 
explanations are appreciated :)

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


Re: Newbie: SWIG or SIP?

2005-02-10 Thread Phil Thompson
 I have a third-party DLL and it's associated .h file.  The DLL was written
 in C.  I have neither the associated .c files nor the .obj files for the
 DLL.  Can I use SWIG or SIP to build something that will allow me to use
 the
 DLL with Python?  And what is that something, an .obj file, another DLL or
 what?

Yes, you can use either SWIG or SIP. C (as opposed to C++) support was
added with SIP v4. The something is another DLL, conventionally given a
.pyd extenstion.

Phil

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


hard_decoding

2005-02-10 Thread Tamas Hegedus
Hi!
Do you have a convinient, easy way to remove special charachters from 
u'strings'?

Replacing:
ÀÁÂÃÄÅ  = A
èéêë= e
etc.
'L0xe1szl0xf3' = Laszlo
or something like that:
'L\xc3\xa1szl\xc3\xb3' = Laszlo
Thanks,
Tamas
--
Tamas Hegedus, Research Fellow | phone: (1) 480-301-6041
Mayo Clinic Scottsdale | fax:   (1) 480-301-7017
13000 E. Shea Blvd | mailto:[EMAIL PROTECTED]
Scottsdale, AZ, 85259  | http://hegedus.brumart.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: variable declaration

2005-02-10 Thread Antoon Pardon
Op 2005-02-08, Fredrik Lundh schreef [EMAIL PROTECTED]:
 Peter Otten wrote:

 executed. the compiler handles global and from __future__, everything
 else is done at runtime.

 and __debug__, too, it seems:

 you left out the python -O line.

 __debug__
 False
 def f():
 ... if __debug__:
 ... global x
 ... x = 42
 ...
 f()
 x
 Traceback (most recent call last):
  File stdin, line 1, in ?
 NameError: name 'x' is not defined

 yup, but unlike the two others, that's a CPython -O implementation issue.
 (I'd say bug, in this case).

 neither standard CPython (without -O) nor Jython behave this way.


If people here are so against declarations, how do they feel about
statements that don't seem like declarations but have a declarative
effect anyway?

Because that is what assignment statements in python essentially are.
If assignments wouldn't have a declarative effect then code like
the following should work:

x = 42

def f():
  if False:
x = 20
  return x

f()


If the x = 20 would be a pure executing statement, then how come
its presence has an effect on the return statement even when it
isn't executed. And we can play the same trick here. calling python -O
and feeding it this program but with the False replaced by __debug__
will make this work.

So having come to the conclusion that some statements have a declarative
effect, I would prefer to have the declaration and the assignment be
seperated in two different statements. That would make the declaration
explicit instead of being implicit now and explicit is better than
implicit.

Of course the other solution, simply removing the declarative effect from
assignments, could work too and might even be preferable but I fear
it would produce strange behaviour.

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


Re: convert list of tuples into several lists

2005-02-10 Thread Oliver Eichler
Pierre Barbier de Reuille wrote:
 
 Best answer is : try it :)
 use the timeit module (in the standard lib) to do so ...

Ok, (a second time. I hope the first post was cancelled as it was false)

import timeit

s = \
a,b,c1,c2 = zip(*[(x[2],x[4], x[2]-x[1], x[2] - x[3]) for x in z])


t = timeit.Timer(stmt=s,setup=z = [(1,2,3,4,5)]*1000)
print %.2f usec/pass % (100 * t.timeit(number=10)/10)

s =\
a = []
b = []
c1 = []
c2 = []
for x in z:
  a.append(x[2])
  b.append(x[4])
  c1.append(x[2] - x[1])
  c2.append(x[2] - x[3])


t = timeit.Timer(stmt=s,setup=z = [(1,2,3,4,5)]*1000)
print %.2f usec/pass % (100 * t.timeit(number=10)/10)

for 100 elements:
[EMAIL PROTECTED]:~/tmp python test.py
104.67 usec/pass
180.19 usec/pass

for 1000 elements:
[EMAIL PROTECTED]:~/tmp python test.py
1432.06 usec/pass
1768.58 usec/pass


What do we learn? The zip-thingy is even faster than the for loop

Learned my lesson :)

Thanks to all

Oliver

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


Re: Some questions...

2005-02-10 Thread bruno modulix
Mario Lacunza wrote:
Hello,
Im new in Python, please  I need some information:
- Somebody know if: is possible use Python within Net Framework in
windows environment??
http://www.ironpython.com/
http://www.zope.org/Members/Brian/PythonNet/
- Where found info about reports in Python? exist some program like
Crystal Reports??
ReportLab is probably the place to go
http://www.reportlab.org/
-  Database access: Firebird , I dont found correct information about
this tools and his conection/working with Python.
http://kinterbasdb.sourceforge.net/

Thanks!!!
HTH
--
bruno desthuilliers
ruby -e print '[EMAIL PROTECTED]'.split('@').collect{|p| 
p.split('.').collect{|w| w.reverse}.join('.')}.join('@')
--
--
http://mail.python.org/mailman/listinfo/python-list


sre is broken in SuSE 9.2

2005-02-10 Thread Denis S. Otkidach
On all platfroms \w matches all unicode letters when used with flag
re.UNICODE, but this doesn't work on SuSE 9.2:

Python 2.3.4 (#1, Dec 17 2004, 19:56:48) 
[GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
Type help, copyright, credits or license for more information.
 import re
 re.compile(ur'\w+', re.U).match(u'\xe4')
 

BTW, is correctly recognize this character as lowercase letter:
 import unicodedata
 unicodedata.category(u'\xe4')
'Ll'

I've looked through all SuSE patches applied, but found nothing related.
What is the reason for broken behavior?  Incorrect configure options?

-- 
Denis S. Otkidach
http://www.python.ru/  [ru]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hard_decoding

2005-02-10 Thread Peter Maas
Tamas Hegedus schrieb:
Do you have a convinient, easy way to remove special charachters from 
u'strings'?

Replacing:
ÀÁÂÃÄÅ = A
èéêë= e
etc.
'L0xe1szl0xf3' = Laszlo
or something like that:
'L\xc3\xa1szl\xc3\xb3' = Laszlo
 ord(u'ë')
235
 ord(u'e')
101
 cmap = {235:101}
 u'hello'.translate(cmap)
u'hello'
 u'hëllo'.translate(cmap)
u'hello'
The inconvenient part is to generate cmap. I suggest you write a
helper class genmap for this:
 g = genmap()
 g.add(u'ÀÁÂÃÄÅ', u'A')
 g.add(u'èéêë', u'e')
 'László'.translate(g.cmap())
Laszlo
--
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
---
--
http://mail.python.org/mailman/listinfo/python-list


Re: probably weird or stupid newbie dictionary question

2005-02-10 Thread Nick Craig-Wood
Diez B. Roggisch [EMAIL PROTECTED] wrote:
  But what happens in case of a hash code clash? Then a list of (key, values)
  is stored, and for a passed key, each key in that list is additionally
  compared for being equal to the passed one. So another requirement of
  hashable objecst is the comparability. In java, this is done using the
  equals method.
 
  So in the end, the actual mapping of key, value looks like this:
 
  hash(key) - [(key, value), ]

Thats called hashing with chaining.

See Knuth: Sorting and Searching if you want to know more!

-- 
Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: convert list of tuples into several lists

2005-02-10 Thread Nick Craig-Wood
Cappy2112 [EMAIL PROTECTED] wrote:
  What does the leading * do?

It causes the list/tuple following the * to be unpacked into function
arguments. Eg

 zip(*[(1, 2, 3), (4, 5, 6)])
[(1, 4), (2, 5), (3, 6)]

is the same as

 zip((1, 2, 3), (4, 5, 6))
[(1, 4), (2, 5), (3, 6)]

The * should make you think of dereferencing things (eg pointer
de-reference in C).

Its equivalent to the now deprecated apply function which does the
same thing in a more wordy fashion, ie apply the list as parameters to
the function.

 apply(zip, [(1, 2, 3), (4, 5, 6)])
[(1, 4), (2, 5), (3, 6)]

-- 
Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variable declaration

2005-02-10 Thread Antoon Pardon
Op 2005-02-09, Nick Coghlan schreef [EMAIL PROTECTED]:
 Antoon Pardon wrote:
 Op 2005-02-08, Nick Coghlan schreef [EMAIL PROTECTED]:
The CPython *_FAST opcodes relate to functions' local variables. Behind the 
scenes they are implemented as integer indexing operations into a pre-sized 
C 
array. Operations don't come much faster than that :)
 
 
 I don't follow. AFAIR my remark here above was about the STORE opcode.
 But you seem to react to it as if I am talking about STORE_FAST.

 I've been talking about rebinding function local variables all along - which 
 means STORE_FAST. I may not have made that explicit, though.

 However, even in the general case, check it already exists and overwrite it 
 if 
 it does is going to be slower than just store it.

 The reason is that, if checking for the existence of the name first somehow 
 provides a speed advantage (I still can't see how it could), then the latter 
 case of unconditional storage can check for the names existence *just to get 
 the 
 speed advantage* (the difference being that the name gets bound irrespective 
 of 
 whether it originally existed or not).

 Anything that could be used to speed up a rebinding, could most likely be 
 used 
 to speed up a standard binding at the same point in the code. So, while it 
 might 
 be possible to get rebinding code which isn't any slower than a standard 
 binding, it seems practically impossible to do anything to get rebinding code 
 to 
 be *faster*.

Well it seems you have some fair points. I'll just stop here stating
that I would like to have it, even if it proved to be slower. Speed
is not that big a factor in the things I write. I just would like
to ask a question relating semantics. Supose the following code.

x = 42

def f():
  x := 21   #  or x .= 42  I don't remember what you used exactly

f()
print x


What do you feel should happen. I can think of two possibilities.

1) It raises an exception because x is not locally bound.

2) it prints 21.


I think the second option would be the more interesting one as
it would allow to get rid of the global statement and it would
allow for rebinding names within nested scopes.

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


Re: A great Alan Kay quote

2005-02-10 Thread jfj
Peter Hansen wrote:
Grant Edwards wrote:
In an interview at 
http://acmqueue.com/modules.php?name=Contentpa=showpagepid=273
Alan Kay said something I really liked, and I think it applies
equally well to Python as well as the languages mentioned:

I characterized one way of looking at languages in this
way: a lot of them are either the agglutination of features
or they're a crystallization of style. Languages such as
APL, Lisp, and Smalltalk are what you might call style
languages, where there's a real center and imputed style to
how you're supposed to do everything.
I think that a crystallization of style sums things up nicely.
The rest of the interview is pretty interesting as well.

Then Perl is an agglutination of styles, while Python might
be considered a crystallization of features...
Bah. My impressions from the interview was there are no good
languages anymore. In my time we made great languages, but today
they all suck. Perl for example
I got the impressions that the interview is as bad for python
as for perl and any of the languages of the 90's and 00's.
From the interview:
 You could think of it as putting a low-pass filter on some of the 
good ideas from the 60s and 70s, as computing spread out much, much 
faster than educating unsophisticated people can happen. In the last 25 
years or so, we actually got something like a pop culture, similar to 
what happened when television came on the scene and some of its 
inventors thought it would be a way of getting Shakespeare to the 
masses. But they forgot that you have to be more sophisticated and have 
more perspective to understand Shakespeare. What television was able to 
do was to capture people as they were.

So I think the lack of a real computer science today, and the lack of 
real software engineering today, is partly due to this pop culture.


So, let's not be so self-important winkus, and see this interview
as one who bashes perl and admires python. It aint. Python is pop
culture according to Mr Kay. I'll leave the rest to slashdot..
jfj
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and version control

2005-02-10 Thread Nick Craig-Wood
Sergei Organov [EMAIL PROTECTED] wrote:
  Carl [EMAIL PROTECTED] writes:
 
  [...]
  I am a keen user of Emacs, but version control, which is very simple
  when you are in a Linux environment, for example, is not a
  straightforward in Windows.
 
  Emacs + CVS (or CVSNT) should work just fine in Windows either.

When I have to edit stuff on windows I use emacs.  Cvs works fine on
windows too.  I haven't tried cvs in emacs on windows, but I suspect
it will work fine as all emacs does is shell out to the cvs binaries.

-- 
Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: That horrible regexp idiom

2005-02-10 Thread Ville Vainio
 Stephen == Stephen Thorne [EMAIL PROTECTED] writes:

Stephen We've all seen it before. Its a horrible idiom that you
Stephen would achieve in another language by doing:

Stephen if (m = foo_pattern.search(subject)) 
Stephen { }
Stephen else
Stephen { }

Stephen but it occured to me today, that it is possible to do it in python
Stephen without the extra line.
Stephen '
Stephen ' def xsearch(pattern, subject):
Stephen ' yield pattern.search(subject)

Stephen ' for m in xsearch(foo_pattern, subject):
Stephen ' pass
Stephen ' else:
Stephen ' pass

Stephen simple, concise, requires no new syntax, and is only a
Stephen little confusing[1]!

I'm always confused by for-else (lack of practice), but isn't the else
clause going to be always executed when there is no break in the for
suite?

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


Re: Loop in list.

2005-02-10 Thread beliavsky
Jim wrote:
 Wow!  All I wanted to do was write the equivalence
 of the Fortran statement:  Real*4 matrix(n,n).

If you are doing numerical linear algebra in Python, you should use the
Numeric or Numarray modules. With Numeric, the equivalent is just

from Numeric import zeros
matrix = zeros([n,n],Float)

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


Re: sre is broken in SuSE 9.2

2005-02-10 Thread Serge Orlov
Denis S. Otkidach wrote:
 On all platfroms \w matches all unicode letters when used with flag
 re.UNICODE, but this doesn't work on SuSE 9.2:

 Python 2.3.4 (#1, Dec 17 2004, 19:56:48)
 [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
 Type help, copyright, credits or license for more
information.
  import re
  re.compile(ur'\w+', re.U).match(u'\xe4')
 

 BTW, is correctly recognize this character as lowercase letter:
  import unicodedata
  unicodedata.category(u'\xe4')
 'Ll'

 I've looked through all SuSE patches applied, but found nothing
related.
 What is the reason for broken behavior?  Incorrect configure options?

I can get the same results on RedHat's python 2.2.3 if I pass re.L
option, it looks like this option is implicitly set in Suse.

  Serge

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


Re: Building Python with Tcl/Tk on Cygwin_NT-5.1

2005-02-10 Thread Jason Tishler
Dean,

On Wed, Feb 09, 2005 at 08:15:43AM -0800, Dean N. Williams wrote:
 The $ TMP=/tmp rebaseall command worked! Thank you.

You are quite welcome.

 When a new Cygwin is available w/ your changes please let me know...

Sorry, but the above does not scale.  If you subscribe to
cygwin-announce@, then you will be notified when rebase and other Cygwin
packages are released.

Jason

-- 
PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers
Fingerprint: 7A73 1405 7F2B E669 C19D  8784 1AFD E4CC ECF4 8EF6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sre is broken in SuSE 9.2

2005-02-10 Thread Denis S. Otkidach
On Thu, 10 Feb 2005 13:00:42 +0300
Denis S. Otkidach [EMAIL PROTECTED] wrote:

 On all platfroms \w matches all unicode letters when used with flag
 re.UNICODE, but this doesn't work on SuSE 9.2:
 
 Python 2.3.4 (#1, Dec 17 2004, 19:56:48) 
 [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
 Type help, copyright, credits or license for more information.
  import re
  re.compile(ur'\w+', re.U).match(u'\xe4')
  
 
 BTW, is correctly recognize this character as lowercase letter:
  import unicodedata
  unicodedata.category(u'\xe4')
 'Ll'
 
 I've looked through all SuSE patches applied, but found nothing
 related. What is the reason for broken behavior?  Incorrect configure
 options?

Just a bit more information. test_re.py fails in SuSE 9.2 with the
following errors:

snip
Running re_tests test suite
=== Failed incorrectly ('(?u)\\b.\\b', u'\xc4', 0, 'found', u'\xc4')
=== Failed incorrectly ('(?u)\\w', u'\xc4', 0, 'found', u'\xc4')

-- 
Denis S. Otkidach
http://www.python.ru/  [ru]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: negative integer division

2005-02-10 Thread Mike Meyer
Jive Dadson [EMAIL PROTECTED] writes:

 Mike Meyer wrote:
 [C] isn't - it's a portable assembler.

 I've heard that many times, but it makes no sense to me.  By definition,
 the syntax of an assembly language closely resembles the format of
 individual hardware instructions for a particular processor.

Um, no. The syntax of an assembly language is totally unrelated to the
format of the individual hardware instructions for a particular
processor. Typically, the syntax of an assembly language is such that
one obvious syntactical element (for instance, a line) generates one
hardware instruction. Usually, mnemonics of some kind were used to
denote which instruction to generate. However, it doesn't have to be
that way. Whitesmith had a z80/8080 assembler in which you wrote a +=
b to add the contents of register b to register a.

 An
 assembler assembles individual hardware instructions.  Back in the day,
 Unix (written largely in C) and Steve Johnson's pcc (the *portable* C
 compiler) together constituted a big leap forward.

A big leap forward *from assembler*. The development space that C
occupied at that time was the kernel and system utilities - things
that were usually (though by no means always) done in assembler before
the arrival of C. As a tool for producing robust, reliable code it
pretty much sucks, because it has so many of the flaws that assembler
has. Calling it a high level language is a disservice to the HLLs of
the era.

 Implementing Unix on
 new processors was infinitely easier than porting OS's written in
 assembly language.  So I disagree on two counts: C code is not entirely
 portable, (for example, division and mod may not work the same on two
 different machines), and a C compiler is most certainly not an
 assembler.

No language is entirely portable. C is *much* more portable than the
assembler languages that it displaced.

Note that C has displaced assembler in other areas - for instance,
it's not uncommon to find compilers that use ANSI C as the target
machine. By using C as a portable assembler instead of generating
machine code, the number of supported platforms increases
dramatically.

 Now, I'll agree with you if you want to argue that some machines do
 negative integer division in stupifyingly horrible ways.

 That's why I think it was a stupifyingly horrible decision.
 Understandable, but in the end an s.h.d. nonetheless.  It would have
 been okay to define / and % correctly, in the mathematical sense,
 but also provide functions quick_div() and quick_mod() that were
 guaranteed to work correctly only when both arguments were positive.
 The way they did it is just too error prone, akin to early
 optimization.

The way they did it was exactly right for the target applications
(i.e. - the v6 Unix kernel and system utilities).

 It's bitten me before, when I was called on to port
 code (which I did not write) from one machine to another.

There is no such thing as a portable program - merely ported
programs. I've been bitten by the code assuming that ints were two
bytes long, and know of cases where people were bitten by code that
assumed that chars were 8 bits. The simple fact of the matter is that
these things - like the behavior of the low-level div and mod
instructions - change from machine to machine. You have to deal with
such things when you are writing what is basically assembler. If you
were using a real HLL, none of these things would be a problem.

 Having standard operators with
 under-defined behavior is just inviting trouble: long debugging
 sessions, or worse, unexplained failures in the field.  Of course you
 and I would avoid all the pitfalls at the start. :-)

It's no worse than having standard types with loosely defined
sizes. That's part of the price for working that close to the machine.

   mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variable declaration

2005-02-10 Thread Nick Coghlan
Antoon Pardon wrote:
Well it seems you have some fair points. I'll just stop here stating
that I would like to have it, even if it proved to be slower. Speed
is not that big a factor in the things I write.
Oh, certainly. I wasn't suggesting the speed hit was enough to kill the idea - I 
was just pointing it was something that you would use when correctness and being 
explicit was considered more important than a small price in speed. And if the 
name check got optimised out like an assert does. . . Hey, that gives me an idea 
(see below).

I just would like
to ask a question relating semantics. Supose the following code.
x = 42
def f():
  x := 21   #  or x .= 42  I don't remember what you used exactly
Alex used ':=' in a couple of examples, but you'll have to ask him his 
reasons.
I used '.=' instead mainly because I think colons are ugly, but also because 
':=' has the ability to trigger confusion due to its slightly different use in 
those languages which use it for assignment (Eiffel and Pascal come to mind. . . 
since Pascal uses it, I guess Delphi does too).

What do you feel should happen. I can think of two possibilities.
1) It raises an exception because x is not locally bound.
2) it prints 21.
I think the second option would be the more interesting one as
it would allow to get rid of the global statement and it would
allow for rebinding names within nested scopes.
I was thinking of the simpler version, with x .= 21 meaning roughly:
  assert x or True # This will blow up if x fails to resolve
  x = 21
The assertion would then blow up in your example (because x is an as yet unbound 
local variable). To my mind, this follows the principle of least surprise.

I think the globals issue is better handled via the generic objects PEP, with an 
alternate constructor that allows the generic object to be used to alter an 
existing dictionary. Apply the trick to globals() and you're done.

And if Python were to ever acquire some sort of 'scope()' function to allow 
programmatic access to scopes other than globals, generic objects would work for 
using those, too.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


passing arguments like -JOB

2005-02-10 Thread John Leslie
I am porting a script from Korn Shell to python and want to pass named
parameters like -JOB 123456 -DIR mydir

I can get it to work passing --JOB and --DIR but not -JOB and -DIR

Any ideas?

Current code :

try:
options, xarguments = getopt.getopt(sys.argv[1:], '', ['JOB=',
'DIR=', 'ERR=', 'GRP=', 'TST=', 'JNM=', 'DAT=',])
except getopt.error:
print 'Error: You tried to use an unknown option'
sys.exit(1)
JOB = ''
for o,a in options[:]:
print 'here2'
print o
print a
if o == '--JOB':
   JOB = a
   print JOB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hard_decoding

2005-02-10 Thread John Lenton
On Wed, Feb 09, 2005 at 05:22:12PM -0700, Tamas Hegedus wrote:
 Hi!
 
 Do you have a convinient, easy way to remove special charachters from 
 u'strings'?
 
 Replacing:
 ÀÁÂÃÄÅ= A
 èéêë  = e
 etc.
 'L0xe1szl0xf3' = Laszlo
 or something like that:
 'L\xc3\xa1szl\xc3\xb3' = Laszlo

for the examples you have given, this works:

from unicodedata import normalize

def strip_composition(unichar):

Return the first character from the canonical decomposition of
a unicode character. This wil typically be the unaccented
version of the character passed in (in Latin regions, at
least).

return normalize('NFD', unichar)[0]

def remove_special_chars(anystr):

strip_composition of the whole string

return ''.join(map(strip_composition, unicode(anystr)))

for i in ('ÀÁÂÃÄÅ', 'èéêë',
  u'L\xe1szl\xf3',
  'L\xc3\xa1szl\xc3\xb3'):
print i, '-', remove_special_chars(i)

produces:

ÀÁÂÃÄÅ - AA
èéêë - 
László - Laszlo
László - Laszlo

although building a translation mapping is, in general, faster. You
could use the above to build that map automatically, like this:

def build_translation(sample, table=None):

Return a translation table that strips composition characters
out of a sample unicode string. If a table is supplied, it
will be updated.

assert isinstance(sample, unicode), 'sample must be unicode'
if table is None:
table = {}
for i in set(sample) - set(table):
table[ord(i)] = ord(strip_composition(i))
return table

this is much faster on larger strings, or if you have many strings,
but know the alphabet (so you compute the table once). You might also
try to build the table incrementally,

for i in strings:
i = i.translate(table)
try:
i.encode('ascii')
except UnicodeEncodeError:
table = build_translation(i, table)
i = i.translate(table)
stripped.append(i)

of course this won't work if you have other, non-ascii but
non-composite, chars in your strings.

-- 
John Lenton ([EMAIL PROTECTED]) -- Random fortune:
El que está en la aceña, muele; que el otro va y viene. 


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: A great Alan Kay quote

2005-02-10 Thread alex23

jfj wrote:
 Bah. My impressions from the interview was there are no good
 languages anymore. In my time we made great languages, but today
 they all suck. Perl for example

That was kind of what I took from it as well. Don't get me wrong, I've
a lot of respect for Kay's contributions...he just doesn't understand
that there's *more* to a language than it's adherence to his ideas of
'best'. His arguments are literally academic.

Decrying contemporary choices for their pop nature kinda sounds like
the ugly kid devaluing the importance of the school dance.

It just wasn't fit enough to survive, Alan. Let it go.

- alex23

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


pyclbr

2005-02-10 Thread Fernando San Martín Woerner
Hi guys!

i'm using pycblr to implement a class browser for my app, i got some
issues about it:

i did:

dict = pyclbr.readmodule(name, [dir] + sys.path)

but  this only works one time, i mean if module name is changed and
some class were added or removed i can't see any changes even if i
execute readmodule again.

any idea?, thanks in advance


-- 
Fernando San Martn Woerner
Jefe de Informtica
Galilea S.A.

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


some question about tp_basicsize

2005-02-10 Thread Dmitry Belous
Hi, All

I use C++ to create new types(inherited from PyTypeObject)
and objects(inherited from PyObject) and virtual
destructor to destroy objects. sizeof() is different
for different objects and therefore i don't know what i must do
with tp_basicsize.

Will the following source code work?
Must i set tp_basicsize to right size? (Can I use zero
for tp_basicsize?)

static void do_instance_dealloc(PyObject* obj) {
  if(obj-ob_type == mytype_base)
delete static_castmyobject_base*(obj);
}

PyTypeObject mytype_base = {
...
  0, /*tp_basicsize*/ /*i don't know size of object*/
...
  do_instance_dealloc, /*tp_dealloc*/
...
};

class myobject_base : public PyObject {
public:
  myobject_base() : ob_type(mytype_base) {}
  virtual ~myobject_base() {}
};

class myobject_specific : public myobject_base {
public:
  std::string name;
  myobject_specific() : myobject_base() {}
};

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


Re: variable declaration

2005-02-10 Thread Antoon Pardon
Op 2005-02-10, Nick Coghlan schreef [EMAIL PROTECTED]:
 Antoon Pardon wrote:
 Well it seems you have some fair points. I'll just stop here stating
 that I would like to have it, even if it proved to be slower. Speed
 is not that big a factor in the things I write.

 Oh, certainly. I wasn't suggesting the speed hit was enough to kill the idea 
 - I 
 was just pointing it was something that you would use when correctness and 
 being 
 explicit was considered more important than a small price in speed. And if 
 the 
 name check got optimised out like an assert does. . . Hey, that gives me an 
 idea 
 (see below).

 I just would like
 to ask a question relating semantics. Supose the following code.
 
 x = 42
 
 def f():
   x := 21   #  or x .= 42  I don't remember what you used exactly

 Alex used ':=' in a couple of examples, but you'll have to ask him his 
 reasons.

 I used '.=' instead mainly because I think colons are ugly, but also because 
 ':=' has the ability to trigger confusion due to its slightly different use 
 in 
 those languages which use it for assignment (Eiffel and Pascal come to mind. 
 . . 
 since Pascal uses it, I guess Delphi does too).

I don't think that would be a big issue. Python uses '=' also
differently from a number of languages. My preference would
currently be for ':=' because I have the impression that if
you don't leave spaces the period in '.=' tends to be obscured.

  x.=42   vsx:=42

seems a clear win for the second IMO.

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


Re: Testing conditions.

2005-02-10 Thread Nick Coghlan
Ray Gibbon wrote:
Before I resign myself to the inevitable, 'that's the way it is - get used
to it', I'd just like to scratch it once.  But, before I try walking on very
thin ice, I want to ask whether there are expectations of some future
changes which address these issues?
I note PEP 3000 is silent on this matter, and PEP 315, though related, is
not relevant.
The nicest idea I've seen along these lines is:
  if expr as name:
pass
  elif expr as name:
pass
  else:
pass
and
  while expr as name:
pass
It's based on the idea of using 'as' to name caught exceptions in Python 3k 
(which is in turn based on the use of as for renaming in import statements)

However, like allowing assignment, this approach breaks down as soon the thing 
you want bound and the condition you want to test aren't the same, and then you 
have to switch back to the 'bind before test' approach.

Which means a general solution has to allow *three* parts, not two:
1. A conditional expression
And optionally:
2. A subexpression to be named
3. The name for the subexpression
That is, something like:
  if expr using expr as name:
pass
  elif expr using expr as name:
pass
  else:
pass
and
  while expr using expr as name:
pass
(In the degenerate case where the condition is the thing we want named, it may 
be possible to make the 'using' clause optional. If not, then the first 
expression is simply name)

But such a solution involves an entirely new keyword and there's the eternal 
question of whether the feature is needed *enough* to justify complicating the 
syntax. The while case isn't good justification, since such while loops can 
usually be converted to a generator function and a pair of for loops easily 
enough. if/elif is slightly more promising as a motivation - having to convert 
to nested if statements if you discover you need access to some part of the 
condition test is a pain and the nested if's are harder to read that if/elif. 
How common is that situation in reality, though? I can't think of a case where 
I've had to use more than one nested if statement due to the 'problem' of not 
being to do an embedded assignment.

*shrug* The issue has never really bothered me in practice. Heck, I often don't 
use nested assignment even in C, since the buggers can be so damn hard to read. 
That's mainly due to the = vs == problem though :)

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Loop in list.

2005-02-10 Thread Jim
I assume this is one of the addons for Python.  I know that there
is a great deal of stuff out there available for Python that does
some of the stuff that I am looking at, but I am interested in
learning to use Python.  When I want to get faster and more
general, I will get some of this stuff or use a different language.

Thanks for the help.

Jim

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


implementing singleton class at the module level

2005-02-10 Thread Satchidanand Haridas
Hi,
I was looking at ways to implement a Singleton class. I saw some methods 
described on the PythonSingleton wiki 
(http://c2.com/cgi/wiki?PythonSingleton). I implemented the following.

code
module: A.py
--
class Singleton:
   def __init__(self):
  #do something
singleton_instance = Singleton()

Then in any other module (eg B.py):
from A import singleton_instance
/code
singleton_instance will be created only once and can be reused in other 
modules. But is this ok? I am trying to figure out what are the 
disadvantages of using the above method. I would appreciate any 
comments. thanks.

regards,
Satchit
--
http://mail.python.org/mailman/listinfo/python-list


Re: That horrible regexp idiom

2005-02-10 Thread Nick Coghlan
Stephen Thorne wrote:
Hi,
import re
foo_pattern = re.compile('foo')
' m = foo_pattern.search(subject)
' if m:
'pass
' else:
'pass
Heh. Did you see Ray Gibbons's 'Testing Conditions' post before you sent 
this?
I knew if/elif was a much better argument in favour of embedded assignment than 
while loops are.

Anyway, here's the above using my idle thought from that the thread.:
  if m using foo_pattern.search(subject) as m:
pass
  else:
pass
And the 'alternative patterns' case:
  if m using foo_pattern.search(subject) as m:
pass
  elif m using bar_pattern.search(subject) as m:
pass
  else:
pass
(Y'know, I'm pretty sure the impetus was regexp matching the *last* time 
embedded assignment came up. . .)

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: passing arguments like -JOB

2005-02-10 Thread Duncan Booth
John Leslie wrote:

 I am porting a script from Korn Shell to python and want to pass named
 parameters like -JOB 123456 -DIR mydir
 
 I can get it to work passing --JOB and --DIR but not -JOB and -DIR
 
 Any ideas?
 
Unfortunately (for you), I think you will find most or all of the existing 
ways to parse command line options in Python follow the POSIX convention 
for arguments, i.e. single letter options are introduced with a single - 
and multi-letter options are introduced with --.

My guess is that if you can't change whatever generates the command lines 
to conform to this convention you will have to write your own code to do 
the processing.

Alternatively you might get by by hacking the command line in your Python 
code:

   for i, opt in enumerate(sys.argv):
   if opt in ('-JOB','-DIR', '-ERR', '-GRP', '-TST', '-JNM', '-DAT'):
  sys.argv[i] = '-'+opt

   ... and then use getopt or optparse here ...

It isn't pretty, but so long as those values don't turn up elsewhere in the 
command line it ought to work.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: deepcopy chokes with TypeError on dynamically assigned instance method

2005-02-10 Thread Nick Coghlan
5ÛHH575-UAZWKVVP-7H2H48V3 wrote:
class Foo(list):
Foo
def __init__(self, l=[]):
Change this too:
  def __init__(self, l=None):
if l is None: l = []
And see if your problem goes away.
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reportlab and Barcodes

2005-02-10 Thread Jaime Wyant
That looks cleaner than mine.  I had to do this -

# Register the barcode true-type-font
# Don't want to push the font out to everyone in the office...
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont( TTFont( 'barcode',
r'c:\inetpub\wwwroot\barcode\fre3of9x.ttf'))

# 'c' is the canvas
c.setFont( barcode, 40  )
c.drawString( x * inch, y * inch, text )

jw

On Wed, 09 Feb 2005 11:25:22 -0800 (PST), Josh [EMAIL PROTECTED] wrote:
 One of the users on the Reportlabs mailing list was kinda enough to
 offer me the solution.. A simple call to the drawOn function, e.g.:
 
 bc = code39.Standard39(123,xdim = .015*inch)
 x = 6*inch
 y = -5*inch
 bc.drawOn(canvas,x,y)
 
 --
 http://mail.python.org/mailman/listinfo/python-list

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


lambda and for that matter goto not forgetting sugar

2005-02-10 Thread Philip Smith
I've read with interest the continuing debate about 'lambda' and its place 
in Python.

Just to say that personally I think its an elegant and useful construct for 
many types of programming task (particularly number theory/artificial 
intelligence/genetic algorithms)

I can't think why anyone would be proposing to do away with it.  Sometimes 
an anonymous function is just what you need and surely it just reflects the 
python philosophy of everything being an object (in this case a code 
object).

Mind you my particular programming interest is algorithmic programming, I 
have no idea whether Lambda is of any relevance to eg client server 
programming.

For that matter I would find implementing the classical algorithms far 
easier if python had 'goto' (I'll wait for the guffaws to subside before 
mentioning that no lesser guru than Donald Knuth writes his algorithms that 
way - naturally so because it reflects what the machine does at the base 
level).  Please don't suggest using try/except as an alternative as the 
ugliness and inappropriateness of that to achieve a simple 'goto' is utterly 
out of keeping with the 'cleanliness' which is Python's most appealing 
feature.

(And yes - I do like spaghetti but only to eat, not in my code).

Following on naturally from that last point I would also like to 'deprecate' 
the use of the expression 'syntactic sugar' on these pages.  All high level 
languages (Python included) are nothing but syntactic sugar designed to 
conceal the ugliness of what actually gets sent to the CPU to make it all 
happen.

On a positive note though - I have found this newsgroup an invaluable aid to 
learning Python over the last few weeks and the response to queries has been 
as quick as it has been informative.

I've decided I like Python - in fact I think of it more as syntactic maple 
syrup than sugar.

Competition:  Has anyone found anything you can't do in the language?

regards to all

Phil 


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


OT: Anyone want a GMail account?

2005-02-10 Thread Chris Cioffi
I've got 50 so if you want a GMail invite reply directly to me and
I'll send our an invite.

Chris Cioffi
-- 
It is our responsibilities, not ourselves, that we should take
seriously. -- Peter Ustinov
-- 
http://mail.python.org/mailman/listinfo/python-list


is there a safe marshaler?

2005-02-10 Thread Irmen de Jong
Pickle and marshal are not safe. They can do harmful
things if fed maliciously constructed data.
That is a pity, because marshal is fast.
I need a fast and safe (secure) marshaler.
Is xdrlib the only option?
I would expect that it is fast and safe because
it (the xdr spec) has been around for so long.
Or are there better options (perhaps 3rd party libraries)?
Thanks
Irmen.
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question

2005-02-10 Thread Peter Hansen
Dan Perl wrote:
I can't say that is not part of the reason, but the example in the OP is a 
clear illustration of cases where something like an increment/decrement 
operator would be very useful.  
The OP didn't show how he was using the while (n--) at all,
so it can hardly be a clear illustration of how it's useful.
In fact, it's even possible it was entirely unnecessary in
the original code...  at this point I'd be really interested
in seeing just what code is inside the while statement, and
possibly what follows it (if the following code relies on the
value of n).
OTOH, I was thinking of saying in my 
previous posting that I prefer
for n in range(start, 0, -1):
to
n = start
while (n--)
I think that the first form is more readable, although that may be just me. 
I would actually even prefer the 'for' statement in C to the 'while' 
statement:
for (n=start; n=0; n--) 
I'm not sure if it's just picking nits, but I'd like to
point out that neither of your alternatives is actually
equivalent to the while (n--) form...  nor was Jeff
Shannon's attempt (in that case it leaves the loop with
n equal to 0, not -1).
The fact that it's so easy to get confused with post-decrement
is perhaps an excellent reason to keep it out of Python.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: That horrible regexp idiom

2005-02-10 Thread Duncan Booth
Nick Coghlan wrote:

 I knew if/elif was a much better argument in favour of embedded
 assignment than while loops are.
 

I know I'm going to regret posting this, but here is an alternative, very 
hackish way to do all those things people keep asking for, like setting 
variables in outer scopes or doing lots of nested ifs for regex matching or 
simulating passing a local variable by reference.

My excuse for the following code is that was unwell and I think I was 
slightly feverish when I wrote it:

- hack.py ---
import new

def mksetter(baa):
'''Cruel hack to set scoped variables.
baa should be a lambda which accesses the variable you wish to set.
It must be a local or outer scope variable, not a global
'''
closure = baa.func_closure
name = baa.func_code.co_names[0]
if not isinstance(closure, tuple) or len(closure) != 1:
raise TypeError('''mksetter() argument must be a lambda accessing a 
local or scoped variable''')

def f(v):
a = v
return v
lambda: a

c = f.func_code
newcode = new.code(
c.co_argcount, 1, c.co_stacksize, c.co_flags, c.co_code,
c.co_consts, c.co_names, c.co_varnames, c.co_filename, 'set_'+name,
c.co_firstlineno, c.co_lnotab, (name,), (),
)
return new.function(newcode, f.func_globals,
'set_'+name, None, closure)

if __name__=='__main__':
def set_a_local():
a = 42
print a=,a
set_a = mksetter(lambda: a)
set_a(24)
print set_a
print a=,a

set_a_local()

def set_scoped():
count = 0
set_count = mksetter(lambda: count)
def inc():
set_count(count+1)
for i in range(10):
print count=,count
inc()
print Final value,count

set_scoped()

import re
def silly_regex():
name = re.compile('[a-zA-Z_][a-zA-Z0-9_]*')
number = re.compile('[0-9]+(\\.[0-9]*)?([eE][-+]?[0-9]+)?')

m = None
set_m = mksetter(lambda: m)

for s in 'abc', '2.5e-3', '!':
if set_m(name.match(s)):
print name, m.group(0)
elif set_m(number.match(s)):
print number, m.group(0)
else:
print no match, m, s

silly_regex()

- end of hack.py 

Sorry.

If anyone actually feels tempted to use this: I take no responsibility for 
the results. I can't particularly see why future versions of Python would 
change to stop it working, but they could, and of course it is definitely a 
'C-Python only' trick.


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


Re: is there a safe marshaler?

2005-02-10 Thread Pierre Barbier de Reuille
Irmen de Jong a écrit :
Pickle and marshal are not safe. They can do harmful
things if fed maliciously constructed data.
That is a pity, because marshal is fast.
I need a fast and safe (secure) marshaler.
Is xdrlib the only option?
I would expect that it is fast and safe because
it (the xdr spec) has been around for so long.
Or are there better options (perhaps 3rd party libraries)?
Thanks
Irmen.
What exactly do you mean by safe ? Do you want to ensure your objects 
cannot receive corrupted data ? Do you want to ensure no code will be 
evaluated during the unmarshalling ?

Please, be more precise,
Pierre
--
http://mail.python.org/mailman/listinfo/python-list


Re: convert list of tuples into several lists

2005-02-10 Thread Nick Coghlan
Steven Bethard wrote:
Peter Hansen wrote:
Steven Bethard wrote:
Diez B. Roggisch wrote:
zip(*[(1,4),(2,5),(3,6)])

While this is also the approach I would use, it is worth noting that 
Guido thinks of this as an abuse of the argument passing machinery:

http://mail.python.org/pipermail/python-dev/2003-July/037346.html

I'm not sure that's the same thread I already read where he
dissed zip like that, but what I'm wondering is what is the
alternative?  Is there an equally elegant approach that
doesn't abuse the argument passing machinery?

I know I found it in another thread before.  I think he's said it a few 
times.

Personally, I wish that, if we're not to use zip like this, that Python 
would provide a builtin 'unzip' to do the corresponding thing.
I never really got the impression that Guido was particularly *strongly* opposed 
to this use of the extended call syntax. Merely that he was concerned that it 
would break down if the relevant list turned out to be large (that is, the abuse 
is using *args with a list when the list may turn out to be large, not a problem 
specifically with using the star syntax with zip()).

Maybe he's been more explicit somewhere, and I just never saw it.
Anyway, his concern seems justified, as my understanding is that func(*iterable) 
is roughly equivalent to func(*tuple(iterable)), which can be rather expensive 
when the iterable is a long list of tuples.

So zip(*zip(*iterable)) is actually zip(*tuple(zip(*tuple(iterable. That's 
potentially an awful lot of data copying for an identity operation :)

Anyway, I think it does make a decent case for an itertools.iunzip or some such 
beast.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question

2005-02-10 Thread Dan Perl

Peter Hansen [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Dan Perl wrote:
 OTOH, I was thinking of saying in my previous posting that I prefer
 for n in range(start, 0, -1):
 to
 n = start
 while (n--)
 I think that the first form is more readable, although that may be just 
 me. I would actually even prefer the 'for' statement in C to the 'while' 
 statement:
 for (n=start; n=0; n--)

 I'm not sure if it's just picking nits, but I'd like to
 point out that neither of your alternatives is actually
 equivalent to the while (n--) form...  nor was Jeff
 Shannon's attempt (in that case it leaves the loop with
 n equal to 0, not -1).

You're right in your nit picking.  I have to go back to using some C/C++ and 
Java also, I don't want to forget them completely. 


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


Re: sre is broken in SuSE 9.2

2005-02-10 Thread Denis S. Otkidach
On 10 Feb 2005 03:59:51 -0800
Serge Orlov [EMAIL PROTECTED] wrote:

  On all platfroms \w matches all unicode letters when used with flag
  re.UNICODE, but this doesn't work on SuSE 9.2:
[...]
 I can get the same results on RedHat's python 2.2.3 if I pass re.L
 option, it looks like this option is implicitly set in Suse.

Looks like you are right:

 import re
 re.compile(ur'\w+', re.U).match(u'\xe4')
 from locale import *
 setlocale(LC_ALL, 'de_DE')
'de_DE'
 re.compile(ur'\w+', re.U).match(u'\xe4')
_sre.SRE_Match object at 0x40375560

But I see nothing related to implicit re.L option in their patches and
the sources themselves are the same as on other platforms.  I'd prefer
to find the source of problem.

-- 
Denis S. Otkidach
http://www.python.ru/  [ru]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda and for that matter goto not forgetting sugar

2005-02-10 Thread Nick Coghlan
Philip Smith wrote:
I've read with interest the continuing debate about 'lambda' and its place 
in Python.

Just to say that personally I think its an elegant and useful construct for 
many types of programming task (particularly number theory/artificial 
intelligence/genetic algorithms)

I can't think why anyone would be proposing to do away with it.  Sometimes 
an anonymous function is just what you need and surely it just reflects the 
python philosophy of everything being an object (in this case a code 
object).
The *concept* is fine, but the current syntax is seriously ugly, and the keyword 
used creates false expectations for those familiar with what lambda calculus 
actually *is*.

If the lambda syntax were a new proposal to be added to the language now, it 
would never be accepted.

Unfortunately, its existence tends to stymie efforts to come up with a 
*Pythonic* way of spelling the same idea. The people who want to get rid of 
lambda completely think coming up with a new spelling is a waste of time - Just 
define the damn function already! is their rallying cry. The people who want 
real lambda calculus complain that they still can't put statements inside 
expressions - they shout Give me real anonymous functions, not this neutered 
junk that restricts me to a single expression!. And, of course, there's always 
someone to complain that supporting a new spelling would violate TOOWTDI - But, 
but, we already have def and lambda, why are you trying to come up with yet 
another way to create a function?.

Anyway, check out AlternateLambdaSyntax on the python.org Wiki if you haven't 
already. For my own part, I'd like a new spelling. Something that is more 
stylistically in line with a genexp would be significantly preferable to the 
status quo (e.g (x*x from (x)) aligns better with (x*x for x in seq) than 
lambda x: x*x does).

Following on naturally from that last point I would also like to 'deprecate' 
the use of the expression 'syntactic sugar' on these pages.  All high level 
languages (Python included) are nothing but syntactic sugar designed to 
conceal the ugliness of what actually gets sent to the CPU to make it all 
happen.
Yup, you're right. But 'syntactic sugar' often isn't used in a negative way - 
it's more descriptive than anything. It's any language change that's designed to 
make common idioms easier to use.

Cheers,
Nick.
No comment on the goto thing ;)
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python as capable as Perl for sysadmin work?

2005-02-10 Thread Nick Coghlan
Richie Hindle wrote:
[Steve]
Was it INTERCAL that had the COMEFROM Line number statement instead of
GOTO? I REALLY like the idea of a COMEFROM statement. I think python should
have a COMEFROM statement

It does - see http://entrian.com/goto/
(In case you doubt it: yes, it works, but note that it doesn't work at the
interactive prompt, only in a real source file.)
(The fact that I felt obliged to add the first paragraph on that page is
the funniest part of the whole thing.  I really did have people genuinely
thanking me for the module, asking for features, asking for help with
using it, and so on.)
That module is. . .
 a) impressive
 b) very, very, wrong
 c) both a) and b)
I think I'm voting for c). . .
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Two questions: python/Net(c#) and Win Raw sockets?

2005-02-10 Thread Simon Roses Femerling



Hi all,

First Question: Anyone has experience with any of 
this Python/Net implementations:

- PythonNet
- IronPython
- Boo

Which is best for using in a c# app for embedding 
and extending ?

Second Question: I know that python 2.3 _socket.dll 
was not compile with raw socket support on windows. Anyone have a compile 
version or know
any solution for raw socket on windows for python 
2.3 or 2.4 or I must compile my own version of _socket.dll ?

Thx

Sincerely,

SRF


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

Re: variable declaration

2005-02-10 Thread Nick Coghlan
Antoon Pardon wrote:
I don't think that would be a big issue. Python uses '=' also
differently from a number of languages. My preference would
currently be for ':=' because I have the impression that if
you don't leave spaces the period in '.=' tends to be obscured.
  x.=42   vsx:=42
seems a clear win for the second IMO.
I'm forced to agree. So I'll use the latter syntax if I end up writing anything 
further about rebinding :)

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: convert list of tuples into several lists

2005-02-10 Thread Peter Hansen
Nick Coghlan wrote:
I never really got the impression that Guido was particularly *strongly* 
opposed to this use of the extended call syntax. Merely that he was 
concerned that it would break down if the relevant list turned out to be 
large (that is, the abuse is using *args with a list when the list may 
turn out to be large, not a problem specifically with using the star 
syntax with zip()).
Is there some unexpected limit to the number of arguments that may be
passed with the *args format (say, 256 function arguments maximum are
supported by Python), or is this concern just because of the raw
memory inherently used by the tuple?
In other words, if one is confident that one can whip tuples of the
required size around without using up available memory, would there
still be such a concern about the *args abuse?
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: wxgrid multiline cell editor

2005-02-10 Thread jean-michel
James [EMAIL PROTECTED] a écrit dans le message de
news:[EMAIL PROTECTED]
 wxpython 2.5.3
 anyone know how to make a multiline cell editor for wxgrid?

Hello,

You can do that by a wxGridCellAutoWrapStringEditor.
You can test it by modifying GridSimple.py in the demo by adding (at line 24
in my version):
self.SetRowSize(1, 45)
self.SetCellEditor(1, 1, wxGridCellAutoWrapStringEditor())
Save it and now, when you launch the gridsimple in the demo (it's in core
windows control), you can enter multiple lines in the cell containing
Another cell. It works in 2.4.2.4. I think it should also in 2.5.

I join the whole program.
Have fun.
++jm

#---
from wxPython.wx import *
from wxPython.grid import *
from wxPython.lib.mixins.grid import wxGridAutoEditMixin

#---

class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin):
def __init__(self, parent, log):
wxGrid.__init__(self, parent, -1)
##wxGridAutoEditMixin.__init__(self)
self.log = log
self.moveTo = None

EVT_IDLE(self, self.OnIdle)

self.CreateGrid(25, 25) #, wxGrid.wxGridSelectRows)
##self.EnableEditing(False)

# simple cell formatting
self.SetColSize(3, 200)
self.SetRowSize(4, 45)
self.SetCellValue(0, 0, First cell)
self.SetCellValue(1, 1, Another cell)
self.SetRowSize(1, 45)
self.SetCellEditor(1, 1, wxGridCellAutoWrapStringEditor())
self.SetCellValue(2, 2, Yet another cell)
self.SetCellValue(3, 3, This cell is read-only)
self.SetCellFont(0, 0, wxFont(12, wxROMAN, wxITALIC, wxNORMAL))
self.SetCellTextColour(1, 1, wxRED)
self.SetCellBackgroundColour(2, 2, wxCYAN)
self.SetReadOnly(3, 3, True)

self.SetCellEditor(5, 0, wxGridCellNumberEditor(1,1000))
self.SetCellValue(5, 0, 123)
self.SetCellEditor(6, 0, wxGridCellFloatEditor())
self.SetCellValue(6, 0, 123.34)
self.SetCellEditor(7, 0, wxGridCellNumberEditor())

self.SetCellValue(6, 3, You can veto editing this cell)


# attribute objects let you keep a set of formatting values
# in one spot, and reuse them if needed
attr = wxGridCellAttr()
attr.SetTextColour(wxBLACK)
attr.SetBackgroundColour(wxRED)
attr.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD))

# you can set cell attributes for the whole row (or column)
self.SetRowAttr(5, attr)

self.SetColLabelValue(0, Custom)
self.SetColLabelValue(1, column)
self.SetColLabelValue(2, labels)

self.SetColLabelAlignment(wxALIGN_LEFT, wxALIGN_BOTTOM)

#self.SetDefaultCellOverflow(False)
#r = wxGridCellAutoWrapStringRenderer()
#self.SetCellRenderer(9, 1, r)

# overflow cells
self.SetCellValue( 9, 1, This default cell will overflow into
neighboring cells, but not if you turn overflow off.);
self.SetCellSize(11, 1, 3, 3);
self.SetCellAlignment(11, 1, wxALIGN_CENTRE, wxALIGN_CENTRE);
self.SetCellValue(11, 1, This cell is set to span 3 rows and 3
columns);


editor = wxGridCellTextEditor()
editor.SetParameters('10')
self.SetCellEditor(0, 4, editor)
self.SetCellValue(0, 4, Limited text)


# test all the events
EVT_GRID_CELL_LEFT_CLICK(self, self.OnCellLeftClick)
EVT_GRID_CELL_RIGHT_CLICK(self, self.OnCellRightClick)
EVT_GRID_CELL_LEFT_DCLICK(self, self.OnCellLeftDClick)
EVT_GRID_CELL_RIGHT_DCLICK(self, self.OnCellRightDClick)

EVT_GRID_LABEL_LEFT_CLICK(self, self.OnLabelLeftClick)
EVT_GRID_LABEL_RIGHT_CLICK(self, self.OnLabelRightClick)
EVT_GRID_LABEL_LEFT_DCLICK(self, self.OnLabelLeftDClick)
EVT_GRID_LABEL_RIGHT_DCLICK(self, self.OnLabelRightDClick)

EVT_GRID_ROW_SIZE(self, self.OnRowSize)
EVT_GRID_COL_SIZE(self, self.OnColSize)

EVT_GRID_RANGE_SELECT(self, self.OnRangeSelect)
EVT_GRID_CELL_CHANGE(self, self.OnCellChange)
EVT_GRID_SELECT_CELL(self, self.OnSelectCell)

EVT_GRID_EDITOR_SHOWN(self, self.OnEditorShown)
EVT_GRID_EDITOR_HIDDEN(self, self.OnEditorHidden)
EVT_GRID_EDITOR_CREATED(self, self.OnEditorCreated)



def OnCellLeftClick(self, evt):
self.log.write(OnCellLeftClick: (%d,%d) %s\n %
   (evt.GetRow(), evt.GetCol(), evt.GetPosition()))
evt.Skip()

def OnCellRightClick(self, evt):
self.log.write(OnCellRightClick: (%d,%d) %s\n %
   (evt.GetRow(), evt.GetCol(), evt.GetPosition()))
evt.Skip()

def OnCellLeftDClick(self, evt):
self.log.write(OnCellLeftDClick: (%d,%d) %s\n %
   (evt.GetRow(), evt.GetCol(), evt.GetPosition()))
evt.Skip()

def OnCellRightDClick(self, evt):

¿ù1%´ë ¹ýÁ¤±Ý¸®Áؼö ÃÖ°í5000¸¸¿ø±îÁö!

2005-02-10 Thread ÀÌÇÏ´Ã15
Title: www.kc-loan.com













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

Re: sre is broken in SuSE 9.2

2005-02-10 Thread Daniel Dittmar
Denis S. Otkidach wrote:
On all platfroms \w matches all unicode letters when used with flag
re.UNICODE, but this doesn't work on SuSE 9.2:
I think Python on SuSE 9.2 uses UCS4 for unicode strings (as does 
RedHat), check sys.maxunicode.

This is not an explanation, but perhaps a hint where to look.
Daniel
--
http://mail.python.org/mailman/listinfo/python-list


python equivalent to access reports

2005-02-10 Thread flupke
Hi,
a lot of applications here a made with access. Tables, forms, reports 
and the like. Now i rather use Python to do this but i'm not sure how to 
proceed. I can use wxPython for a gui via wxGlade for rapid testing and 
design (forms), MySQL as db (tables) but the report part is what's 
bothering me.
The only semi easy way that i see is by making html files with the 
results in and then opening a browser to display the result.
But this would lack nice printing as there is no way to cleanly start a 
new page.

Any other ideas?
Thanks,
Benedict
--
http://mail.python.org/mailman/listinfo/python-list


Re: python equivalent to access reports

2005-02-10 Thread flupke
flupke wrote:
Hi,
a lot of applications here a made with access. Tables, forms, reports 
and the like. Now i rather use Python to do this but i'm not sure how to 
proceed. I can use wxPython for a gui via wxGlade for rapid testing and 
design (forms), MySQL as db (tables) but the report part is what's 
bothering me.
The only semi easy way that i see is by making html files with the 
results in and then opening a browser to display the result.
But this would lack nice printing as there is no way to cleanly start a 
new page.

Any other ideas?
Thanks,
Benedict
I just saw a reference too http://www.reportlab.org/
This might do what i want.
Benedict
--
http://mail.python.org/mailman/listinfo/python-list


Re: sre is broken in SuSE 9.2

2005-02-10 Thread Denis S. Otkidach
On Thu, 10 Feb 2005 16:23:09 +0100
Daniel Dittmar [EMAIL PROTECTED] wrote:

 Denis S. Otkidach wrote:
 
  On all platfroms \w matches all unicode letters when used with flag
  re.UNICODE, but this doesn't work on SuSE 9.2:
 
 I think Python on SuSE 9.2 uses UCS4 for unicode strings (as does 
 RedHat), check sys.maxunicode.
 
 This is not an explanation, but perhaps a hint where to look.

Yes, it uses UCS4.  But debian build with UCS4 works fine, so this is
not a problem.  Can --with-wctype-functions configure option be the
source of problem?

-- 
Denis S. Otkidach
http://www.python.ru/  [ru]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reportlab and Barcodes

2005-02-10 Thread Josh
Damjan,

Code39 here refers to part of the Barcode Extensions available to
Reportlabs. It can be imported as such

from reportlab.extensions.barcode import code39

Josh

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


Re: Datatype of non-negative values

2005-02-10 Thread Dirk Hagemann
A result smaller than 0 should be just invalid.

I'd like to work with try and except like this:
value=20
try:
value=value-23
except:
print 'value is smaller than 23'

Now it should run into the except.

Dirk Hagemann


Larry Bates [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]...
 What exactly do you want to happen when result
 would be negative?  I'll guess be zero:
 
 pseudocode:
 
 x=value
 x=max(x-something, 0)
 
 That way if it goes negative, it sticks to zero.
 
 Larry Bates
 
 
 Dirk Hagemann wrote:
  Hi,
  
  Is there a datatype in python which allows no negative values? I
  subtract several times something from a value and I don't want to chek
  everytime if this value is still bigger or equal 0.
  
  Thanks for help!
  Dirk Hagemann
-- 
http://mail.python.org/mailman/listinfo/python-list


Variable size plot symbols, variable hue plot colors in Python (MatPlotLib) ?

2005-02-10 Thread Dr. Colombes
Using MatPlotLib plot function, is there a way to get variable size
plot symbols?  For example, using symbol strings like 'o' (circle), 's'
(square), 'x' (cross), etc., is there a way to specify other plot
symbols such a small circle, Medium square, LARGE cross, etc.?

Similarly, using the MatPlotLib plot function, is there a way to get
variable hue (RGB-specified) plot colors?  For example, using symbol
strings like 'b' (blue), 'g' (green), 'red' (red), etc., is there a way
to specify other colors such as light blue, dark green, pink, etc.?

Or perhaps is there some other Python MatPlotLib or other Python module
functions that allow variable size plot symbols and variable hue plot
colors in Python ?

Thank you for your suggestions.

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


goto, cls, wait commands

2005-02-10 Thread BOOGIEMAN
I've just finished reading Python turtorial for non-programmers
and I haven't found there anything about some usefull commands I used in
QBasic. First of all, what's Python command equivalent to QBasic's goto ?
Secondly, how do I clear screen (cls) from text and other content ?
And last, how do I put program to wait certain amount of seconds ?
If I remeber correctly I used to type Wait 10 and QBasic waits 
10 seconds before proceeding to next command.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: negative integer division

2005-02-10 Thread Mark Jackson
[EMAIL PROTECTED] (John Machin) writes:
 [EMAIL PROTECTED] (Mark Jackson) wrote in message news:[EMAIL PROTECTED]...
  
  A:  42
  
  Q:  What multiple of 7 did I add to the critical expression in the Zeller
  algorithm so it would remain nonnegative for the next few centuries?
 
 What are you calling the Zeller algorithm, and what is the critical
 expression?

A C function in calendar.c, encountered in the source code for xvtdl:

int zeller (month, day, year)
int month, day, year;
{
  int century;
  month -= 2;   /* Years start on March 1 so adjust standard date */
  if (month  1) {
 month += 12;
 year--;
  }
  century = year / 100;
  year = (int)year % (int)100;
  return ((int)((2.6 * month - 0.1) + day + year + year / 4  + century / 4 - 
century * 2) % 7);
}

The expression upon which % 7 acts is negative when year is small.
This caused errors beginning in March 2000; which could be deferred by
adding a suitably-large multiple of 7 to the expression.  The choice
was obvious. :-)

 I've no doubt you came across a stuffed-up date-to-days calculation
 routine and fixed it, but it's a bit unfair to lumber Zeller with the
 blame. If it was a days-to-date routine, then Zeller is not even
 standing next to the real target.

Fair enough, although I'm not responsible for having named the function
(which appears to date from 1991).  The original author is identified
in the code (available at
http://www.alumni.caltech.edu/~mjackson/xvtdl.html) and is findable via
the Web; you might take the matter up with him.

-- 
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
People who write obscurely are either unskilled in writing
or up to mischief.  - Sir Peter Medawar


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


Re: goto, cls, wait commands

2005-02-10 Thread Fouff
BOOGIEMAN a écrit :
I've just finished reading Python turtorial for non-programmers
and I haven't found there anything about some usefull commands I used in
QBasic. First of all, what's Python command equivalent to QBasic's goto ?
I had a professor that told me that using goto in prog is that there is 
a mistake in the algorythm.
If I remember, I think there is no goto instruction in python !

Secondly, how do I clear screen (cls) from text and other content ?
I don't understand well what you exactly want to do. Can you explain 
more please.

And last, how do I put program to wait certain amount of seconds ?
If I remeber correctly I used to type Wait 10 and QBasic waits 
10 seconds before proceeding to next command.
import time
   time.sleep(10)
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there a safe marshaler?

2005-02-10 Thread [EMAIL PROTECTED]
Irmen de Jong wrote:
 Pickle and marshal are not safe. They can do harmful
 things if fed maliciously constructed data.
 That is a pity, because marshal is fast.

I think marshal could be fixed; the only unsafety I'm aware of is that
it doesn't always act rationally when confronted with incorrect input
like bad type codes or truncated input. It only receives instances of
the built-in types and it never executes user code as a result of
unmarshalling.

Perhaps someone would be interested in submitting a patch to the
unmarshalling code? Since this is a security fix we'd even accept a fix
for 2.3.

 I need a fast and safe (secure) marshaler.
 Is xdrlib the only option?
 I would expect that it is fast and safe because
 it (the xdr spec) has been around for so long.

I don't expect that to be particularly fast, since it mostly operates
at Python speed.  I think it could be safe but I would still do a
thorough code review if I were you -- the code is older than my
awareness of the vulnerabilities inherent in this kind of remote data
transfer.

--Guido

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


Re: goto, cls, wait commands

2005-02-10 Thread Duncan Booth
BOOGIEMAN wrote:

 I've just finished reading Python turtorial for non-programmers
 and I haven't found there anything about some usefull commands I used
 in QBasic. First of all, what's Python command equivalent to QBasic's
 goto ?

There isn't one. Why do you think you need this?

 Secondly, how do I clear screen (cls) from text and other
 content ?

That depends on your computer, and how you are running your program.
One way which *might* work is:

   import os
   os.system(cls)

 And last, how do I put program to wait certain amount of
 seconds ? If I remeber correctly I used to type Wait 10 and QBasic
 waits 10 seconds before proceeding to next command.

   import time
   time.sleep(10)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: goto, cls, wait commands

2005-02-10 Thread TZOTZIOY
On Thu, 10 Feb 2005 16:59:04 +0100, rumours say that BOOGIEMAN
[EMAIL PROTECTED] might have written:

Best advice: try to forget QBasic, and try again reading the tutorial.  That, if
your post is serious.  If it isn't, keep reading my reply :)

I've just finished reading Python turtorial for non-programmers
and I haven't found there anything about some usefull commands I used in
QBasic. First of all, what's Python command equivalent to QBasic's goto ?

goto for python:

http://entrian.com/goto/index.html

Please ignore the line in bold red.

Secondly, how do I clear screen (cls) from text and other content ?

Python clears after itself, so you don't need to.  If you insist though,

. import os
. os.system('cls')

That on a windows console.

If on IDLE, try closing the window and reopening it.

And last, how do I put program to wait certain amount of seconds ?
If I remeber correctly I used to type Wait 10 and QBasic waits 
10 seconds before proceeding to next command.

(A serious answer for a change)  Waiting is time related.  So import time and
call the time.sleep function.

Try entering help at a Python prompt.
-- 
TZOTZIOY, I speak England very best.
Be strict when sending and tolerant when receiving. (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: goto, cls, wait commands

2005-02-10 Thread Grant Edwards
On 2005-02-10, BOOGIEMAN [EMAIL PROTECTED] wrote:

 First of all, what's Python command equivalent to QBasic's goto ?

There isn't one.  

One defines functions and calls them. One uses for and while
loops.  One uses list comprehensions.  One uses if/elif/else.

 Secondly, how do I clear screen (cls) from text and other content ?

That depends on the host system.  Under Unix, you can do
os.system('clear').  Or you can use ncurses.  Or you can use
os.system to run the 'tput' command with appropriate parameters
-- see the tput man page.

There's probably some way to do it in Windows as well, but I
don't do windows.

 And last, how do I put program to wait certain amount of
 seconds ?

time.sleep(1) will wait for 1 second.
time.sleep(5.5) will wait for 5.5 seconds.

-- 
Grant Edwards   grante Yow!  Yow! I like my new
  at   DENTIST...
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [noob] Questions about mathematical signs...

2005-02-10 Thread administrata
Steve Holden [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]...
 administrata wrote:
 
  Hi! I'm programming maths programs.
  And I got some questions about mathematical signs.
  
  1. Inputing suqare like a * a, It's too long when I do time-consuming
 things. Can it be simplified?
  
 You mean you have to write a*a*a*a when you want the fourth power? You 
 need the exponentiation operator ** :
 
for i in range(6):
   ...   print 2 ** i
   ...
 1
 2
 4
 8
 16
 32
 
  2. Inputing fractions like (a / b) + (c / d), It's tiring work too.
 Can it be simplified?
  
 Surely you jest. Can you suggest a simplification, or have you come 
 across one in some other language?
 
  3. How can i input root?
  
 Fractional exponents give you roots (sorry about the tiring division):
 
for i in range(1,7):
   ...   print i, 64 ** (1.0/i)
   ...
 1 64.0
 2 8.0
 3 4.0
 4 2.82842712475
 5 2.29739670999
 6 2.0
 
  thx 4 reading :)
 
 regards
   Steve

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


Re: sre is broken in SuSE 9.2

2005-02-10 Thread Fredrik Lundh
Denis S. Otkidach wrote:

  On all platfroms \w matches all unicode letters when used with flag
  re.UNICODE, but this doesn't work on SuSE 9.2:

 I think Python on SuSE 9.2 uses UCS4 for unicode strings (as does
 RedHat), check sys.maxunicode.

 This is not an explanation, but perhaps a hint where to look.

 Yes, it uses UCS4.  But debian build with UCS4 works fine, so this is
 not a problem.  Can --with-wctype-functions configure option be the
 source of problem?

yes.

that option disables Python's own Unicode database, and relies on the C 
library's
wctype.h (iswalpha, etc) to behave properly for Unicode characters.  this isn't 
true
for all environments.

is this an official SuSE release?  do they often release stuff that hasn't been 
tested
at all?

/F 



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


Re: sre is broken in SuSE 9.2

2005-02-10 Thread Serge Orlov
Denis S. Otkidach wrote:
 On 10 Feb 2005 03:59:51 -0800
 Serge Orlov [EMAIL PROTECTED] wrote:

   On all platfroms \w matches all unicode letters when used with
flag
   re.UNICODE, but this doesn't work on SuSE 9.2:
 [...]
  I can get the same results on RedHat's python 2.2.3 if I pass re.L
  option, it looks like this option is implicitly set in Suse.

 Looks like you are right:

  import re
  re.compile(ur'\w+', re.U).match(u'\xe4')
  from locale import *
  setlocale(LC_ALL, 'de_DE')
 'de_DE'
  re.compile(ur'\w+', re.U).match(u'\xe4')
 _sre.SRE_Match object at 0x40375560

 But I see nothing related to implicit re.L option in their patches
 and the sources themselves are the same as on other platforms.  I'd
 prefer to find the source of problem.

I found that

print u'\xc4'.isalpha()
import locale
print locale.getlocale()

produces different results on Suse (python 2.3.3)

False
(None, None)


and RedHat (python 2.2.3)

1
(None, None)

  Serge.

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


Re: executing VBScript from Python and vice versa

2005-02-10 Thread Valentina Boycheva
A while ago I asked how VBScript can be called from Python. The two answers
I received suggested using win32com.client and
MSScriptControl.ScriptControl. This solution required embedding the VBScript
code inside the Python script.

Here's  a shell approach that runs an existing VBScript file:

Python script
import os
import sys
os.system(F:\Projects\Doc\Scripts\VBScript\WriteDataToTextFile.vbs)

VBScript:
' WriteDataToTextFile.vbs
Const ForAppending = 8
Set objFSO = CreateObject(Scripting.FileSystemObject)
Set objTextFile = objFSO.OpenTextFile _
(c:\temp\temp.txt, ForAppending, True)
Set objNetwork = CreateObject(Wscript.Network)
objComputerName = objNetwork.ComputerName
objTextFile.WriteLine(My computer's name is)
objTextFile.WriteLine(objComputerName)
objTextFile.Close

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


Re: is there a safe marshaler?

2005-02-10 Thread Irmen de Jong
Pierre Barbier de Reuille wrote:
Irmen de Jong a écrit :
Pickle and marshal are not safe. They can do harmful
things if fed maliciously constructed data.
That is a pity, because marshal is fast.
I need a fast and safe (secure) marshaler.
Is xdrlib the only option?
I would expect that it is fast and safe because
it (the xdr spec) has been around for so long.
Or are there better options (perhaps 3rd party libraries)?
Thanks
Irmen.

What exactly do you mean by safe ? Do you want to ensure your objects 
cannot receive corrupted data ? Do you want to ensure no code will be 
evaluated during the unmarshalling ?
safe (secure)
But to be more precise, let's look at the security warning that
is in the marshal documentation:
The marshal module is not intended to be secure against erroneous or 
maliciously constructed data. Never unmarshal data received from an 
untrusted or unauthenticated source.

So essentially I want the opposite of that ;-)
I want a marshalar that is okay to use where the data it processes
comes from unknown, external sources (untrusted). It should not crash
on corrupt data and it should not execute arbitrary code when
unmarshaling, so that it is safe against hacking attempts.
Oh, preferrably, it should be fast :)
Some XML-ish thing may be secure but is likely to be not fast at all.
Ideally it should be able to transfer user defined Python types,
but if it is like marshal (can only marshal builtin types) that's
okay too.
--Irmen
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there a safe marshaler?

2005-02-10 Thread Irmen de Jong
Hello Guido
[EMAIL PROTECTED] wrote:
Irmen de Jong wrote:
Pickle and marshal are not safe. They can do harmful
things if fed maliciously constructed data.
That is a pity, because marshal is fast.

I think marshal could be fixed; the only unsafety I'm aware of is that
it doesn't always act rationally when confronted with incorrect input
like bad type codes or truncated input. It only receives instances of
the built-in types and it never executes user code as a result of
unmarshalling.
So it is not vulnerable in the way that pickle is? That's a start.
The security warning in the marsal doc then makes it sound worse than
it is...
Perhaps someone would be interested in submitting a patch to the
unmarshalling code? Since this is a security fix we'd even accept a fix
for 2.3.
That would be nice indeed :)

I need a fast and safe (secure) marshaler.
Is xdrlib the only option?
I would expect that it is fast and safe because
it (the xdr spec) has been around for so long.

I don't expect that to be particularly fast, since it mostly operates
at Python speed.
Ah, I wasn't aware that xdrlib was implemented in Python :)
I thought it used a (standard?) C-implementation.
But I now see that it's a Python module (utilizing struct).
I think it could be safe but I would still do a
thorough code review if I were you -- the code is older than my
awareness of the vulnerabilities inherent in this kind of remote data
transfer.
Thanks for the warning.
--Irmen de Jong
--
http://mail.python.org/mailman/listinfo/python-list


Is this a bug? BOM decoded with UTF8

2005-02-10 Thread pekka niiranen
Hi there,
I have two files my.utf8 and my.utf16 which
both contain BOM and two a characters.
Contents of my.utf8 in HEX:
EFBBBF6161
Contents of my.utf16 in HEX:
FEFF6161
For some reason Python2.4 decodes the BOM for UTF8
but not for UTF16. See below:
 fh = codecs.open(my.uft8, rb, utf8)
 fh.readlines()
[u'\ufeffaa']   # BOM is decoded, why
 fh.close()
 fh = codecs.open(my.utf16, rb, utf16)
 fh.readlines()
[u'\u6161'] # No BOM here
 fh.close()
Is there a trick to read UTF8 encoded file with BOM not decoded?
-pekka-
--
http://mail.python.org/mailman/listinfo/python-list


Re: sre is broken in SuSE 9.2

2005-02-10 Thread Denis S. Otkidach
On Thu, 10 Feb 2005 17:46:06 +0100
Fredrik Lundh [EMAIL PROTECTED] wrote:

  Can --with-wctype-functions configure option be the
  source of problem?
 
 yes.
 
 that option disables Python's own Unicode database, and relies on the C 
 library's
 wctype.h (iswalpha, etc) to behave properly for Unicode characters.  this 
 isn't true
 for all environments.
 
 is this an official SuSE release?  do they often release stuff that hasn't 
 been tested
 at all?

Yes, it's official release:
# rpm -qi python
Name: python   Relocations: (not relocatable)
Version : 2.3.4 Vendor: SUSE LINUX AG, 
Nuernberg, Germany
Release : 3 Build Date: Tue Oct  5 02:28:25 2004
Install date: Fri Jan 28 13:53:49 2005  Build Host: gambey.suse.de
Group   : Development/Languages/Python   Source RPM: python-2.3.4-3.src.rpm
Size: 15108594 License: Artistic License, Other 
License(s), see package
Signature   : DSA/SHA1, Tue Oct  5 02:42:38 2004, Key ID a84edae89c800aca
Packager: http://www.suse.de/feedback
URL : http://www.python.org/
Summary : Python Interpreter
snip

BTW, where have they found something with Artistic License in Python?

-- 
Denis S. Otkidach
http://www.python.ru/  [ru]
-- 
http://mail.python.org/mailman/listinfo/python-list


XDR? (was Re: is there a safe marshaler?)

2005-02-10 Thread PA
On Feb 10, 2005, at 15:01, Irmen de Jong wrote:
Is xdrlib the only option?
I would expect that it is fast and safe because
it (the xdr spec) has been around for so long.
XDR? Like Sun's XDR: External Data Representation standard?
http://www.faqs.org/rfcs/rfc1014.html
http://www.faqs.org/rfcs/rfc1832.html
How does XDR copes with Unicode these days?
Alternatively, perhaps there is a ASN.1 DER library in python?
http://asn1.elibel.tm.fr/en/standards/index.htm
Cheers
--
PA, Onnay Equitursay
http://alt.textdrive.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: goto, cls, wait commands

2005-02-10 Thread Alan Kennedy
[BOOGIEMAN]
I've just finished reading Python turtorial for non-programmers
and I haven't found there anything about some usefull commands I used in
QBasic. First of all, what's Python command equivalent to QBasic's goto ?
Oh no! You said the G word! That's a dirty word in computer science 
circles, because of the perception that goto (there, I said it, ugh!) 
can lead people to structure their code badly, i.e. write bad programs.

Instead, most modern programming languages offer a range of control and 
looping constructs that allow you to code your intention more clearly 
than with goto. Python examples include while, for .. in .., try .. 
except .., etc, etc.

So in order to answer your question, you're probably going to have to be 
more specific on what you want goto for.

Interestingly, gotos are undergoing a bit of renaissance in coding 
circles, but people have felt compelled to call them something 
different: continuations. But you're probably not interested in them. 
And python can't do them anyway.

Secondly, how do I clear screen (cls) from text and other content ?
That depends on
A: What type of display device you're using
B: What type of interface is being rendered on that display (command 
line, GUI, IDE, etc)
C: Perhaps what operating system you are using.

And last, how do I put program to wait certain amount of seconds ?
If I remeber correctly I used to type Wait 10 and QBasic waits 
10 seconds before proceeding to next command.
Ahh, a simple question! :-)
import time
time.sleep(10.0)
HTH,
--
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyclbr

2005-02-10 Thread Dennis Benzinger
Fernando San Martn Woerner wrote:
 Hi guys!
 
 i'm using pycblr to implement a class browser for my app, i got some
 issues about it:
 
 i did:
 
 dict = pyclbr.readmodule(name, [dir] + sys.path)

Don't use dict (or the name of any other built-in function)
as an identifier! It shadows the built-in function and can be quite
confusing for others reading your code.

It's sufficient to give only [dir] as the second parameter.
sys.path is always searched.
(http://docs.python.org/lib/module-pyclbr.html)

 but  this only works one time, i mean if module name is changed and
 some class were added or removed i can't see any changes even if i
 execute readmodule again.
 
 any idea?, thanks in advance

pyclbr caches modules it has already read. I think there is no method
for clearing that cache, so you have to

reload(pyclbr)

in order to see your changes.


Bye,
Dennis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Big development in the GUI realm

2005-02-10 Thread Stelios Xanthakis
Alex Martelli wrote:
Dennis Lee Bieber [EMAIL PROTECTED] wrote:

hassle to code, but if your application could dynamically select from
whatever toolkit is available on the machine, you (and I should emphasis
that this is an impersonal/generic you I reference) might be able to
argue an exemption from the QT license.

So maybe it's time to resurrect anygui, maybe in a simplified version
which can only interface to, say, PyQt or Tkinter -- 'eithergui' maybe.
Alex
Done already: 'Twilight GUI'!
http://students.ceid.upatras.gr/~sxanth/twgui/
However, it's very furstrating working on 4 toolkits in parallel
and because some of the don't have good documentation, I'm doing
other things right now:)
Stelios
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there a safe marshaler?

2005-02-10 Thread Alan Kennedy
[Irmen de Jong]
Pickle and marshal are not safe. They can do harmful
things if fed maliciously constructed data.
That is a pity, because marshal is fast.
I need a fast and safe (secure) marshaler.
Hi Irmen,
I'm not necessarily proposing a solution to your problem, but am 
interested in your requirement. Is this for pyro?

In the light of pyro, would something JSON be suitable for your need? I 
only came across it a week ago (when someone else posted about it here 
on c.l.py), and am intrigued by it.

http://json.org
What I find particularly intriguing is the JSON-RPC protocol, which 
looks like a nice lightweight alternative to XML-RPC.

http://oss.metaparadigm.com/jsonrpc/
Also interesting is the browser embeddable JSON-RPC client written in 
javascript, for which you can see a demo here

http://oss.metaparadigm.com/jsonrpc/demos.html
I thought you might be interested.
regards,
--
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: empty classes as c structs?

2005-02-10 Thread Steven Bethard
Alex Martelli wrote:
Steven Bethard [EMAIL PROTECTED] wrote:
I like the idea of chain, though, so I'll probably add the class with
just __init__ and __getattribute__ to the current implementation.  I'm
willing to be persuaded, of course, but for the moment, since I can see
a few different options, I'm refusing the temptation to guess on the 
most natural behavior for __delattr__ and __setattr__...  =)

That's probably best in terms of API.  Not too sure about the
implementation (why wouldn't __getattr__ suffice, holding the bunches in
an attribute with a magicname?) but that's a secondary issue.
Yeah, I had it written with __getattr__ at first...  Not sure why I 
switched over... ;)  I'll probably switch it back.

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


Re: Newbie: SWIG or SIP?

2005-02-10 Thread suryaprakashg
Look at this , this might be more simple to use

http://starship.python.net/crew/theller/ctypes/



Phil Thompson wrote:
  I have a third-party DLL and it's associated .h file.  The DLL was
written
  in C.  I have neither the associated .c files nor the .obj files
for the
  DLL.  Can I use SWIG or SIP to build something that will allow me
to use
  the
  DLL with Python?  And what is that something, an .obj file, another
DLL or
  what?

 Yes, you can use either SWIG or SIP. C (as opposed to C++) support
was
 added with SIP v4. The something is another DLL, conventionally given
a
 .pyd extenstion.
 
 Phil

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


Re: newbie question

2005-02-10 Thread Jeff Shannon
Dennis Lee Bieber wrote:
On Wed, 09 Feb 2005 18:10:40 -0800, Jeff Shannon [EMAIL PROTECTED]
declaimed the following in comp.lang.python:

for i in range(n)[::-1]:
func(n)

Shouldn't that be
func(i)
(the loop index?)
You're right, that's what I *meant* to say.  (What, the interpreter 
doesn't have a do what I mean mode yet? ;) )

The '[::-1]' iterates over the range in a reverse (decreasing) 
direction; this may or may not be necessary depending on the 
circumstances.
Eeee sneaky... (I'm a bit behind on latest syntax additions)
I'd probably have coded something like
for n1 in range(n):
func(n-n1)
though, and note that I do admit it here  [...]
Given a need/desire to avoid extended slicing (i.e. being stuck with 
an older Python, as I often am), I'd actually do this by changing the 
input to range(), i.e.

for i in range(n, 0, -1):   # ...
That (IMO) makes the decreasing-integer sequence a bit clearer than 
doing subtraction in the function parameter list does.  Actually, it's 
possibly clearer than the extended slicing, too, so maybe this would 
be the better way all around... ;)

I haven't done the detailed
analysis to properly set the end point... 
And as Peter Hansen points out, none of the Python versions leave n in 
the same state that the C loop does, so that's one more way in which 
an exact translation is not really possible -- and (IMO again) further 
evidence that trying to do an exact translation would be 
ill-conceived.  Much better to consider the context in which the loop 
is used and do a looser, idiomatic translation.

Jeff Shannon
Technician/Programmer
Credit International
--
http://mail.python.org/mailman/listinfo/python-list


[N00B] What's %?

2005-02-10 Thread administrata
Hi! it's been about a week learning python!
I've read 'python programming for the absolute begginer'
I don't understand about % like...

107 % 4 = 3
7 % 3 = 1

I'm confused with division :/
Please help me...

thx 4 reading.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: SWIG or SIP?

2005-02-10 Thread Grant Edwards
On 2005-02-10, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Phil Thompson wrote:
 I have a third-party DLL and it's associated .h file.  The DLL
 was written in C.  I have neither the associated .c files nor
 the .obj files for the DLL.  Can I use SWIG or SIP to build
 something that will allow me to use the DLL with Python?  And
 what is that something, an .obj file, another DLL or what?

 Yes, you can use either SWIG or SIP. C (as opposed to C++)
 support was added with SIP v4. The something is another DLL,
 conventionally given a .pyd extenstion.

 Look at this , this might be more simple to use

 http://starship.python.net/crew/theller/ctypes/

ctypes completely rocks.  I'm guessing it's a little more
overhead than using a swigified DLL, but it's dead-easy to use
and doesn't require a C or C++ compiler.  For the stuff I do, a
bit of extra overhead when calling DLL's is completely
negligible.

-- 
Grant Edwards   grante Yow!  By MEER biz doo
  at   SCHOIN...
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [N00B] What's %?

2005-02-10 Thread Alec Berryman
administrata on 2005-02-10 09:38:41 -0800:

 Hi! it's been about a week learning python!
 I've read 'python programming for the absolute begginer'
 I don't understand about % like...
 
 107 % 4 = 3
 7 % 3 = 1
 
 I'm confused with division :/

It's not division; the division operator is '/'.  It's the mod
function, which returns the remainder - for example, 7 divided by 3 is
2 remainder 1, so 7 % 3 returns 1.


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

Re: [N00B] What's %?

2005-02-10 Thread Simon Brunning
On Thu, 10 Feb 2005 09:41:07 -0800 (PST), administrata
[EMAIL PROTECTED] wrote:
 Hi! it's been about a week learning python!
 I've read 'python programming for the absolute begginer'

I hope you are enjoying it. ;-_

 I don't understand about % like...
 
 107 % 4 = 3
 7 % 3 = 1

It;'s modular aritmetic. See
http://en.wikipedia.org/wiki/Modular_arithmetic and
http://www.python.org/doc/2.3.4/ref/binary.html.

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [N00B] What's %?

2005-02-10 Thread Grant Edwards
On 2005-02-10, administrata [EMAIL PROTECTED] wrote:

 I don't understand about % like...

 107 % 4 = 3
 7 % 3 = 1

It's the modulus operator.  It returns the remainder of integer
division.  As we used to say in second grade:

 4 goes into 107 26 times with 3 left over.

 3 goes into 4 2 times with 1 left over. 

-- 
Grant Edwards   grante Yow!  If I pull this SWITCH
  at   I'll be RITA HAYWORTH!! Or
   visi.coma SCIENTOLOGIST!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [N00B] What's %?

2005-02-10 Thread Bruno Desthuilliers
administrata a écrit :
Hi! it's been about a week learning python!
I've read 'python programming for the absolute begginer'
I don't understand about % like...
107 % 4 = 3
7 % 3 = 1
it's the modulo operator (if you don't remember, the modulo is the 
remaining of the integer division, ie 5 % 2 = 1)

One of the most commun use is to test wether a number is odd or even:
any_even_number % 2 == 0
any_odd_number % 2 == 1
Note that the % operator is also used for string formating, ie:
%d modulo %d = %d % (5, 2, 1)
= 5 modulo 2 = 1
Please help me...
HTH
Bruno
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >