Re: deleting from tarfile

2005-01-16 Thread "Martin v. Löwis"
Mark McEahern wrote:
It doesn't appear so.  A workaround, of course, is to create a new file 
with the subset of files from the old file:
That is actually the *only* way to do that. tarfiles cannot be "sparse",
in the sense that parts of the file can be marked as deleted. So in
order to delete a file, you have to copy the entire tarfile, and skip
the file you want to delete - whether you do this yourself, or whether
tarfile.py does it for you.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


generator expressions: performance anomaly?

2005-01-16 Thread John Machin
Please consider the timings below, where a generator expression starts
out slower than the equivalent list comprehension, and gets worse:

>python -m timeit -s "orig=range(10)" "lst=orig[:];lst[:]=(x for x
in orig)"
10 loops, best of 3: 6.84e+004 usec per loop

>python -m timeit -s "orig=range(20)" "lst=orig[:];lst[:]=(x for x
in orig)"
10 loops, best of 3: 5.22e+005 usec per loop

>python -m timeit -s "orig=range(30)" "lst=orig[:];lst[:]=(x for x
in orig)"
10 loops, best of 3: 1.32e+006 usec per loop

>python -m timeit -s "orig=range(10)" "lst=orig[:];lst[:]=[x for x
in orig]"
10 loops, best of 3: 6.15e+004 usec per loop

>python -m timeit -s "orig=range(20)" "lst=orig[:];lst[:]=[x for x
in orig]"
10 loops, best of 3: 1.43e+005 usec per loop

>python -m timeit -s "orig=range(30)" "lst=orig[:];lst[:]=[x for x
in orig]"
10 loops, best of 3: 2.33e+005 usec per loop

Specs: Python 2.4, Windows 2000, 1.4GHz Athlon chip, 768Mb of memory.

Background: There was/is a very recent thread about ways of removing
all instances of x from a list. /F proposed a list comprehension to
build the result list. Given a requirement to mutate the original list,
this necessitates the assignment to lst[:]. I tried a generator
expression as well. However while the listcomp stayed competitive up to
a million-element list, the genexp went into outer space, taking about
20 times as long. The above timeit runs show a simpler scenario where
the genexp also seems to be going quadratic.
Comments, clues, ... please.

TIA,
John

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


Re: How to del item of a list in loop?

2005-01-16 Thread Fredrik Lundh
John Machin wrote:

>> (if you have 2.4, try replacing [] with () and see what happens)
>
> The result is a generator with a name ("lst") that's rather misleading
> in the context.

according to my dictionary, the word "list" means "A series of names, words,
or other items written, printed, or imagined one after the other".  I'd say that
matches both list objects and iterators pretty well.

but alright, you can change the name to "seq" if you want.

> Achieving the same result as the list comprehension, by doing lst = list(i for
... etc etc), appears to be slower.

the original post didn't contain a complete use case; a generator is a perfect
replacement for a list in many cases.  I'm sure most comp.lang.python readers
are smart enough to understand when and why.

 



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


Re: generator expressions: performance anomaly?

2005-01-16 Thread Fredrik Lundh
John Machin wrote:

> Given a requirement to mutate the original list, this necessitates the 
> assignment
> to lst[:].

do you always pull requirements out of thin air?

 



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


Re: How to del item of a list in loop?

2005-01-16 Thread Nick Coghlan
John Machin wrote:
Nick Coghlan wrote:
The effbot's version is still going to be faster though:
  lst = [x for x in lst if x != 2]

Have you measured this?
Nope. I'm going purely on the fact that it is O(n), and the in-place 
modification will always be worse than that.

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


Re: generator expressions: performance anomaly?

2005-01-16 Thread Nick Coghlan
John Machin wrote:
Background: There was/is a very recent thread about ways of removing
all instances of x from a list. /F proposed a list comprehension to
build the result list. Given a requirement to mutate the original list,
this necessitates the assignment to lst[:]. I tried a generator
expression as well. However while the listcomp stayed competitive up to
a million-element list, the genexp went into outer space, taking about
20 times as long. The above timeit runs show a simpler scenario where
the genexp also seems to be going quadratic.
Comments, clues, ... please.
Py> lc = [x for x in range(100)]
Py> len(lc)
100
Py> ge = (x for x in range(100))
Py> len(ge)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: len() of unsized object
It would be nice if unconditional ge's with known length inputs propagated 
__len__, but that is not currently the case. There's a similar performance 
glitch associated with constructing a tuple from a generator expression (with 
vanilla 2.4, detouring via list is actually faster)

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


Re: How to del item of a list in loop?

2005-01-16 Thread Bengt Richter
On Sat, 15 Jan 2005 15:27:08 -0500, skull <[EMAIL PROTECTED]> wrote:

>
>Hi everybody, it is my first post in this newsgroup.
>I am a newbie for python though I have several years development experience in 
>c++.
>recently, I was stumped when I tried to del item of a list when iteration.
>
>here is the wrong way I did:
>
>lst = [1, 2, 3]
>for i in lst:
>print i
>if i == 2: 
>   lst.remove(i)
>
>the result is:
>
>1
>2

>
>as you would see, '3' is missing. this problem is caused by 'lst.remove(i)'.
>apparently, 'marked-and-sweep' is a solution to deal with this issue.
>but I think there SHOULD BE more 'wise' trick. I want to get your help.
>
>Thanks in advance.
>
No one seems to have suggested this in-place way yet,
so I'll trot it out once again ;-)

 >>> lst = [1, 2, 3]
 >>> i = 0
 >>> for item in lst:
 ...if item !=2:
 ...lst[i] = item
 ...i += 1
 ...
 >>> del lst[i:]
 >>> lst
 [1, 3]


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


Re: interpret 4 byte as 32-bit float (IEEE-754)

2005-01-16 Thread Bengt Richter
On Sat, 15 Jan 2005 11:00:36 -0800, Scott David Daniels <[EMAIL PROTECTED]> 
wrote:

>G.Franzkowiak wrote:
>> Scott David Daniels schrieb:
>> 
>>> franzkowiak wrote:
>>>
 I've read some bytes from a file and just now I can't interpret 4 
 bytes in this dates like a real value.  An extract from my program:
 def l32(c):
 return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) +  
 (ord(c[3])<<24)
 ...
 value = l32(f.read(4))  <---  3F 8C CC CD  should be 1.11

>>> OK, here's the skinny (I used blocks & views to get the answer):
>>>
>>> import struct
>>> bytes = ''.join(chr(int(txt, 16)) for txt in '3F 8C CC CD'.split())
>>> struct.unpack('>f', bytes)
>>>
>>> I was suspicious of that first byte, thought it might be an exponent,
>>> since it seemed to have too many on bits in a row to be part of 1.11.
>>>
>>> -Scott David Daniels
>>> [EMAIL PROTECTED]
>> 
>> 
>> Ok, I the string exist with "mystr = f.read(4)" and the solution for 
>> this case is in your line "struct.unpack('>f', bytes)"
>> But what can I do when I want the interpret the content from the Integer 
>> myInt  (*myInt = 0x3F8D) like 4-byte-real ?
>> This was stored with an othes system in a binary file to
>> CD CC 8C 3F and now is it in python in value. The conversion is not 
>> possible. It's right... one of this bytes is an exponent.
>> I want copy the memory content from the "value address" to "myReal 
>> address" and use print "%f" %myReal.
>> Is myReal then the right format ?
>> What can I do with python, in FORTH is it simple
>> ( >f f. )
>> 
>> gf
>> 
>> 
>> 
>If you really want to do this kind of byte fiddling:
> http://members.dsl-only.net/~daniels/block.html
>
>Then:
> from block import Block, View
> b = Block(4) # enough space for one float (more is fine)
> iv = View('i', b) # getting to it as an integer
> fv = View('f', b) # same memory as floating point
> iv[0] = 0x3F8D # Here is a sample just using the integer
> print fv[0]
>
>On an Intel/Amd/Generic "PC" machine, you should get 1.1
>
Ok, for most bit patterns (except QNANs), you can do it in pure python:

< i32as_single.py >
class NoQNAN(ValueError): pass  # use to flag inability to return QNANs

def i32as_single(i):
"""
(UIAM in my interpretation of a 1995 Pentium Processor Developer's Manual)
This converts bits in a 32-bit integer as if they were bits
of a single-precision IEEE 754 floating point number to python float

+---+---+---+---+---+---+---+---+---+---+---+---+ ... +---+---+---+---+
| s | e   e   e   e   e   e   e   eb| b   b   b   ...  b   b   b   b0 |
+---+---+---+---^---+---+---+---^---+---+---+---^ ... ^---+---+---+---+
  31  30  29  28  27  26  25  24  23  22  21  203   2   1   0

where s is the sign bit, and is the only thing that changes between + and -
and e..eb is an 8-bit biased (by 127) exponent, and eb is the hidden
unit 1 bit followed by 23 b..b0 significant "fraction" bits",
normalized so that the most significant bit is always 1 and therefore
doesn't have to be stored at eb, except that when all but the sign bit
are zero, eb is ignored and the value is then a signed zero value.
The binary fraction starting bit is after the hidden '1' bit eb at 23,
so viewing bits 0..23 as an integer, we have to divide by 2**23 (or
adjust the exponent) to get the 1. values when the official unbiased
exponent is zero (offset value 127).  Thus 0x3f80 is zero unbiased
exponent and no other bits, for a value of 1.0

A biased exponent of 255 signifies a NaN, and a biased exponent of
zero signifies a denormal (which doesn't have a hidden bit, and whose
unit bit is bit 22). Single precision denormals can be normalized
in python (double) float format, which is done for the return value.
"""
signbit = i&0x8000
if not i&0x7fff: return signbit and -0.0 or 0.0 # if -0.0 available
biased_exp = (i>>23) & 0xff # bits 30-23
unitbit = biased_exp and 0x80 or 0 # bit 23, or 0 for denormals
significand = i & 0x7f  # bits 22-0
if biased_exp == 255:
if significand:
raise NoQNAN, "Sorry, can't generate QNAN from %08x" % i
return signbit and -1e or 1e  # XXX s/b INF's for sure??
adjexp = (biased_exp or 1) - 127 - 23 # adjusted for denormal
posvalue = (significand + unitbit)*2.0**adjexp
return signbit and -posvalue or posvalue

def test():
import struct
num = 0
for sign in (0, 2*(-2**30)):
for i3 in xrange(128):
num3 = i3<<24
for i2 in xrange(256):
print '\r%08x'%(num,),  # show progress
num2 = i2<<16
# skip mid byte of significand, make 0
# and twiddle only a few bits at the bottom
for num0 in xrange(8):
num = sign+num3+num2+num0
  

Re: video analysis with python

2005-01-16 Thread Miki Tebeka
Hello Ashot,

>   I need to write a video analysis tool which extracts statistics from 
> microsocope video.  Essentially what I need is to translate the video data  
> into numerical matrices. I have been using Python for the past 1.5 years  
> anytime I could for absolutely everything, because it has every library  
> imaginable... Alas, I can not find a library for decoding video/using  
> codecs.  The only solution I have been able to come up with is to create  
> an image sequence and load those in with PIL, however this is not really  
> feasible as the images are too large (nor is it proffessional).
> 
>   Is there a library or project that I have missed, or is there a way 
>   to  incorporate something like vfw.lib directly?  If there isn't I 
> think 
> this  would be a pretty large whole in Python's arsenal.  Thanks in advance 
> for  any help.

1. There is PyMedia (http://pymedia.org/)
2. Maybe you can use the code from VLC (http://www.videolan.org/vlc/)
  (using SWIG/PyBoost/Pyrex ...)

HTH.
--

Miki Tebeka <[EMAIL PROTECTED]>
http://tebeka.bizhat.com
The only difference between children and adults is the price of the toys
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to del item of a list in loop?

2005-01-16 Thread John Machin

Bengt Richter wrote:
> No one seems to have suggested this in-place way yet,
> so I'll trot it out once again ;-)
>
>  >>> lst = [1, 2, 3]
>  >>> i = 0
>  >>> for item in lst:
>  ...if item !=2:
>  ...lst[i] = item
>  ...i += 1
>  ...
>  >>> del lst[i:]
>  >>> lst
>  [1, 3]

Works, but slowly. Here's another that appears to be the best on large
lists, at least for removing 1 element. It's O(len(list) *
number_to_be_removed).

!def method_try_remove(lst, remove_this):
!try:
!while 1:
!lst.remove(remove_this)
!except:
!pass

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


accessing class variables of private classes

2005-01-16 Thread Uwe Mayer
Hi,

I need to access class variables of a class I'd like to make private:

i.e.
class __Bar(object):
  pass

class __Foo(__Bar):
  def __init__(self):
super(__Foo, self).__init__()

>>> __Foo()
Name Error: global name '_Foo__Foo' is not defined

Here I want to prevent the user of instanciating __Foo from outside of the
module.


i.e.
class __A:
  a_list = []
  def __init__(self):
__A.a_list.append(self)

>>> __A()
NameError: global name '_A__A' is not defined

Here I want to keep a list of instanciated objects of class __A, so I can
update internal values if they are changed.


Any ideas?

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


Re: there's a socket.sendall(), so why no socket.recvall()?

2005-01-16 Thread Roger Binns
 there's a socket.sendall(), so why no socket.recvall()?

BTW socket.sendall() doesn't actually work for large amounts
of data on Windows 2000 and probably other versions of
Windows as well.  Eg if you supply a 1MB buffer then you get
an exception based on some internal Windows error code.
I haven't experimented on Unix yet to see if it has the same
issue.

The workaround is to write a wrapper that really does send
everything.

Roger 


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


Newbie inheritance question.

2005-01-16 Thread bwobbones
Hi all,
 I'm a java programmer struggling to come to terms with python - bear 
with me!

 I'm trying to subclass a class, and I want to be able to see it's 
attributes also.  Here are my classes:

one.py:
*
class one:
   def __init__(self):
   print "one"
   self.testVar = 1
   def printHello(self):
   print "hello"
*
two.py
*
from one import one
class two(one):
   def __init__(self):
   print "two"
   def printTestVar(self):
   print "testVar: " + str(self.testVar)
*
and the driver to make it work:
*
from two import two
class driver:
   def go(self):
   print "driver"
   self.two = two()
   self.two.printHello()
   self.two.printTestVar()
if __name__ == '__main__':
   d = driver()
   d.go()
*
the "self.two.printTestVar()" call doesn't work: shouldn't two.py have 
access to all of it's parents attributes?  In java I would make the 
testVar protected so it's children could see it.  How do I do this in 
python?

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


Re: accessing class variables of private classes

2005-01-16 Thread Mark McEahern
Uwe Mayer wrote:
Hi,
I need to access class variables of a class I'd like to make private:
 

Use single underscores instead of double underscores--you won't have to 
workaround the name mangling.  Besides, nothing's really private anyway.

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


Re: Newbie inheritance question.

2005-01-16 Thread Ed Leafe
On Jan 16, 2005, at 9:08 AM, bwobbones wrote:
class two(one):
   def __init__(self):
   print "two"
	You need to specifically call the superclass's __init__ here in order 
for it to fire. Just add the line

   super(two, self).__init__()
as the first line of the subclass's __init__.
 ___/
/
   __/
  /
 /
 Ed Leafe
 http://leafe.com/
 http://dabodev.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie inheritance question.

2005-01-16 Thread Mark McEahern
bwobbones wrote:
Hi all,
 I'm a java programmer struggling to come to terms with python - bear 
with me!
Welcome!
 I'm trying to subclass a class, and I want to be able to see it's 
attributes also.  Here are my classes:
[snip]
class two(one):
   def __init__(self):
   print "two"
The problem is that you're not calling the parent class' __init__::
 class two(one):
 def __init__(self):
 one.__init__(self)
 ...
You can also use super() to do that, but I do that so rarely I forget 
the syntax.  Of course, that's no big deal, since::

 python
 >>> help(super)
is always to the rescue, but I'm lazy.
// m
--
http://mail.python.org/mailman/listinfo/python-list


Re: there's a socket.sendall(), so why no socket.recvall()?

2005-01-16 Thread Irmen de Jong
Roger Binns wrote:
there's a socket.sendall(), so why no socket.recvall()?

BTW socket.sendall() doesn't actually work for large amounts
of data on Windows 2000 and probably other versions of
Windows as well.  Eg if you supply a 1MB buffer then you get
an exception based on some internal Windows error code.
I haven't experimented on Unix yet to see if it has the same
issue.
I suspect that this is related to this issue:
http://www.python.org/sf/853507
socket.recv() raises MemoryError exception (WindowsXP ONLY)
Also see:
http://www.python.org/sf/1103350
But I haven't yet experienced this problem yet with sendall
(on linux and windows xp)
--Irmen
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie inheritance question.

2005-01-16 Thread Just
In article <[EMAIL PROTECTED]>,
 Ed Leafe <[EMAIL PROTECTED]> wrote:

> On Jan 16, 2005, at 9:08 AM, bwobbones wrote:
> 
> > class two(one):
> >def __init__(self):
> >print "two"
> 
>   You need to specifically call the superclass's __init__ here in order 
> for it to fire. Just add the line
> 
> super(two, self).__init__()
> 
> as the first line of the subclass's __init__.

super() only works for new-style classes, ie. class one needs to derive 
from object for this to work.

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


Re: How to del item of a list in loop?

2005-01-16 Thread Michael Hoffman
John Machin wrote:
I've taken your code and improved it along the
suggested lines, added timing for first, middle, and last elements,
added several more methods, and added a testing facility as well. Would
you like a copy?
Actually I think it would be great if you posted it here for our
combined edification. I would have been considerably less annoyed if you
had done that and explained why it is better rather than nitpicking my
version.
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: generator expressions: performance anomaly?

2005-01-16 Thread Raymond Hettinger
"John Machin" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Please consider the timings below, where a generator expression starts
> out slower than the equivalent list comprehension, and gets worse:
>
> >python -m timeit -s "orig=range(10)" "lst=orig[:];lst[:]=(x for x
> in orig)"
 . . .
> >python -m timeit -s "orig=range(20)" "lst=orig[:];lst[:]=(x for x
> in orig)"

This has nothing to do with genexps and everything to do with list slice
assignment.

List slice assignment is an example of a tool with a special case optimization
for inputs that know their own length -- that enables the tool to pre-allocate
its result rather than growing and resizing in spurts.  Other such tools include
tuple(), map() and zip().

The incredulous tone of the posting suggests a presumption that genexps always
outperform list comps.  That is not the case. Sometimes you want a list instead
of a generator because you want more than just iteration; perhaps the consumer
function may be able to take advantage of length reporting, indexing, slicing,
re-iterability or other useful list behaviors.

Also, the timing jig bites.  Use xrange() instead of range().  Otherwise,
there's an immediate forfeit of the memory savings normally being sought by the
use of generators and iterators.



> Background: There was/is a very recent thread about ways of removing
> all instances of x from a list. /F proposed a list comprehension to
> build the result list.

FWIW, deques have a natural idiom for this kind of situation:

for i in xrange(len(mydeque)):
x = mydeque.popleft()
if some_condition(x):
mydeque.append(x)



> Given a requirement to mutate the original list,
> this necessitates the assignment to lst[:].

Sometimes people introduce arbitrary requirements and twist themselves in knots
when real applications tend to allow a wider range of alternative solutions.
There is a funky code smell emanating from any code resembling
a[:]=some_iterator.  It would make me examine how 'a' is being used and check
whether the surrounding code can use the iterator or an new object.



> Comments, clues, ... please.

As a point of interest, note that Py2.4 improved some of its built-in iterators
to report their length if requested.  Now you now why.

>>> d = dict(a=1, b=2, c=3, d=4)
>>> len(d.iteritems())
4



Raymond Hettinger


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


iTools

2005-01-16 Thread kent sin
Where can I download python-itools?

I found it in the python packages index but the site
is not contactable. 

Thank you.

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


Re: interpret 4 byte as 32-bit float (IEEE-754)

2005-01-16 Thread Tim Peters
[Bengt Richter]
...
> But I don't know how to build QNaNs:

You can subtract infinity from infinity.  While all Python behavior in
the presence of NaNs, infinities, and signed zeroes is a
platform-dependent accident, it you're on a box that has such things,
and figure out some (accidental!) way to spell infinity, then inf-inf
should return a NaN (although on a WinTel box, it's most likely to be
spelled "-1.#IND" when converted to string).

...

> Whereas struct does:

No, it doesn't.  All Python behavior in the presence of NaNs,
infinities, and signed zeroes is a platform-dependent accident.

> >>> import struct
> >>> struct.unpack('f','\x00\x00\x80\x7f')[0]
> 1.#INF

An accident (both that you got back an infinity, and the string
representation of an infinity).

> >>> struct.unpack('f','\x01\x00\x80\x7f')[0]
> 1.#QNAN

Ditto.

Those specific accidents are reliable on the box you're using.

> BTW, your example:
> >>> struct.unpack('f','\xcd\xcc\x8c\x3f')[0]
> 1.100238418579
> >>> i32f(0x3f8d)
> 1.100238418579
> 
> But what does this mean?

Mostly just that behavior is predictable when you're *not* using
infinities, NaNs or signed zeroes from Python.

> (I wanted to test with little endian unpacking, since
> that is what I knew I created, but that isn't what '<' means?? ...)

Little-endian is part of what '<' means.  '<' also means "use standard
alignment" and "use standard data size" and "use standard bit
representation".  As soon as you force anything like that, Python has
to try to interpret the bits itself.  In the absence of "<", ">" and
"!", plain "f" asks for a wholly platform-native result.  In that
case, Python doesn't have to know anything about what the bits might
mean:  it stores the bytes into a native sizeof(float)-byte memory
area natively aligned for a float, and you get back whatever the
native C thinks that means.

> >>> struct.unpack('f','\x00\x00\x80\x7f')[0]
> 1.#INF

Entirely determined by the platform C compiler and hardware.

> >>> struct.unpack(' 3.4028236692093846e+038

Entirely determined by what Python thinks the bits should mean, but
Python doesn't know anything about infinities, NaNs, or signed zeroes,
and C89 library routines Python calls to construct the value (like
ldexp()) have no portably defined behavior in their presence either.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I get the names of the files in a directory?

2005-01-16 Thread Stian Soiland
På 15. jan 2005 kl. 16:16 skrev .removethis.:
>>> import glob
>>> from os.path import isfile
>>> print filter(isfile, glob.glob('/tmp/*')) # can use patterns
Nice example of when filter() is better than list comprehension.
[f for f in glob.glob("/tmp/*") if isfile(fi)]
is a bit too verbose, the iteration is a totally uninteresting part 
here.

--
Stian Søiland
Trondheim, Norway
http://www.soiland.no/
 =/\=
--
http://mail.python.org/mailman/listinfo/python-list


Re: accessing class variables of private classes

2005-01-16 Thread Peter Otten
Uwe Mayer wrote:

> I need to access class variables of a class I'd like to make private:
> 
> i.e.
> class __Bar(object):
>   pass
> 
> class __Foo(__Bar):
>   def __init__(self):
> super(__Foo, self).__init__()
> 
 __Foo()
> Name Error: global name '_Foo__Foo' is not defined
> 
> Here I want to prevent the user of instanciating __Foo from outside of the
> module.
> 
> 
> i.e.
> class __A:
>   a_list = []
>   def __init__(self):
> __A.a_list.append(self)
> 
 __A()
> NameError: global name '_A__A' is not defined
> 
> Here I want to keep a list of instanciated objects of class __A, so I can
> update internal values if they are changed.
> 
> 
> Any ideas?

Use single underscores. Even better: don't impose bogus restrictions on
users of your module. I know, we're all dissenting children, but still...

> 
> Thanks
> Uwe

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


Re: threading and sockets ?

2005-01-16 Thread Daniel Bickett
http://www.twistedmatrix.com/

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


Re: mutable string?

2005-01-16 Thread "Martin v. Löwis"
Torsten Mohr wrote:
is there some string class that i can change in place,
like perls strings?
array.array is mutable. You can use the 'c' code if
you want an array of characters.
Is it possible to do some regex replacement functions
that would even change its length?
You can't use re.sub array, but you can use re.search,
and you can perform slice assigment.
Can i append to this string?
Yes.
Is there some wrapper for C++ STL string class (if that
would make sense)?
It would be possible, but I cannot see why one would want
to do that.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: why are some types immutable?

2005-01-16 Thread "Martin v. Löwis"
Torsten Mohr wrote:
reading the documentation (and also from a hint from this NG)
i know now that there are some types that are not mutable.
But why is it this way?
There are various reasons, some apply for some types, and
some for others:
- immutable objects are hashable - their hash value will not
  change during their life time (if it is a container, the
  contained objects also need to be hashable). Mutable
  types are typically not hashable.
  A type needs to be hashable to act as a dictionary key.
- immutable objects can be shared, allowing the same
  reference to be used in multiple places. For mutable
  objects, one often needs to make a copy of the object
  before storing it.
- immutable types can often be implemented more efficiently.
  For examples, the length of a tuple is fixed, as tuples
  are immutable. Therefore, memory management for tuples
  is simpler (they only require one memory block, instead
  of two, as lists do).
- for some types, the expectation of immutability is so
  common that people would complain massively if they were
  mutable. This, in particular, applies to numbers - people
  expect that after
  x = 7
  the variable x keeps the value, and that the "7" object
  cannot suddenly change its value to 8.
From an overhead point of view i think it is not optimal,
for example for a large string it could be much faster to
have it changed in place, not generating a new one for
every step in a change.
For strings, the following points apply; as a net result,
the overhead is *less* than it would be if strings were
mutable:
- strings must be hashable, so they can be used as
  a dictionary key. If you would modify, say,
  len.func_name, then newly imported code could not
  find the len function anymore.
  It would be possible to solve this by introducing
  an additional immutable identifier type, but then
  you would need to create copies of strings (to
  create identifier object). Many applications might
  break which currently use strings as dictionary
  keys.
- strings are currently assumed to be shareable.
  You pass strings to functions which then store
  the strings in global variables, object attributes,
  etc. In all these places, copies would need to be
  made if strings were mutable, since the caller
  might chose to modify the string afterwards.
- immutable strings consume less memory than
  mutable strings would, because a string is made
  up of just one memory block.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Weekly Python Patch/Bug Summary

2005-01-16 Thread Kurt B. Kaiser
Patch / Bug Summary
___

Patches :  272 open ( +5) /  2737 closed (+10) /  3009 total (+15)
Bugs:  793 open ( -5) /  4777 closed (+29) /  5570 total (+24)
RFE :  165 open ( +0) /   141 closed ( +1) /   306 total ( +1)

New / Reopened Patches
__

Enhance tracebacks and stack traces with vars  (2005-01-08)
   http://python.org/sf/1098732  opened by  Skip Montanaro

Single-line option to pygettext.py  (2005-01-09)
   http://python.org/sf/1098749  opened by  Martin Blais

improved smtp connect debugging  (2005-01-11)
CLOSED http://python.org/sf/1100140  opened by  Wummel

Log gc times when DEBUG_STATS set  (2005-01-11)
   http://python.org/sf/1100294  opened by  Skip Montanaro

deepcopying listlike and dictlike objects  (2005-01-12)
   http://python.org/sf/1100562  opened by  Björn Lindqvist

ast-branch: fix for coredump from new import grammar  (2005-01-11)
   http://python.org/sf/1100563  opened by  logistix

datetime.strptime constructor added  (2005-01-12)
   http://python.org/sf/1100942  opened by  Josh

Feed style codec API  (2005-01-12)
   http://python.org/sf/1101097  opened by  Walter Dörwald

Patch for potential buffer overrun in tokenizer.c  (2005-01-13)
   http://python.org/sf/1101726  opened by  Greg Chapman

ast-branch: hacks so asdl_c.py generates compilable code  (2005-01-14)
   http://python.org/sf/1102710  opened by  logistix

Fix for 926423: socket timeouts + Ctrl-C don't play nice  (2005-01-15)
   http://python.org/sf/1102879  opened by  Irmen de Jong

Boxing up PyDECREF correctly  (2005-01-15)
CLOSED http://python.org/sf/1103046  opened by  Norbert Nemec

AF_NETLINK sockets basic support  (2005-01-15)
   http://python.org/sf/1103116  opened by  Philippe Biondi

Adding the missing socket.recvall() method  (2005-01-16)
   http://python.org/sf/1103213  opened by  Irmen de Jong

tarfile.py: fix for bug #1100429  (2005-01-16)
   http://python.org/sf/1103407  opened by  Lars Gustäbel

Patches Closed
__

pydoc data descriptor unification  (2004-04-17)
   http://python.org/sf/936774  closed by  jlgijsbers

xml.dom missing API docs (bugs 1010196, 1013525)  (2004-10-21)
   http://python.org/sf/1051321  closed by  jlgijsbers

Fix for bug 1017546  (2004-08-27)
   http://python.org/sf/1017550  closed by  jlgijsbers

fixes urllib2 digest to allow arbitrary methods  (2005-01-04)
   http://python.org/sf/1095362  closed by  jlgijsbers

Bug fix 548176: urlparse('http://foo?blah') errs  (2003-03-30)
   http://python.org/sf/712317  closed by  jlgijsbers

bug fix 702858: deepcopying reflexive objects  (2003-03-22)
   http://python.org/sf/707900  closed by  jlgijsbers

minor codeop fixes  (2003-05-15)
   http://python.org/sf/737999  closed by  jlgijsbers

SimpleHTTPServer reports wrong content-length for text files  (2003-11-10)
   http://python.org/sf/839496  closed by  jlgijsbers

improved smtp connect debugging  (2005-01-11)
   http://python.org/sf/1100140  closed by  jlgijsbers

Boxing up PyDECREF correctly  (2005-01-15)
   http://python.org/sf/1103046  closed by  rhettinger

New / Reopened Bugs
___

socket.setdefaulttimeout() breaks smtplib.starttls()  (2005-01-08)
   http://python.org/sf/1098618  opened by  Matthew Cowles

set objects cannot be marshalled  (2005-01-09)
CLOSED http://python.org/sf/1098985  opened by  Gregory H. Ball

codec readline() splits lines apart  (2005-01-09)
CLOSED http://python.org/sf/1098990  opened by  Irmen de Jong

Optik OptionParse important undocumented option  (2005-01-10)
   http://python.org/sf/1099324  opened by  ncouture

refman doesn't know about universal newlines  (2005-01-10)
   http://python.org/sf/1099363  opened by  Jack Jansen

raw_input() displays wrong unicode prompt  (2005-01-10)
   http://python.org/sf/1099364  opened by  Petr Prikryl

tempfile files not types.FileType  (2005-01-10)
CLOSED http://python.org/sf/1099516  opened by  Frans van Nieuwenhoven

copy.deepcopy barfs when copying a class derived from dict  (2005-01-10)
   http://python.org/sf/1099746  opened by  Doug Winter

Cross-site scripting on BaseHTTPServer  (2005-01-11)
   http://python.org/sf/1100201  opened by  Paul Johnston

Scripts started with CGIHTTPServer: missing cgi environment  (2005-01-11)
   http://python.org/sf/1100235  opened by  pacote

Frame does not receive configure event on move  (2005-01-11)
   http://python.org/sf/1100366  opened by  Anand Kameswaran

Wrong "type()" syntax in docs  (2005-01-11)
   http://python.org/sf/1100368  opened by  Facundo Batista

TarFile iteration can break (on Windows) if file has links  (2005-01-11)
   http://python.org/sf/1100429  opened by  Greg Chapman

Python Interpreter shell is crashed   (2005-01-12)
   http://python.org/sf/1100673  opened by  abhishek

test_fcntl fails on netbsd2  (2005-01-12)
   http://python.org/sf/1101233  opened 

Re: Statement local namespaces summary (was Re: python3: 'where' keyword)

2005-01-16 Thread Andrey Tatarinov
Nick Coghlan wrote:
# Anonymous functions
use res:
  def f(x):
d = {}
exec x in d
return d
in:
  res = [f(i) for i in executable]
as for me, I found construction "use :" unobvious and confusing.
Also there is great possibility to forget some of variables names.
I think that syntax

where:

is more obvious. (and we already have defined semantics for it)
we have two problems, that we try to solve
1) create method to nest scopes
2) create method to reverse execution order for better readability
"using:" solves both at once.
but your "use ... in ..." syntax shows, that you want to be able to 
solve 1) independently i.e. create nested scope without reversing 
execution order.

so, I can suggest one more keyword "do:", which will create nested 
scope, just as "def f(): ... ; f()" do (and that could be just syntaxic 
sugar for it.

so "use ... in ..." would look the following way:
do:
res = [f(i) for i in executable]
#some more equations here
using:
def f(x):
d = {}
exec x in d
return d
that seems good for me. of course if you want to return something from 
the nest scope you must show that variable is from parent scope.

// while writing that I realized that it's too complex to be implemented 
in python in that way. consider it as some type of brainstorming.
--
http://mail.python.org/mailman/listinfo/python-list


Executing a script created by the end user

2005-01-16 Thread Craig Howard
I am working on a python project where an object will have a script that 
can be edited by the end user: object.script

If the script is a simple one with no functions, I can easily execute it 
using:
	exec object.script

But if the object script is a bit more complicated, such as the example 
below, my approach does not  work:

def main():
hello1()
hello2()
def hello1():
print 'hello1'
def hello2():
print 'hello2'
--
http://mail.python.org/mailman/listinfo/python-list


Re: protecting the python code.

2005-01-16 Thread Bob Smith
nell wrote:
Hi Steve,
First the "10x in advance" means thanks in advance.
The main importance of protecting my code is to save headache of
customers that want to be smart and change it and then complain on bugs
and problems.
10x
I'd say that's more of a policy issue than a technical issue. You have a 
contract or agreement with your customers, right? Just place a cluase in 
it that addresses your concerns. You don't have to support people who 
have altered your code... nor should they expect to be supported.

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


Re: Newbie inheritance question.

2005-01-16 Thread Jeremy Bowers
On Sun, 16 Jan 2005 22:08:13 +0800, bwobbones wrote:

> Hi all,
> 
>   I'm a java programmer struggling to come to terms with python - bear 
> with me!

Christophe already identified the problem, I wanted to address another
Javaism in your code, for your educational benefit.

Speaking "idiomatically" (since this is all small sample code), in Python
you'd normally code your driver as follows:

--
import two

t = two() # or something, there's a name conflict here, too many "two"s
t.printHello()
t.printTestVar()
--

Things that aren't objects shouldn't be forced to be objects and I don't
think there is any shame in having a non-OO top level. (I go on about this
at http://www.jerf.org/writings/bowersLaw.html#4 in more detail.)


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


Scriptomatic 2.0

2005-01-16 Thread Do Re Mi chel La Si Do
Hi !

Scriptomatic 2.0 can, now, to generate scripts in Python.

Download :

http://www.microsoft.com/downloads/thankyou.aspx?FamilyID=09dfc342-648b-4119-b7eb-783b0f7d1178&displaylang=en


Note : scriptomatic is a generator of WMI's scripts, for Windows, (and
compatibles WBEM).



Good night
-- 
Michel Claveau



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


List problems in C code ported to Python

2005-01-16 Thread Lucas Raab
I'm done porting the C code, but now when running the script I 
continually run into problems with lists. I tried appending and 
extending the lists, but with no avail. Any help is much appreciated 
Please see both the Python and C code at 
http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py

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


Re: Newbie inheritance question.

2005-01-16 Thread Christophe Cavalaria
bwobbones wrote:

> Hi all,
> 
>   I'm a java programmer struggling to come to terms with python - bear
> with me!
> 
>   I'm trying to subclass a class, and I want to be able to see it's
> attributes also.  Here are my classes:
> 
> two.py
> *
> from one import one
> 
> class two(one):
> def __init__(self):
> print "two"
> 
> def printTestVar(self):
> print "testVar: " + str(self.testVar)
> *

You simply forgot to call the parent __init__. You have to do that
explicitely in Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List problems in C code ported to Python

2005-01-16 Thread Grant Edwards
On 2005-01-16, Lucas Raab <[EMAIL PROTECTED]> wrote:
> I'm done porting the C code, but now when running the script I 
> continually run into problems with lists. I tried appending and 
> extending the lists, but with no avail. Any help is much appreciated 
> Please see both the Python and C code at 
> http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py

  http://www.catb.org/~esr/faqs/smart-questions.html

-- 
Grant Edwards   grante Yow!  Did an Italian CRANE
  at   OPERATOR just experience
   visi.comuninhibited sensations in
   a MALIBU HOT TUB?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why would I get a TypeEror?

2005-01-16 Thread Stian Soiland
På 14. jan 2005 kl. 22:58 skrev Steven Bethard:
(Any mac users? How do I fix this to appear in Norwegian? =)
Note that if you're not comfortable with short-circuiting behavior, 
you can also code this using lazy evaluation:

(lambda: 1/x, lambda: 1.0e99)[x==0]()
.. and people wonder why so many Python people want to get rid of 
Lambda =)

--
Stian Søiland   You can't say civilization don't
Trondheim, Norway   advance, however, for in every war
http://www.soiland.no/  they kill you in a new way. [Rogers]
 =/\=
--
http://mail.python.org/mailman/listinfo/python-list


[perl-python] 20050116 defining a function

2005-01-16 Thread Xah Lee
© # the following is a example of defining
© # a function in Python.
©
© def fib(n):
© """This prints n terms of a sequence
© where each term is the sum of previous two,
© starting with terms 1 and 1."""
© result=[];a=1;b=1
© for i in range(n):
© result.append(b)
© a,b=b,a+b;
© result.insert(0,1)
© del result[-1]
© return result
©
© print fib(6)
©
© # note the use of .insert to insert 1 at
© # the beginning of a list, and Òdel
© # result[-1]Ó to remove the last element
© # in a list.  Also, the string
© # immediately following the function
© # definition is the function's
© # documentation.
©
© # the unusual syntax of a.insert() is
© # what's known as Object Oriented syntax style.
©
© # try writing a factorial function.
©
© ---
© # the equivalent perl version is this:
©
© =pod
©
© fib(n) prints n terms of a sequence where each
© term is the sum of previous two,
© starting with terms 1 and 1.
©
© =cut
©
© use strict;
© my @result;
© my ($a, $b);
©
© sub fib($) {
© my $n= @_[0];
© @result=();$a=1;$b=1;
© for my $i (1..$n){
©   push @result, $b;
©   ($a,$b)=($b,$a+$b);
© }
© unshift @result, 1;
© pop @result;
© return @result;
© }
©
© use Data::Dumper;
© print Dumper [fib(5)];
©
© # the =pod and =cut
© # is perl's way of demarking inline
© # documentation called POD.
© # see Òperldoc -t perlpodÓ
© # note: the empty line around it
© # is necessary, at least in perl version
© # 5.6 up to ~2002.
©
© # the Òuse strict;Ó is to make perl's
© # loose syntax stricter by enforcement.
© # Its use is encouraged by
© # perl gurus, but not all standard
© # packages use it.
©
© # the ÒmyÓ are used to declare variables.
© # necessary under Òuse strict;Ó
© # see Òperldoc -t strictÓ
©
© # the $ in fib($) is there to declare
© # that fib has a parameter of one scalar.
© # Its use is however optional and uncommon.
© # it is used for clarity but
© # has also met with controversy by
© # perl gurus as being unperl.
© # see Òperldoc perlsubÓ for ref.
©
© # the @_[0] is the first element of the
© # array @_. The @_ array is a predefined
© # array, holding arguments to subroutines.
© # see Òperldoc -t perlvarÒ
©
© # see
© # perldoc -tf unshift
© # perldoc -tf pop
©
© # the last line, [fib(5)], is basically
© # to make it a memory address of a copy of
© # the list returned by fib(5), so that
© # Dumper can print it.
© # see Òperldoc -t perldataÓ or perlref
© # for unix-styled technicalities.
©
©  Xah
©  [EMAIL PROTECTED]
©  http://xahlee.org/PageTwo_dir/more.html

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


Re: why are some types immutable?

2005-01-16 Thread Roy Smith
Torsten Mohr <[EMAIL PROTECTED]> wrote:
> reading the documentation (and also from a hint from this NG)
> i know now that there are some types that are not mutable.
> 
> But why is it this way?
> 
> From an overhead point of view i think it is not optimal,
> for example for a large string it could be much faster to
> have it changed in place, not generating a new one for
> every step in a change.

There has been a huge amount written about immutable types recently.  A 
search of the Google news archives should turn up tons of articles.

But, in a nutshell, the biggest reason for immutable types (tuples and 
strings) is that this lets they be dictionary keys.  If you want to know 
why dictionary keys have to be immutable, do that google search; there 
was a huge thread on exactly that subject just in the path month or two.

Making strings immutable has some good points (in addition to making 
them usable as dictionary keys) and bad points.  On the good side, it 
lets you intern strings and share memory.  For example:

>>> a = "fred"
>>> b = "fred"
>>> id (a)
3587520
>>> id (b)
3587520

when the interpreter saw the string "fred" in the second assignment 
statement, it looked it up and discovered that it already had a string 
with the value "fred", so it just re-used the same string (which is why 
they both have the same id).  This saves memory (which can become 
important when you have a lot of strings).  It also makes string 
comparison more efficient, since a test for equality can often be 
satisfied by just comparing id's.

The bad side is that, as you mentioned, things like:

s = ""
for c in getCharacters():
   s = s + c

become very inefficient: O(n^2).  Fortunately, there is an easy idiom to 
avoid that quadratic behavior.  You just accumulate the characters in a 
list, O(n), and then convert the list to a string with join(), also 
O(n).  Two O(n) passes is a heck of a lot better than a single O(n^2).

l = []
for c in getCharacters():
   l.append (c)
s = "".join (l)

Other types of in-place string manipulation could use the same trick.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generator expressions: performance anomaly?

2005-01-16 Thread John Machin
On Sun, 16 Jan 2005 12:18:23 GMT, "Raymond Hettinger"
<[EMAIL PROTECTED]> wrote:

>"John Machin" <[EMAIL PROTECTED]> wrote in message
>news:[EMAIL PROTECTED]
>> Please consider the timings below, where a generator expression starts
>> out slower than the equivalent list comprehension, and gets worse:
>>
>> >python -m timeit -s "orig=range(10)" "lst=orig[:];lst[:]=(x for x
>> in orig)"
> . . .
>> >python -m timeit -s "orig=range(20)" "lst=orig[:];lst[:]=(x for x
>> in orig)"
>
>This has nothing to do with genexps and everything to do with list slice
>assignment.
>
>List slice assignment is an example of a tool with a special case optimization
>for inputs that know their own length -- that enables the tool to pre-allocate
>its result rather than growing and resizing in spurts.  Other such tools 
>include
>tuple(), map() and zip().
>

My reading of the source: if the input is not a list or tuple, a
(temporary) tuple is built from the input, using PySequence_Tuple() in
abstract.c. If the input cannot report its own length, then that
function resorts to "growing and resizing in spurts", using the
following code:

if (j >= n) {
if (n < 500)
n += 10;
else
n += 100;
if (_PyTuple_Resize(&result, n) != 0) {

Perhaps it could be changed to use a proportional increase, like
list_resize() in listobject.c, which advertises (amortised) linear
time. Alternative: build a temporary list instead?


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


Re: threading and sockets ?

2005-01-16 Thread Irmen de Jong
ionel wrote:
how to make a efficient server.. please point me to some good and clear examples
I nominate SocketServer.ThreadingTCPServer from the standard library.
--Irmen
--
http://mail.python.org/mailman/listinfo/python-list


Re: generator expressions: performance anomaly?

2005-01-16 Thread bearophileHUGS
Nick Coghlan:
>There's a similar performance glitch associated with constructing a
tuple from a generator expression (with vanilla 2.4, detouring via list
is actually faster)

You look right:

.from time import clock
.print "[x for x in l], list(x for x in l), aux = list(x for x in l);
tuple(aux), tuple(x for x in l):"
.for np in range(13, 21):
.n = 1*2**np
.print "n:", n, " s:",
.l = xrange(n)
.t1 = clock()
.[x for x in l]
.t2 = clock()
.print round(t2-t1,3),
.
.t1 = clock()
.list(x for x in l)
.t2 = clock()
.print round(t2-t1,3),
.
.t1 = clock()
.aux = list(x for x in l)
.tuple(aux)
.t2 = clock()
.print round(t2-t1,3),
.
.#l = tuple(l) useless
.t1 = clock()
.tuple(x for x in l)
.t2 = clock()
.print round(t2-t1,3)


Output:
[x for x in l], list(x for x in l), aux = list(x for x in l);
tuple(aux), tuple(x for x in l):
n: 8192  s: 0.01 0.007 0.01 0.013
n: 16384  s: 0.024 0.019 0.021 0.032
n: 32768  s: 0.054 0.042 0.049 0.113
n: 65536  s: 0.111 0.078 0.101 0.088
n: 131072  s: 0.196 0.155 0.183 0.177
n: 262144  s: 0.436 0.385 0.429 1.832
n: 524288  s: 0.921 0.744 0.877 8.271
n: 1048576  s: 1.86 1.546 1.866 33.154

The timings for tuple(x for x in l) seem to grow as len(n)**2.
Bear hugs,
Bearophile

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


Re: generator expressions: performance anomaly?

2005-01-16 Thread Raymond Hettinger
[Raymond Hettinger]
> >List slice assignment is an example of a tool with a special case
optimization
> >for inputs that know their own length -- that enables the tool to
pre-allocate
> >its result rather than growing and resizing in spurts.  Other such tools
include
> >tuple(), map() and zip().

[John Machin]
> My reading of the source: if the input is not a list or tuple, a
> (temporary) tuple is built from the input, using PySequence_Tuple() in
> abstract.c. If the input cannot report its own length, then that
> function resorts to "growing and resizing in spurts", using the
> following code:
>
> if (j >= n) {
> if (n < 500)
> n += 10;
> else
> n += 100;
> if (_PyTuple_Resize(&result, n) != 0) {
>
> Perhaps it could be changed to use a proportional increase, like
> list_resize() in listobject.c, which advertises (amortised) linear
> time.

Check out the current source.  The time machine beat you to it.

Keep the faith,


Raymond Hettinger


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


RE: generator expressions: performance anomaly?

2005-01-16 Thread Delaney, Timothy C (Timothy)
Raymond Hettinger wrote:

> Check out the current source.  The time machine beat you to it.

Nick's other suggestion - that genexps propagate __len__ - might still
be interesting. Of course, it would only be applicable for unconditional
genexps(i.e. no if clause).

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


Re: Integration with java (Jpype vs. JPE)

2005-01-16 Thread Steve Menard
Cameron Laird wrote:
In article <[EMAIL PROTECTED]>,
Jon Perez  <[EMAIL PROTECTED]> wrote:
Can someone summarize in a nutshell what is the
difference between JPype and JPE?

JPE's the original.  It provided more functionality than JPype has
achieved so far, I believe (though that could change any day).  I
think no one now maintains JPE.
Someone really ought to include a couple of sentences to that effect
on the front page of http://jpype.sf.net/ >.
Well, Cameron summed it up pretty good :)
I'd add that The only major (and yes I know it is VERY major) 
funtionailty missing in JPype is the ability to subclass Java classes in 
Python.

On the other hand JPype will (soon) have functionality that JPE doesnt 
have. Java arrays can already (in 0.4) be iterated as regular Python 
collections. Version 0.5 will add that same behavior for Java 
collections (Map, List, Set, Iterator).

Of course, the above is based on the JPE documentation, because I havent 
been able to get JPE to work.

About Cameron's suggestion, sure. I'll do it as soon as I (or someone 
else) can get both JPype and JPE to work so they can be compared through 
more than just their respective documentation.

Steve
a.k.a devilwolf on sourceforge
--
http://mail.python.org/mailman/listinfo/python-list


Re: protecting the python code.

2005-01-16 Thread nell
Hi Steve,
First the "10x in advance" means thanks in advance.
The main importance of protecting my code is to save headache of
customers that want to be smart and change it and then complain on bugs
and problems.

10x

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


Re: Why would I get a TypeEror?

2005-01-16 Thread Steven Bethard
Stian Soiland wrote:
På 14. jan 2005 kl. 22:58 skrev Steven Bethard:
(Any mac users? How do I fix this to appear in Norwegian? =)
Note that if you're not comfortable with short-circuiting behavior, 
you can also code this using lazy evaluation:

(lambda: 1/x, lambda: 1.0e99)[x==0]()

.. and people wonder why so many Python people want to get rid of Lambda =)
Heh heh.  No I don't.  ;)
In fact, I don't ever use lambdas in any of my own "real" code.  But I 
don't mind being a little dirty when I post to c.l.py. ;)  I guess I 
could have written this as:

def inverse():
return 1/x
def largenum():
return 1.0e99
b = (inverse, largenum)[x==0]()
but I'm usually too lazy, and it's an ugly solution anyway, compared to 
the simple one which the OP was apparently trying to avoid:

if x != 0:
b = 1/x
else:
b = 1.0e99
=)
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: pygame + py2exe = bad exe. why?

2005-01-16 Thread Erik Bethke
M.E.Farmer wrote:
>
> Erik glad to see you were able to track it down.
> Have you been succesful in making the changes they mentioned?
> M.E.Farmer

Yes below is a simple script that works.  The key was that pygame uses
freesansbold.ttf as the default font and that is not copied over in the
normal py2exe process.  See the end of the setup script.

#!/usr/bin/env python
from distutils.core import setup
import py2exe, pygame
import glob, shutil

setup(windows=["mahjong.py"],
name='GoPets Mahjong',
version='0.3.1',
description='Mahjong for GoPets Users',
author='Erik Bethke',
author_email='[EMAIL PROTECTED]',
url='www.erikbethke.com',
py_modules=['mahjong','background','board','tile','textBox']
)

shutil.copytree('data', 'dist/data')
shutil.copyfile('freesansbold.ttf', 'dist/freesansbold.ttf')

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


Re: nntplib: abstraction of threads

2005-01-16 Thread Werner Amann
Rakesh schrieb:

> What I want is to *group the messages belonging to each thread* .

Hello

Why not sort with Message-ID and References?
Attention - it is a Newbie-Solution.

import nntplib

hamster = nntplib.NNTP('127.0.0.1', 119, 'user', 'pass')
resp, count, first, last, name = hamster.group('comp.lang.python')
resp, items = hamster.xover(first,last)

start_dic = {}
re_dic = {}
numb = 1

for id,subject,author,date,message_id,references,size,lines in items:
if 'Re:' not in subject:
start_dic[subject] = (author, message_id)
else:
re_dic[numb] = (subject, author, references)
numb += 1

resp = hamster.quit()

for a in start_dic:
print a
print start_dic[a][0]
for b in re_dic:
if start_dic[a][1] in re_dic[b][2]:
print '|'
print ' ->', re_dic[b][0]
print '   ', re_dic[b][1]
print 

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


Re: nntplib: abstraction of threads

2005-01-16 Thread Steve Holden
Werner Amann wrote:
Rakesh schrieb:

What I want is to *group the messages belonging to each thread* .

Hello
Why not sort with Message-ID and References?
Attention - it is a Newbie-Solution.
import nntplib
hamster = nntplib.NNTP('127.0.0.1', 119, 'user', 'pass')
resp, count, first, last, name = hamster.group('comp.lang.python')
resp, items = hamster.xover(first,last)
start_dic = {}
re_dic = {}
numb = 1

for id,subject,author,date,message_id,references,size,lines in items:
if 'Re:' not in subject:
start_dic[subject] = (author, message_id)
else:
re_dic[numb] = (subject, author, references)
numb += 1

resp = hamster.quit()
for a in start_dic:
print a
print start_dic[a][0]
for b in re_dic:
if start_dic[a][1] in re_dic[b][2]:
print '|'
print ' ->', re_dic[b][0]
print '   ', re_dic[b][1]
print 

Better still, do a Google search on "mail threading algorithm", 
implement the algorithm described in

  http://www.jwz.org/doc/threading.html
and post your implementation back to the newsgroup :-)
regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: why are some types immutable?

2005-01-16 Thread Dan Bishop
Roy Smith wrote:
> Torsten Mohr <[EMAIL PROTECTED]> wrote:
> > reading the documentation (and also from a hint from this NG)
> > i know now that there are some types that are not mutable.
> >
> > But why is it this way?
> >
> > From an overhead point of view i think it is not optimal,
> > for example for a large string it could be much faster to
> > have it changed in place, not generating a new one for
> > every step in a change.
>
> There has been a huge amount written about immutable types recently.
A
> search of the Google news archives should turn up tons of articles.
>
> But, in a nutshell, the biggest reason for immutable types (tuples
and
> strings) is that this lets they be dictionary keys.  If you want to
know
> why dictionary keys have to be immutable,

More precisely, dictionary keys can't be mutable in any way that
affects the result of the hash function or the == or != operators.

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


Re: protecting the python code.

2005-01-16 Thread Steve Holden
nell wrote:
Hi Steve,
First the "10x in advance" means thanks in advance.
The main importance of protecting my code is to save headache of
customers that want to be smart and change it and then complain on bugs
and problems.
10x 

I'd have understood "tnx", never seens 10x b4 :-)
Your concerns are what licensing's for. ("No support on modified copies" 
would be a good heading for a section addressing this issue).

With good enough release controls you can verify the code is unmodified 
using md5 checksums or similar.

If a customer's good enough at Python to disassemble your .pyc files, 
they will probably tell you they've modified your code when the support 
queries come in :-)

regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: why are some types immutable?

2005-01-16 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 "Dan Bishop" <[EMAIL PROTECTED]> wrote:

> Roy Smith wrote:
> > Torsten Mohr <[EMAIL PROTECTED]> wrote:
> > > reading the documentation (and also from a hint from this NG)
> > > i know now that there are some types that are not mutable.
> > >
> > > But why is it this way?
> > >
> > > From an overhead point of view i think it is not optimal,
> > > for example for a large string it could be much faster to
> > > have it changed in place, not generating a new one for
> > > every step in a change.
> >
> > There has been a huge amount written about immutable types recently.
> A
> > search of the Google news archives should turn up tons of articles.
> >
> > But, in a nutshell, the biggest reason for immutable types (tuples
> and
> > strings) is that this lets they be dictionary keys.  If you want to
> know
> > why dictionary keys have to be immutable,
> 
> More precisely, dictionary keys can't be mutable in any way that
> affects the result of the hash function or the == or != operators.

Yes, this is true.  In fact, I spent a fair amount of time in the 
referenced thread arguing exactly that point.  I was hoping people would 
take my hint, read the thread, and find that out :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


PythonMagick Update

2005-01-16 Thread Achim Domma (Procoders)
Hi,
I'm working on a new version of PythonMagick, a wrapper for 
GraphicsMagick. A first version is available at:

http://public.procoders.net/cgi-bin/trac.cgi/wiki/PythonMagick
Any feedback is very appreciated.
regards,
Achim
--
http://mail.python.org/mailman/listinfo/python-list


Re: Checking for X availability

2005-01-16 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Nils Nordman  <[EMAIL PROTECTED]> wrote:
>On Tue, Jan 11, 2005 at 03:32:01AM -0800, Flavio codeco coelho wrote:
>> So my question is: how can I check for the availability of X? i.e.,
>> How will my program know if its running in a text only console or in
>> console window over X?
>
>Well, one way to do it is to check whether the environment variable
>DISPLAY is set (which it is when running under X, and should not be
>otherwise).
.
.
.
While there certainly are successful programs that use this
approach, it's NOT true in general--at least in the generality
I encounter.  It can happen, for example, that a user withOUT
$DISPLAY in the environment launches

  interesting_application -display SOME_DISPLAY ...

Jeremy Bowers gives excellent advice elsewhere in this thread:
try, and use exceptions to learn what's going on; as you learn
more, relaunch the application with a refined command-line.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyChecker messages

2005-01-16 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Roger Binns <[EMAIL PROTECTED]> wrote:
.
.
.
>> runner.py:200: Function (detectMimeType) has too many returns (11)
>>
>> The function is simply a long "else-if" clause, branching out to different
>> return statements. What's wrong? It's simply a "probably ugly code" advice?
>
>That is also advice.  Generally you use a dict of functions, or some other
>structure to lookup what you want to do.
.
.
.
This interests me.  Let's be more precise.

Use, it's absolutely true that good Python style exploits dicts
far more than newcomers realize (although somewhat less than Lua,
a language which intriguingly pushes dictionary pragmatics to the
limit).  In particular, it is frequently the case that beginners'
appetite for a "switch" is best met by a lesson in use of a 
dictionary of functions.

HOWEVER, proliferation of functions itself adds weight.  My own
counsel is that a simple sequence of

  if ...
return ...
  if ...
return ...

often is exactly the right definition for a specific function.
I, incidentally, prefer this form over the 

  if ...
return ...
  elif ...
return ...

the original poster described.

So:  yes, "[g]enerally you use a dict of functions" when PyChecker
thinks you have "too many returns", but I do NOT advise it for the
specific case that appears to be at hand.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: module structure and import question

2005-01-16 Thread Rob Emmons
> yes i know it's related to search path, but i don't know how to set it in a
> practical way (beside hard coding).
> my concern is, if i want to create a custom module/library, i don't know
> what py file will import it and where the working directory should be.

Regarding where the current working directory is -- on Linux your right,
you probably don't know where it is going to be.  On Windows -- you can
pretty much demand that users set up the launcher so that your python
program is opened in a specific location -- typically the root directory
of the installed package.  So in the windows situation -- if all your
components are in that package directory you can access everything via
relative roots.  Linux is not so easy -- I'll get to that.

On the other hand, if your installing a general directory library module
that your going to use from a variety of other programs, then you need to
have the installer setup things so other applications can find it.  The
standard way to do this is to use the distutils package that is part of the
python distribution to install these modules in a standard location which
should already be in the search path.  If you don't want to do that you
have to do something special:  on windows create a registry entry that
can be accessed and looked up probably, or setup the default python path
for your system (or user) to include the extra directories, or like GNOME
does on Linux -- create a script in the executable search path
that your program or installer can run -- and have it return the path you 
need. 

So on the application side, you'd find out the location of the library as
described above and set sys.path.  You can either do this at launch time
in your main program -- or you can have the installer hard code it at the
top of the main program.

This is not really any different then for example using shared libraries. 
You either need to install all of your modules in the search path to start
with or you need to modify the search path by some method.

There is one more thought -- if you want to find out where the python
module is in the file system -- there are sometimes ways to do this --
I've never done this but I have some notes somewhere about this.  This
might also be helpful in finding directories for example.  If your
interested in this -- maybe someone else here can remember?
 
> But if i put a set of classes in a py file as a module,  will it increase
> the dependency of each class?
> back to my example, of course, i can put BaseA and ClassA together in one py
> file. what should i do when i need to add one more class later, "ClassB",
> which also extend BaseA. Put it into the same file or in a new file? if put
> in in the same file, i think it should difficult to maintain versioning.

Versioning -- hmm.  Well I think it depends.  If ClassB is intended to be
a general capability that you want to add to to moduleA (the module with
BaseA and ClassA), then add it to moduleA but make the module upwardly
compatible.  If you want to track versions, then just keep old version
snapshots if you need to or use something like CVS to do it for you.  I'm
pretty basic so I keep old copies but try to make my general libraries
upwardly compatible if possible.

Of course on the other hand, if the new class classB has a special function
then I'd either create a new module, or I'd just include it into my main
program module, or some other application module.  To merge the functions
just import what you need into that module.  I for example often use "from
mymodule import *" which imports everything rather than the limited
imports you used -- nothing wrong with either, just a matter of taste. I
also often use "import" and write the full module name when I reference
things too. 

The point is -- I personally think one should look at modules as being
collections of functions, classes, and other constructs that form
librararies rather than putting each class and function in a separate
module.

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


Re: List problems in C code ported to Python

2005-01-16 Thread Michael Hoffman
Lucas Raab wrote:
Please see both the Python and C code at 
http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py
If you post a small testcase here you are much more likely to get helped.
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: why are some types immutable?

2005-01-16 Thread Peter Maas
Torsten Mohr schrieb:
reading the documentation (and also from a hint from this NG)
i know now that there are some types that are not mutable.
But why is it this way?
Immutable types (e.g. strings, tuples) allow for code optimization
in some situations and can be used as dictionary keys. For the latter
reason see:
http://www.python.org/moin/DictionaryKeys
--
---
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: How to del item of a list in loop?

2005-01-16 Thread John Machin

skull wrote:
> According to Nick's article, I added three 'reversed' methods to your
provided
> test prog. and the result turned out method_reversed is faster than
others except  the 'three' case.
> Following is my modified version:
[snip]
> def method_reversed_idx(lst):
> idx = 0
> for i in reversed(lst):
> if i == 2:
> del lst[idx]
> idx += 1

There appears to be a problem with this one:

>>> def method_reversed_idx(lst):
... idx = 0
... for i in reversed(lst):
... if i == 2:
... del lst[idx]
... idx += 1
...
>>> lst=[1,2,3];method_reversed_idx(lst);print lst
[1, 3]
>>> lst=[2,1,3];method_reversed_idx(lst);print lst
[2, 1]
>>> lst=[1,3,2];method_reversed_idx(lst);print lst
[3]
>>>

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


Re: Executing a script created by the end user

2005-01-16 Thread Steven Bethard
Craig Howard wrote:
I am working on a python project where an object will have a script that 
can be edited by the end user: object.script

If the script is a simple one with no functions, I can easily execute it 
using:
exec object.script

But if the object script is a bit more complicated, such as the example 
below, my approach does not  work:

def main():
hello1()
hello2()
def hello1():
print 'hello1'
def hello2():
print 'hello2'
What do you want to do if you get a script like this?  Run main?  You 
could do something like:

py> s = """
... def main():
... hello1()
... hello2()
...
... def hello1():
... print 'hello1'
...
... def hello2():
... print 'hello2'
... """
py> d = {}
py> exec s in d
py> d["main"]()
hello1
hello2
(Actually, you don't need to exec it in d, that's probably just good 
practice.)

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


Re: import problems *newbie*

2005-01-16 Thread mike kreiner
Thanks for your help Steve and F. Petitjean. Sorry for taking so long
to get back, I was away from my lab for a few days.

The path to my directory was not included in the sys.path list. Adding
a my.pth file to the site-packages directory fixed the import problem.
F. Petitjean, I originally edited the PYTHONPATH because "Learning
Python," the O'Reilly book, says to do so. I like your and Steve's
solutions better--editing the PYTHONPATH seems a little unwieldy--but
just to satisfy my curiosity, what are some of the reasons these
methods are preferable?

Steve, as far as finding out the cause of this problem, I muddled
around python and the registry for a while, but nothing jumped out at
me. The only thing I can think of is that I have both Python 2.3 and
2.4 installed, and I'm currently working in 2.3. I thought that
PYTHONPATH was an environment variable, so having two different
versions wouldn't affect it, but I was wondering...should I bother
uninstalling 2.4 to see if the prob gets fixed? Other than that I'm
still something of a newbie, but I'd love to actually help fix this bug
if you can think of anything for me to try (oh joy, my first open
source contribution!). Thanks.

~mike

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


Re: Excel module for Python

2005-01-16 Thread Erwin S. Andreasen
Simon Brunning <[EMAIL PROTECTED]> writes:

> On Wed, 12 Jan 2005 23:19:44 +0800, sam <[EMAIL PROTECTED]> wrote:
>>
>> No, I don't use MS windows. I need to generate Excel file by printing
>> data to it, just like Perl module Spreadsheet::WriteExcel.

> If you need to write out formulae, formratting, that kind of thing,
> then I think you'll need to write a 'real' Excel file. I don't have a
> clue how to do that - sorry.

There's actually an ancient open spreadsheet format called SYLK which
is a step above CSV: it allows formatting of data, formulas etc.

Google for SYLK to get the rather sparse specification (and skip over
the first few links!)

If you want to generate "real" Office files from UNIX, another
alternative is to automate OpenOffice (which has a COM-like interface
too) or generate OO XML files and feed them to OO asking to conver
them with a bit of OO macro magic.



-- 
===
<[EMAIL PROTECTED]>Herlev, Denmark 
http://www.andreasen.org/> <*>   
===

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


Re: List problems in C code ported to Python

2005-01-16 Thread Lucas Raab
Grant Edwards wrote:
On 2005-01-16, Lucas Raab <[EMAIL PROTECTED]> wrote:
I'm done porting the C code, but now when running the script I 
continually run into problems with lists. I tried appending and 
extending the lists, but with no avail. Any help is much appreciated 
Please see both the Python and C code at 
http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py

  http://www.catb.org/~esr/faqs/smart-questions.html
I didn't expect to get bitched out just because I didn't follow "protocol."
--
http://mail.python.org/mailman/listinfo/python-list


Re: List problems in C code ported to Python

2005-01-16 Thread Paul McGuire
"Lucas Raab" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> I'm done porting the C code, but now when running the script I
> continually run into problems with lists. I tried appending and
> extending the lists, but with no avail. Any help is much appreciated
> Please see both the Python and C code at
> http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and
engima.py
>
> TIA

I didn't actually run your script, but you have some fundamental things to
fix first.  Here are some corrections that will get you closer:

- Single-character strings are still strings as far as Python is concerned.
Unlike C's distinction of single quotes for single characters (which allow
you to do integer arithmetic) and double quotes for string literals (which
don't support integer arithmetic), Python uses either quoting style for
strings.  So "A" == 'a' is true in Python, not true in C.  To do single-char
arithmetic, you'll need the ord() and asc() functions, so that instead of
c-'A'
you'll need
ord(c)-ord('A')
(and another little tip - since the ord('A') is likely to be invariant, and
used *heavily* in a function such as an Enigma simulator, you're best off
evaluating it once and stuffing it into a global, with an unimaginitive name
like ord_A = ord('A')

-Line 42: You are testing c == string.alpha_letters, when I think you
*really* want to test c in string.alpha_letters.

- encipher_file - the C version of this actually reads the file and calls
encipher() with each character in it.  Your Python version just calls
encipher() with the complete file contents, which is certain to fail.
(another tip - avoid variable names like 'file', 'string', 'list', 'dict',
etc. as these collide with global typenames - also, your variable naming is
pretty poor, using "file" to represent the filename, and "filename" to
represent the file contents - err???)

- usage() - print("blahblah \n") - the trailing \n is unnecessary unless you
want to double-space your text

Although you say you are "done porting the C code", you really have quite a
bit left to do yet.  You should really try to port this code a step at a
time - open a file, read its contents, iterate through the contents, call a
method, etc.  "Big-bang" porting like this is terribly inefficient!

-- Paul


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


Re: List problems in C code ported to Python

2005-01-16 Thread Roy Smith
"Paul McGuire" <[EMAIL PROTECTED]> wrote:
> "A" == 'a' is true in Python, not true in C.

It could be true in C, if the string is stored in very low memory :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List problems in C code ported to Python

2005-01-16 Thread Michael Hoffman
Paul McGuire wrote:
So "A" == 'a' is true in Python, not true in C.
>>> "A" == 'a'
False
I think you meant:
>>> "A" == "A"
True
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: List problems in C code ported to Python

2005-01-16 Thread Irmen de Jong
Paul McGuire wrote:
So "A" == 'a' is true in Python, not true in C. 
It's not true in Python either.
You probably meant to say:   "a" == 'a'
(lowercase a)
--Irmen
--
http://mail.python.org/mailman/listinfo/python-list


Re: List problems in C code ported to Python

2005-01-16 Thread Michael Hoffman
Lucas Raab wrote:
Grant Edwards wrote:
  http://www.catb.org/~esr/faqs/smart-questions.html
I didn't expect to get bitched out just because I didn't follow "protocol."
I didn't see anyone bitch you out. And you were lucky that one
person was kind enough to go through your web site and make some
suggestions. If you had written a better question I guarantee you would
have had more people answering your question sooner.
Oh yeah, and:
http://www.catb.org/~esr/faqs/smart-questions.html#not_losing
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: import problems *newbie*

2005-01-16 Thread Grig Gheorghiu
In my experience (as a tester), it is easier to deal with PYTHONPATH
than to add the my.pth file to the site-packages directory. The main
reason is that I have my custom packages and modules in a directory
tree that I deploy on many clients/servers/platforms/OS versions, some
running different versions of Python. I found that I solve my import
problems by adding one line to .bash_profile, which sets PYTHONPATH to
the parent directory of my custom directory tree. Or, on Windows, I add
an Environment variable, call it PYTHONPATH, and set it to the
necessary directory. The alternative would be to hunt for the
site-packages directory (of which there might be several) on all my
systems.

I guess it's a matter of taste in the end, but I do find the PYTHONPATH
approach more suitable for automation and scripting, particularly when
dealing with a large number of systems. 

Grig

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


Re: List problems in C code ported to Python

2005-01-16 Thread Michael Hoffman
Michael Hoffman wrote:
Paul McGuire wrote:
So "A" == 'a' is true in Python, not true in C.
I think you meant:
 >>> "A" == "A"
True
Er, "A" == 'A'
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: python mode indentation problem

2005-01-16 Thread Bob Smith
Xah Lee wrote:
© ok, here's the ordeal.
©
© for i in range(5):
© print i
© for i in range(2):
©   print i, 'tt'
©   for i in [3]:
©   print i
©   for i in [32]:
©   print i
©
© # 1 level, 4 space
© # 2 level, 1 tab
© # 3 level, 1 tab, 4 spaces
© # 4 level, 2 tabs.
©
© who the fuck coded the python mode in emacs? fuckhead please peruse:
© http://xahlee.org/UnixResource_dir/writ/responsible_license.html
I hope you never need a favor or interview for a job with someone who 
reads news groups. You're committing eSuicide by posting insulting rants 
such as this. All you accomplish is to isolate yourself.

Try to be friendly. Ideas are only half the battle... presentation is 
the other half. You have some good and valid ideas, but your 
presentation is offensive and condescending. Your ideas are like golden 
coins wrapped in horse shit. Personally, I've had enough of your horse 
shit... perhaps I speak for others as well.
--
http://mail.python.org/mailman/listinfo/python-list


Re: List problems in C code ported to Python

2005-01-16 Thread Grant Edwards
On 2005-01-16, Lucas Raab <[EMAIL PROTECTED]> wrote:

>>>Please see both the Python and C code at 
>>>http://home.earthlink.net/~lvraab. The two files are ENIGMA.C
>>>and engima.py
>>
>>   http://www.catb.org/~esr/faqs/smart-questions.html
>
> I didn't expect to get bitched out just because I didn't
> follow "protocol."

You didn't get "bitched out".  You did get some very sound
advice. You want help solving a problem, and there are ways you
can greatly increase the chances that you'll get help with your
problem.  After being told the best ways to get help, you
whined about it rather than following it.

Nobody owes you anything. 

Remember that.

[You're darned lucky somebody did take the time to go to your
web site and proof your code for you after your posting said in
effect "I'm too lazy to compose and post a precise question, so
go look at my program and fix it for me."]

Now, go back and read the smart questions reference.

-- 
Grant Edwards   grante Yow!  Hello? Enema
  at   Bondage? I'm calling
   visi.combecause I want to be happy,
   I guess...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [perl-python] 20050115, for statement

2005-01-16 Thread Peter Hansen
Jeremy Bowers wrote:
(Hell, five days into Python and some people are already producing working
Backgammon games (I think that was the post last week), and Xah Lee here
is still on for loops! Woo! Go Xah!)
Mah Jongg, actually (if we're thinking of the same post), which
name is often applied in the world of computer games to a what
amounts to the old game of "Concentration" (rather than the real
Mah Jongg which bears no more resemblance to the computerized
version than Bridge bears to Go Fish).  The player merely turns
over cards/tiles two at a time and any identical pairs are removed.
A backgammon game, with the computer actually playing against a
human and all the logic that entails, would be much more sophisticated,
and rather more work.
...not to diminish the impressiveness of someone new to Python
building a visually attractive GUI application in only a few days
and delivering it to the web which in several ways is far more
than I've contributed in over five years. ;-)  (Doffs hat to the
former newbie who achieved this.)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


[perl-python] 20050117, filter, map

2005-01-16 Thread Xah Lee
© # -*- coding: utf-8 -*-
© # Python
©
© # the "filter" function can be used to
© # reduce a list such that unwanted
© # elements are removed.
© # example:
©
© def even(n): return n % 2 == 0
© print filter( even, range(11))
©
©
© # the "map" function applies a function
© # to all elements of a list. Example:
©
© def square(n): return n*n
© print map(square, range(11))
©
© 
© # similar perl versions
©
© use Data::Dumper;
© sub even {return $_[0]%2==0};
© print Dumper[ grep {even $_} (0..10)];
©
©
© # sub square {$n=shift;$n**2;};
© sub square {(shift)**2;};
© print Dumper [ map {square($_)} (0..10)];
©
© # the codes above showcase some syntax
© # variations commonly found in perl code
© # base
©
© -
©
© # in Mathematica for example, filter is
© # akin to Apply and map is MapThread.
© # The standard Map can be applied
© # according to a level spec of trees
© # and there's also MapAt, Nest,
© # NestList...any many more powerful
© # functions that manipulates trees.
© # lisp languages often have a subset
© # of it.
©
© 
© Note: this post is from the Perl-Python
© a-day mailing list at
© http://groups.yahoo.com/group/perl-python/
© to subscribe, send an email to
© [EMAIL PROTECTED] if
© you are reading it on a web page,
© program examples may not run because
© html conversion often breaks the code.
©
©   Xah
©   [EMAIL PROTECTED]
©   http://xahlee.org/PageTwo_dir/more.html

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


Re: List problems in C code ported to Python

2005-01-16 Thread Paul McGuire
"Michael Hoffman" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Michael Hoffman wrote:
> > Paul McGuire wrote:
> >> So "A" == 'a' is true in Python, not true in C.
> > I think you meant:
> >
> >  >>> "A" == "A"
> > True
>
> Er, "A" == 'A'
> -- 
> Michael Hoffman

Yeah, that's the one I meant...  :)

-- Paul


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


strange note in fcntl docs

2005-01-16 Thread John Lenton
In the fnctl docs for both python 2.3 and 2.4 there is a note at the
bottom that says

The os.open() function supports locking flags and is available on
a wider variety of platforms than the lockf() and flock()
functions, providing a more platform-independent file locking
facility.

however, in neither of those versions does os.open support any kind of
mysterious "locking flags", nor is there any reference in os to any
kind of locking magic (nor do any C open()s I know of support any kind
of locking semantics). The note seems bogus; am I missing something,
or should it be elided?

-- 
John Lenton ([EMAIL PROTECTED]) -- Random fortune:
Are Linux users lemmings collectively jumping off of the cliff of
reliable, well-engineered commercial software?
-- Matt Welsh


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

Re: [perl-python] 20050117, filter, map

2005-01-16 Thread Steven Bethard
Xah Lee wrote:
© Note: this post is from the Perl-Python
© a-day mailing list at
© http://groups.yahoo.com/group/perl-python/
Is there any chance you could post these all as part of the same thread? 
  That would be really nice for those of us who aren't interested -- 
then we could just ignore the thread...

Thanks in advance,
Steve
--
http://mail.python.org/mailman/listinfo/python-list


fefinining % of c'm'y and k

2005-01-16 Thread moshebg
hello
i need a program (and pleas shoe me the modol in the softwar) that :
if i have a scaned photo
i want to define out of each poligon color ,as it seems in the photo,
the cmyk
in % (percets) of the color/
4 exampl from poligon color orang defin the cmyk in %
like that: (example)
c: 30%
m:56%
y:78%
k: 10%
moshe
thanks

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


RE: fefinining % of c'm'y and k

2005-01-16 Thread Delaney, Timothy C (Timothy)
[EMAIL PROTECTED] wrote:

> hello
> i need a program (and pleas shoe me the modol in the softwar) that :
> if i have a scaned photo
> i want to define out of each poligon color ,as it seems in the photo,
> the cmyk
> in % (percets) of the color/
> 4 exampl from poligon color orang defin the cmyk in %
> like that: (example)
> c: 30%
> m:56%
> y:78%
> k: 10%

This site will assist you greatly.
http://www.catb.org/~esr/faqs/smart-questions.html

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


Re: [perl-python] 20050117, filter, map

2005-01-16 Thread Erik Max Francis
Steven Bethard wrote:
Is there any chance you could post these all as part of the same thread? 
   That would be really nice for those of us who aren't interested -- 
then we could just ignore the thread...
Or, better yet, not posting it at all.  He's got his mailing list, what 
does he need to post it here for?

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  Make it come down / Like molasses rain
  -- Sandra St. Victor
--
http://mail.python.org/mailman/listinfo/python-list


Re: fefinining % of c'm'y and k

2005-01-16 Thread John Lenton
On Sun, Jan 16, 2005 at 09:57:46PM -0800, [EMAIL PROTECTED] wrote:
> hello
> i need a program (and pleas shoe me the modol in the softwar) that :
> if i have a scaned photo
> i want to define out of each poligon color ,as it seems in the photo,
> the cmyk
> in % (percets) of the color/
> 4 exampl from poligon color orang defin the cmyk in %
> like that: (example)
> c: 30%
> m:56%
> y:78%
> k: 10%
> moshe
> thanks

if I understand you correctly, then what you want to do is to
determine the amounts of each color an image has. I can think of two
ways of doing this, both using PIL; one faster,

  img = Image.open('foo.png')
  dot = img.resize((1,1),1)
  avg = dot.getpixel((0,0))
  for i in zip(dot.getbands(), avg):
  print "%s: %s" % i

and the other, thorougher

  img = Image.open('foo.png')
  width, height = img.size
  numdots = width*height
  avg = [sum(i)/numdots
 for i in zip(*[img.getpixel((x,y))
for x in xrange(width)
for y in xrange(height)])]
  for i in zip(dot.getbands(), avg):
  print "%s: %s" % i

the first is usually pretty close to the second, but YMMV.

Converting from these image-specific average values to CMYK is a
non-trivial problem (impossible in the general casew); see for example
http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2d0c54513c4970f7
where this issue was discussed.

-- 
John Lenton ([EMAIL PROTECTED]) -- Random fortune:
Excellent day to have a rotten day.


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

Re: [perl-python] 20050116 defining a function

2005-01-16 Thread Ala Qumsieh
Xah Lee wrote:
© my $n= @_[0];
Do you ever test your code before making fun of yourself in front of 
millions?

*plonk*
--Ala
--
http://mail.python.org/mailman/listinfo/python-list


Re: video analysis with python

2005-01-16 Thread Alexander 'boesi' Bösecke
Hi

Am 16.01.2005 12:44:27 schrieb Miki Tebeka:

> 1. There is PyMedia (http://pymedia.org/)

Is this library able to extract single images from a video? AFAICS it
can only convert videos from one format to another. But I didn't try it,
I've looked only in the docu.

Maybe pyVideo (http://www.geocities.com/rtrocca/python/) would be a
solution. But for me the AVIFile-Module doesn't work stable, it
regularly crashes the python-interpreter.

And there is a library for accessing DirectShow called PyDShowCam.

cu boesi
-- 
   |¯|/¯/¯¯¯\|¯| |¯|¯|  |¯|/¯/¯¯¯\|\||   #1671 : icq-intern
http://| / / /¯\ | | | | |  | / / /¯\ | (¯) | |¯¯#73628288 : icq-extern
 smb://| \ \ \_/ | `¯´ | |__| \ \ \_/ |  ¯ /|  ¯| boesi111 : aim
 ftp://|_|\_\___/|_|¯|_||_|\_\___/|_|¯¯ |_|¯  i171 : reallife
--
http://mail.python.org/mailman/listinfo/python-list


pythonnt_rc_d.h is missed when building python from source ?

2005-01-16 Thread cr999



I download the source code of Python-2.3.4 from python.org. 
But I can't build python from source under Win2000. The compiler complained that 
there is no pythonnt_rc_d.h file which is included in 
Python-2.3.4\PC\python_nt.rc.
 
Who knows the reason ?
 
Thanks.
 
Best Regards.
 
Robert. 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: video analysis with python

2005-01-16 Thread Ashot
On Mon, 17 Jan 2005 08:08:46 +0100, Alexander 'boesi' Bösecke  
<[EMAIL PROTECTED]> wrote:

Hi
Am 16.01.2005 12:44:27 schrieb Miki Tebeka:
1. There is PyMedia (http://pymedia.org/)
Is this library able to extract single images from a video? AFAICS it
can only convert videos from one format to another. But I didn't try it,
I've looked only in the docu.
Maybe pyVideo (http://www.geocities.com/rtrocca/python/) would be a
solution. But for me the AVIFile-Module doesn't work stable, it
regularly crashes the python-interpreter.
And there is a library for accessing DirectShow called PyDShowCam.
cu boesi
I haven't tried it yet, but yes its pretty full featured library, there is  
a tutorial here on extracting images:
 http://java.sun.com/products/java-media/jmf/2.1.1/solutions/FrameAccess.html

--
Ashot Petrosian
University of Texas at Austin, Computer Sciences
--
http://mail.python.org/mailman/listinfo/python-list