Re: code optimization (calc PI) / Full Code of PI calc in Python and C.

2007-01-04 Thread casevh

> Here is my attempt to convert the C code, not written with speed in mind
> and I was too lazy too time it.  :-)
>
> from itertools import izip
>
> def pi():
> result = list()
> d = 0
> e = 0
> f = [2000] * 2801
> for c in xrange(2800, 0, -14):
> for b, g in izip(xrange(c, 1, -1), xrange((c * 2) - 1, 0, -2)):
> d += f[b] * 1
> h, f[b] = divmod(d, g)
> d = h * b
> h, i = divmod(d, 1)
> result.append('%.4d' % (e + h))
> e = i
> return ''.join(result)
>

Your version: .36 seconds

It's ugly, but unrolling the divmod into two separate statements is
faster for small operands. The following takes .28 seconds:

from time import clock
from itertools import izip

def pi():
result = list()
d = 0
e = 0
f = [2000] * 2801
for c in xrange(2800, 0, -14):
for b, g in izip(xrange(c, 1, -1), xrange((c * 2) - 1, 0, -2)):
d += f[b] * 1
f[b] = d % g
h = d // g
d = h * b
h, i = divmod(d, 1)
result.append('%.4d' % (e + h))
e = i
return ''.join(result)

start_time = clock()
pi = pi()
print pi
print "Total time elapsed:", round(clock() - start_time, 2), "s"
print len(pi)

casevh

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


Re: C/C++, Perl, etc. to Python converter

2007-01-04 Thread John Nagle
Diez B. Roggisch wrote:
> 
>>
>> I think that it *is* possible to do it, but a whole lot of work had to
>> be done to achieve this. It is all about how many rules (like how to
>> convert this block of unreadable code of language X into a readable
>> python block) you are willing to find/program (and these are a lot). It
>> is a almost gigantic task to make this work proper, but it definitely
>> *is* possible.
> 
> 
> It is definitely _not_ possible. There are so many design decisions that 
> are differing based on what a language offers - e.g. generators, garbage 
> collection, precise control over memory layout and so on.

Inter-language translators have been written.  There's usually
a performance penalty, which can be severe when the idioms of
the languages are quite different.

Perl to Python translation might be worth doing.  The
languages have quite different syntax, but roughly the same
functionality.  You'd probably have to write a set of libraries
in Python with the equivalent definitions to their Perl
counterparts, but that's just time-consuming, not difficult.

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


pow() works but sqrt() not!?

2007-01-04 Thread siggi
Hi all,

this is a newbie question on :
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on
win32
PC with WinXP

In
http://www.python.org/doc/2.3.5/lib/module-math.html
I read:

"sqrt( x) Return the square root of x."

Now the test for module math with function pow():
---
>>> pow(9,9)
387420489

 Fine, but sqrt() fails:
---
>>> sqrt(9)
I get this error message

'Traceback (most recent call last):
  File "", line 1, in 
sqrt(9)
NameError: name 'sqrt' is not defined'

Same for sin() and cos(). ">>> Import math" does not help. Will I have to
define the sqrt() function first? If so, how?

Please help!

Thank you,

Siggi










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


NYC Python User Group Meeting

2007-01-04 Thread John Clark
Greetings!

The next New York City Python Users Group meeting is this Tuesday, Jan. 9th,
6:30pm at at the Millennium Partners office at 666 Fifth Avenue (53rd St.
and 5th Ave.) on the 8th Floor. We welcome all those in the NYC area who are
interested in Python to attend. However, we need a list of first and last
names to give to building security to make sure you can gain access to the
building. RSVP to [EMAIL PROTECTED] to add your name to the list. 

More information can be found on the yahoo group page:

http://tech.groups.yahoo.com/group/nycpython/

Hope to see you there!

-John


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


Re: When argparse will be in the python standard installation

2007-01-04 Thread Martin v. Löwis
Steven Bethard schrieb:
> If someone has an idea how to include argparse features into optparse,
> I'm certainly all for it. But I tried and failed to do this myself, so I
> don't know how to go about it.

It's not necessary that the implementation is retained, only that the
interface is preserved. So if you can come up with an implementation
that supports all optparse applications, and adds the additional
features, your implementation could replace the current optparse.
If you need to make incompatible changes, it would be best if you
could produce a list of such changes, so that optparse users can
review them to find out whether they are affected.

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


Re: minidom utf-8 encoding

2007-01-04 Thread Martin v. Löwis
fscked schrieb:
> Hi guys/gals.
> 
> I am trying to write and xml file from data parsed from a csv.
> 
> I can get everything to work except that I cannot get minidom to do -->
> ö which needless to say is driving me nuts.
> 
> Any suggestions?

Works fine for me:

py> d = minidom.Document()
py> r = d.createElement("root")
py> r.appendChild(d.createTextNode(u"\xf6"))

py> d.appendChild(r)

py> d.toxml()
u'\n\xf6'
py> print d.toxml()

ö

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


Re: pow() works but sqrt() not!?

2007-01-04 Thread tonisk
you forgot to import math module

>>> import math
>>> math.sqrt(9)
3.0

if you want math functions to your current namespace use:
>>> from math import *

--
Tõnis

On Jan 4, 10:13 am, "siggi" <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> this is a newbie question on :
> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on
> win32
> PC with WinXP
>
> Inhttp://www.python.org/doc/2.3.5/lib/module-math.html
> I read:
>
> "sqrt( x) Return the square root of x."
>
> Now the test for module math with function pow():
> --->>> pow(9,9)387420489
>
>  Fine, but sqrt() fails:
> --->>> sqrt(9)I get this error message
>
> 'Traceback (most recent call last):
>   File "", line 1, in 
> sqrt(9)
> NameError: name 'sqrt' is not defined'
>
> Same for sin() and cos(). ">>> Import math" does not help. Will I have to
> define the sqrt() function first? If so, how?
> 
> Please help!
> 
> Thank you,
> 
> Siggi

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


Re: Cannot build 2.5 on FC6 x86

2007-01-04 Thread Martin v. Löwis
Paul Watson schrieb:
> Martin v. Löwis wrote:
>> Paul Watson schrieb:
>>> ./configure
>>> make
>>> make test
>>>
>>> The result appears to hang after the test_tkl... line.  I had to kill
>>> the 'make test' process which terminated it.  Any suggestions?

The only suggestion then is that you (or somebody else) would need to
debug the interpreter to find out what is happening - this specific
behaviour is not supposed to happen.

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


Re: question on creating class

2007-01-04 Thread Thomas Heller
wcc schrieb:
> Hello,
> 
> How do I create a class using a variable as the class name?
> 
> For example, in the code below, I'd like replace the line
> 
> class TestClass(object):
> with something like
> class eval(className) (object):
> 
> Is it possible?  Thanks for your help.
> 
> className = "TestClass"
> 
> class TestClass(object):
> def __init__(self):
> print "Creating object of TestClass..."
> 
> def method1(self):
> print "This is a method."
> 
> if __name__ == "__main__":
> o = TestClass()
> o.method1()
> 
> --
> wcc
> 

You call 'type' to create a new-style class.  The signature is:
"type(name, bases, dict) -> a new type".

>>> def __init__(self):
... print "Creating object of TestClass..."
...
>>> def method1(self):
... print "This is a method"
...
>>> TestClass = type("TestClass", (), {"__init__": __init__, "method1": 
>>> method1})
>>>
>>>
>>> help(TestClass)
Help on class TestClass in module __main__:

class TestClass(__builtin__.object)
 |  Methods defined here:
 |
 |  __init__(self)
 |
 |  method1(self)
 |
 |  --
 |  Data and other attributes defined here:
 |
 |  __dict__ = 
 |  dictionary for instance variables (if defined)
 |
 |  __weakref__ = 
 |  list of weak references to the object (if defined)

>>> TestClass()
Creating object of TestClass...
<__main__.TestClass object at 0x00AED0B0>
>>> TestClass().method1()
Creating object of TestClass...
This is a method
>>>


Thomas

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


Re: pow() works but sqrt() not!?

2007-01-04 Thread siggi
Thank you very much, Tõnis!:

*** 1 ***
>you forgot to import math module
>>> import math

Nope, I did not! But I used sqrt(9), and not math.sqrt(9). The latter works
excellent, thank you! From now on, I will use "import math" and
"math.fuction()" for EVERY mathematical function, even for pow() etc. just
to be on the safe side!

*** 2 ***
>if you want math functions to your current namespace use:
>>> from math import *

What is a "namespace" and what is the difference between ">>>import math"
and ">>>from math import *" ?

Siggi


"tonisk" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
you forgot to import math module

>>> import math
>>> math.sqrt(9)
3.0

if you want math functions to your current namespace use:
>>> from math import *

--
Tõnis

On Jan 4, 10:13 am, "siggi" <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> this is a newbie question on :
> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]
> on
> win32
> PC with WinXP
>
> Inhttp://www.python.org/doc/2.3.5/lib/module-math.html
> I read:
>
> "sqrt( x) Return the square root of x."
>
> Now the test for module math with function pow():
> --->>> pow(9,9)387420489
>
>  Fine, but sqrt() fails:
> --->>> sqrt(9)I get this error message
>
> 'Traceback (most recent call last):
>   File "", line 1, in 
> sqrt(9)
> NameError: name 'sqrt' is not defined'
>
> Same for sin() and cos(). ">>> Import math" does not help. Will I have to
> define the sqrt() function first? If so, how?
>
> Please help!
>
> Thank you,
>
> Siggi




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

Re: question on creating class

2007-01-04 Thread Jussi Salmela
wcc kirjoitti:
> Hello,
> 
> How do I create a class using a variable as the class name?
> 
> For example, in the code below, I'd like replace the line
> 
> class TestClass(object):
> with something like
> class eval(className) (object):
> 
> Is it possible?  Thanks for your help.
> 
> className = "TestClass"
> 
> class TestClass(object):
> def __init__(self):
> print "Creating object of TestClass..."
> 
> def method1(self):
> print "This is a method."
> 
> if __name__ == "__main__":
> o = TestClass()
> o.method1()
> 
> --
> wcc
> 

I'm curious: what is the original problem that you are trying to solve?

The following works, but note that I'm no Python expert and if any of 
the regular wizards around here says that doing these kind of things is 
sick, I'm gonna agree 100%  ;)

className = "TestClass2"

class TestClass(object):
 def __init__(self):
 print "Creating object of TestClass..."

 def method1(self):
 print "This is a method."

exec('class ' + className +
 '''(object):
 def __init__(self):
 print "Creating object of TestClass2..."

 def method1(self):
 print "This is a method1 of TestClass2."
''')

if __name__ == "__main__":
 o = TestClass()
 o.method1()
 o2 = TestClass2()
 o2.method1()
 o2 = locals()[className]()
 o2.method1()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where to ask questions related to comtypes?

2007-01-04 Thread Thomas Heller
wcc schrieb:
> Hello group,
> 
> Is there a separate mailing list for comtypes? Or this is the
> appropriate place to post questions related to this package(from Thomas
> Heller)? 

It seems the python-win32 mailing list is the place where the most COM knowledge
is, so that would be most appropriate.  Other places are *this* list or the
ctypes-users lists (since comtypes is based on ctypes).

Thomas

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


Re: pow() works but sqrt() not!?

2007-01-04 Thread Fredrik Lundh
siggi wrote:

> What is a "namespace" and what is the difference between ">>>import math"
> and ">>>from math import *" ?

http://preview.tinyurl.com/t4pxq

for more on this, *please* read the relevant sections in the tutorial. 
Python's all about namespaces, and trial and error is not a very good 
way to figure how they work.



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


Re: pow() works but sqrt() not!?

2007-01-04 Thread tonisk
> >if you want math functions to your current namespace use:
> >>> from math import *What is a "namespace" and what is the difference 
> >>> between ">>>import math"
> and ">>>from math import *" ?

for namespaces read this
http://www.network-theory.co.uk/docs/pytut/tut_68.html

import math creates new namespace "math" for names in that module, so
you can acess them by prefixing them with "math", like math.sqrt(9).
from math import * imports all names to your local scope, so you do not
have to prefix them, sqrt(9)

-- 
Tõnis

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


Re: array of class

2007-01-04 Thread Bruno Desthuilliers
Podi a écrit :
>>>Or more compactly:
>>>
>>>words = [Word(w) for w in 'this is probably what you want'.split()]
>>>print words
>>
>>I didn't want to introduce yet some more "confusing" stuff !-)
> 
> 
> Indeed, the for loop is perfectly fine and totally readable. Let's save
> the "confusing stuff" to the Perl folks.
> 

This is not what I meant. I do like list comprehensions and use them a 
lot - and I don't find anything "perlish" here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pow() works but sqrt() not!?

2007-01-04 Thread siggi
Thank you Tõnis, both for the link and your patient explanation :-)

Siggi


"tonisk" <[EMAIL PROTECTED]> schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
> >if you want math functions to your current namespace use:
> >>> from math import *What is a "namespace" and what is the difference 
> >>> between ">>>import math"
> and ">>>from math import *" ?

for namespaces read this
http://www.network-theory.co.uk/docs/pytut/tut_68.html

import math creates new namespace "math" for names in that module, so
you can acess them by prefixing them with "math", like math.sqrt(9).
from math import * imports all names to your local scope, so you do not
have to prefix them, sqrt(9)

-- 
Tõnis


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

Draw rectangle on a Window DC

2007-01-04 Thread Raymond
Hi:

I want to Draw rectangle on Dc when gived a position. Can you teach me? Let
me view your code?

 

Thanks.

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

Re: array of class / code optimization

2007-01-04 Thread Bruno Desthuilliers
mm a écrit :
> 
> Yes, it was the (), equivalent to thiks like new() create new object 
> from class xy.

Yeps. In Python there's no 'new' operator. Instead, classes are 
themselves 'callable' objects, acting as instance factory. It's very 
handy since it let's you replace a class with a factory function (or 
vice-versa) without impacting client code.

>>   s1.append(Word)
> 
> s1.append(Word())
> 
> But I was looking for a "struct" equivalent like in c/c++.

You can use a dict or a class.

> And/or "union". I can't find it.

What is your real use case ? Direct translation from one language to 
another usually leads to code that's both non-idiomatic and inefficient. 
IOW, don't try to write C++ in Python.

> Maybe you know a source (URL) "Python for c/c++ programmers" or things 
> like that.

Not really, but quite a lot of Python programmers come from the C++ 
world. FWIW, I'd say that the official Python tutorial should be enough 
to get you started. Then, and if you're at ease with OO, you may want to 
have a look at more advanced stuff like special methods and attributes, 
decriptors and metaclasses (here again documented on python.org).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting on multiple values, some ascending, some descending

2007-01-04 Thread Christophe
[EMAIL PROTECTED] a écrit :
> Raymond Hettinger:
>> The simplest way is to take advantage of sort-stability and do
>> successive sorts.  For example, to sort by a primary key ascending and
>> a secondary key decending:
>>L.sort(key=lambda r: r.secondary, reverse=True)
>>L.sort(key=lambda r: r.primary)
> 
> That's probably the faster and simpler way.
> The following solution is probably slow, memory-hungry, and it's not
> tested much so it may be buggy too, but it shows my idea, and bugs can
> be fixed:
> 
> class Inverter:
> def __init__(self, item, reversed=False):
> self.item = item
> self.reversed = reversed
> def __cmp__(self, other):
> if self.reversed:
> return cmp(other.item, self.item)
> else:
> return cmp(self.item, other.item)
> 
> data = [[1, "a", "b"], [1, "b", "d"], [1, "d", "a"]]
> reverses = [True, False, False]
> 
> print sorted(data, key=lambda subseq: map(Inverter, subseq, reverses))

Nice trick, but don't get too caught up using classes ;) Try that one 
instead for much better performance :

class Inverter:
 def __init__(self, item):
 self.item = item
 def __cmp__(self, other):
 return cmp(other, self.item)

def invert_if(item, reversed=False):
 if reversed:
 return Inverter(item)
 return item

data = [[1, "a", "b"], [1, "b", "d"], [1, "d", "a"]]
reverses = [True, False, False]

print sorted(data, key=lambda subseq: map(invert_, subseq, reverses))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: static object

2007-01-04 Thread Bruno Desthuilliers
Ben Finney a écrit :
(snip)
> The "Singleton" pattern does what you say here. Implementing a proper
> Singleton in Python is complicated and hard to understand.

Really ? Using __new__ and a class attribute, it doesn't seem so 
complicated - nor difficult to understand...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert Perl to Python

2007-01-04 Thread itoakya
pyperl - Perl for Python

"This is a Python extension module that makes it possible to embed Perl
interpreter(s) in any Python program.  It can be used to invoke
arbitrary Perl code, load any Perl modules and make calls directly
into Perl functions.  The Perl code invoked can call back into Python
as it see fit."
http://wiki.python.org/moin/PyPerl
At least, a pacific coexistence between Python and Perl.

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


Re: question on creating class

2007-01-04 Thread Steven D'Aprano
On Wed, 03 Jan 2007 23:27:57 -0800, wcc wrote:

> Hello,
> 
> How do I create a class using a variable as the class name?

Try a "class factory".

def create_class(classname):
class Klass(object):
def __init__(self):
print "Creating object of %s..." % self.__class__.__name__
def method(self):
print "This is a method."
k = Klass
k.__name__ = classname
return k


>>> K = create_class("TestClass")
>>> obj = K()
Creating object of TestClass...



-- 
Steven.

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


Re: pow() works but sqrt() not!?

2007-01-04 Thread Fredrik Lundh
"siggi" wrote:

> Nope, I did not! But I used sqrt(9), and not math.sqrt(9). The latter works
> excellent, thank you! From now on, I will use "import math" and
> "math.fuction()" for EVERY mathematical function, even for pow() etc. just
> to be on the safe side!

pow and math.pow are two slightly different things, though.  pow() works on
any type that supports power-of operations (via the __pow__ hook), while
math.pow treats everything as a 64-bit float:

>>> math.pow(2, 200)
1.6069380442589903e+060

>>> pow(2, 200)
1606938044258990275541962092341162602522202993782792835301376L

pow also takes a third modulo argument (pow(x,y,z) is equivalent to pow(x,y) % 
z,
but can be implemented more efficiently for certain data types).

 



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


Re: code optimization (calc PI)

2007-01-04 Thread Nick Craig-Wood
mm <[EMAIL PROTECTED]> wrote:
>  (Yes, I konw whats an object is...)
>  BTW. I did a translation of a pi callculation programm in C to Python. 
>  (Do it by your own... ;-)
>  Calc PI for 800 digs(?). (german: Stellen)
>  int a=1,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5;
>   for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)for(b=c;d+=f[b]*a,
>   f[b]=d%--g,d/=g--,--b;d*=b);}

Below you'll find my translation.  Note that I improved the algorithm
greatly.  Note the nice easy to read algorithm also!  This calculated
800 digits of pi in 0.1 seconds and 10,000 digits in 20 seconds.


"""
Standalone Program to calculate PI using python only

Nick Craig-Wood <[EMAIL PROTECTED]>
"""

import sys
from time import time

class FixedPoint(object):
"""A minimal immutable fixed point number class"""
__slots__ = ['value']   # __weakref__
digits = 25 # default number of digits
base = 10**digits

def __init__(self, value=0):
"""Initialise the FixedPoint object from a numeric type"""
try:
self.value = long(value * self.base)
except (TypeError, ValueError), e:
raise TypeError("Can't convert %r into long", value)

def set_digits(cls, digits):
"""Set the default number of digits for new FixedPoint numbers"""
cls.digits = digits
cls.base = 10**digits
set_digits = classmethod(set_digits)

def copy(self):
"Copy self into a new object"
new = FixedPoint.__new__(FixedPoint)
new.value = self.value
return new
__copy__ = __deepcopy__ = copy

def __add__(self, other):
"""Add self to other returning the result in a new object"""
new = self.copy()
new.value = self.value + other.value
return new
__radd__ = __add__

def __sub__(self, other):
"""Subtract self from other returning the result in a new object"""
new = self.copy()
new.value = self.value - other.value
return new
def __rsub__(self, other):
new = self.copy()
new.value = other.value - self.value
return new

def __mul__(self, other):
"""
Multiply self by other returning the result in a new object.  The
number of digits is that of self.

Note that FixedPoint(x) * int(y) is much more efficient than
FixedPoint(x) * FixedPoint(y)
"""
new = self.copy()
if isinstance(other, (int, long)):
# Multiply by scalar
new.value = self.value * other
else:
new.value = (self.value * other.value) // other.base
return new
__rmul__ = __mul__

def __div__(self, other):
"""
Divide self by other returning the result in a new object.  The
number of digits is that of self.

Note that FixedPoint(x) / int(y) is much more efficient than
FixedPoint(x) / FixedPoint(y)
"""
new = self.copy()
if isinstance(other, (int, long)):
# Divide by scalar
new.value = self.value // other
else:
new.value = (self.value * other.base) // other.value
return new
def __rdiv__(self, other):
if not isinstance(other, FixedPoint):
other = FixedPoint(other, self.digits)
return other.__div__(self)

def __str__(self):
"""
Convert self into a string.  This will be the integral part of
the number possibly preceded by a - sign followed by a . then
exactly n digits where n is the number of digits specified on
creation.
"""
if self.value < 0:
s = str(-self.value)
else:
s = str(self.value)
s = s.zfill(self.digits + 1)
s = s[:-self.digits] + "." + s[-self.digits:]
if self.value < 0:
s = "-" + s
return s

def __abs__(self):
"""Return the absolute value of self"""
new = self.copy()
if new.value < 0:
new.value = - new.value
return new

def __cmp__(self, other):
"""Compare self with other"""
return cmp(self.value, other.value)

def sqrt(n):
"""
Return the square root of n.  It uses a second order
Newton-Raphson convgence.  This doubles the number of significant
figures on each iteration.  This will work for any finite
precision numeric type.
"""
x = n / 2   # FIXME find a better guess!
old_delta = None
while 1:
x_old = x
x = (x + n / x) / 2
delta = abs(x - x_old)
if old_delta is not None and delta >= old_delta:
break
old_delta = delta
return x

def pi_agm(one = 1.0, sqrt=sqrt):
"""
Brent-Salamin Arithmetic-Geometric Mean formula for pi.  This
converges quadratically.

FIXME can increase the numbe

Re: Iterate through list two items at a time

2007-01-04 Thread Wade Leftwich

Wade Leftwich wrote:
> Jeffrey Froman wrote:
> > Dave Dean wrote:
> >
> > >  I'm looking for a way to iterate through a list, two (or more) items at a
> > > time.
> >
> > Here's a solution, from the iterools documentation. It may not be the /most/
> > beautiful, but it is short, and scales well for larger groupings:
> >
> > >>> from itertools import izip
> > >>> def groupn(iterable, n):
> > ... return izip(* [iter(iterable)] * n)
> > ...
> > >>> list(groupn(myList, 2))
> > [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)]
> > >>> list(groupn(myList, 3))
> > [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]
> > >>> list(groupn(myList, 4))
> > [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]
> > >>> for a,b in groupn(myList, 2):
> > ... print a, b
> > ...
> > 0 1
> > 2 3
> > 4 5
> > 6 7
> > 8 9
> > 10 11
> > >>>
> >
> > Jeffrey
>
> This works great except you lose any 'remainder' from myList:
>
> >>> list(groupn(range(10),3))
> [(0, 1, 2), (3, 4, 5), (6, 7, 8)]  # did not include (9,)
>
> The following might be more complex than necessary but it solves the
> problem, and like groupn()
> it works on infinite lists.
>
> from itertools import groupby, imap
> def chunk(it, n=0):
> if n == 0:
> return iter([it])
> grouped = groupby(enumerate(it), lambda x: int(x[0]/n))
> counted = imap(lambda x:x[1], grouped)
> return imap(lambda x: imap(lambda y: y[1], x), counted)
>
> >>> [list(x) for x in chunk(range(10), 3)]
> [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
>
> Note the chunks are iterators, not tuples as in groupn():
>
> >>> [x for x in chunk(range(10), 3)]
> [,
>  ,
>  ,
>  ]
>
>
> -- Wade Leftwich
> Ithaca, NY

Or, using generator expressions instead of imap and getting rid of the
lambdas --

from itertools import groupby

def chunk(it, n=0):
if n == 0:
return iter([it])
def groupfun((x,y)):
return int(x/n)
grouped = groupby(enumerate(it), groupfun)
counted = (y for (x,y) in grouped)
return ((z for (y,z) in x) for x in counted)

>>> [list(x) for x in chunk(range(10), 3)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

>>> [x for x in chunk(range(10), 3)]
[,
 ,
 ,
 ]

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


Re: Iterate through list two items at a time

2007-01-04 Thread Peter Otten
Wade Leftwich wrote:

> from itertools import groupby
> 
> def chunk(it, n=0):
> if n == 0:
> return iter([it])
> def groupfun((x,y)):
> return int(x/n)
> grouped = groupby(enumerate(it), groupfun)
> counted = (y for (x,y) in grouped)
> return ((z for (y,z) in x) for x in counted)
> 
 [list(x) for x in chunk(range(10), 3)]
> [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
> 
 [x for x in chunk(range(10), 3)]
> [,
>  ,
>  ,
>  ]

Note that all but the last of these generators are useless:

>>> chunks = [x for x in chunk(range(10), 3)]
>>> [list(x) for x in chunks]
[[], [], [], [9]] # did you expect that?

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


Extending Embedded Python and execute external script

2007-01-04 Thread Vertilka
What i need from my C application to do ?
1) To execute a python script from file.
2) The python script will call functions in my C application.

According to the answer from Ravi Teja (topic "C app and Python"), I
need to extend embedded python in my C application.

I saw several functions: PyRun_AnyFileExFlags, PyRun_SimpleFileExFlags,
PyRun_FileExFlags.

Questions:
1) Which one should i use in order to achieve what i need ?
2) I couldn't understand the differance betwwen the three ?
3) What is the difference between the "FILE *fp" and "const char
*filename" arguments of these functions. If i give a FILE*, why do i
need to give the file name ?

Tnx,
Vertilka

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


Re: Extending Embedded Python and execute external script

2007-01-04 Thread Fredrik Lundh
"Vertilka" <[EMAIL PROTECTED]> wrote:

> I saw several functions: PyRun_AnyFileExFlags, PyRun_SimpleFileExFlags,
> PyRun_FileExFlags.
>
> Questions:
> 1) Which one should i use in order to achieve what i need ?

PyRun_SimpleFile or PyRun_SimpleString should be good enough.  Using
SimpleString is more robust:

http://effbot.org/pyfaq/pyrun-simplefile-crashes-on-windows-but-not-on-unix-why.htm

and also lets you implement additional glue in Python code instead of in C/C++.

> 2) I couldn't understand the differance betwwen the three ?

AnyFile supports interactive devices, RunFile requires you to provide a custom
execution context.

> 3) What is the difference between the "FILE *fp" and "const char
> *filename" arguments of these functions. If i give a FILE*, why do i
> need to give the file name ?

Python needs the filename to be able to give meaningful error messages.

 



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


Re: pow() works but sqrt() not!?

2007-01-04 Thread siggi
Thanks for the explanation. I am astonished what an interpreted language is 
able to do!

"Fredrik Lundh" <[EMAIL PROTECTED]> schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
> "siggi" wrote:
>
>> Nope, I did not! But I used sqrt(9), and not math.sqrt(9). The latter 
>> works
>> excellent, thank you! From now on, I will use "import math" and
>> "math.fuction()" for EVERY mathematical function, even for pow() etc. 
>> just
>> to be on the safe side!
>
> pow and math.pow are two slightly different things, though.  pow() works 
> on
> any type that supports power-of operations (via the __pow__ hook), while
> math.pow treats everything as a 64-bit float:
>
 math.pow(2, 200)
> 1.6069380442589903e+060
>
 pow(2, 200)
> 1606938044258990275541962092341162602522202993782792835301376L
>
> pow also takes a third modulo argument (pow(x,y,z) is equivalent to 
> pow(x,y) % z,
> but can be implemented more efficiently for certain data types).
>
> 
>
> 


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


Re: Iterate through list two items at a time

2007-01-04 Thread Wade Leftwich
Peter Otten wrote:
> Wade Leftwich wrote:
>
> > from itertools import groupby
> >
> > def chunk(it, n=0):
> > if n == 0:
> > return iter([it])
> > def groupfun((x,y)):
> > return int(x/n)
> > grouped = groupby(enumerate(it), groupfun)
> > counted = (y for (x,y) in grouped)
> > return ((z for (y,z) in x) for x in counted)
> >
>  [list(x) for x in chunk(range(10), 3)]
> > [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
> >
>  [x for x in chunk(range(10), 3)]
> > [,
> >  ,
> >  ,
> >  ]
>
> Note that all but the last of these generators are useless:
>
> >>> chunks = [x for x in chunk(range(10), 3)]
> >>> [list(x) for x in chunks]
> [[], [], [], [9]] # did you expect that?
> In [48]: chunkgen = chunk(range(10), 3)

In [49]: for x in chunkgen:
   : print list(x)
   :
   :
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]

> Peter

That's an interesting gotcha that I've never run into when using this
function, because in practice I never put the generator returned by
chunk() inside a list comprehension.

In [51]: chunkgen = chunk(range(10), 3)

In [52]: [list(x) for x in chunkgen]
Out[52]: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

But, as you pointed out --

In [57]: chunkgen = chunk(range(10), 3)

In [58]: chunks = list(chunkgen)

In [59]: [list(x) for x in chunks]
Out[59]: [[], [], [], [9]]

So apparently when we list(chunkgen), we are exhausting the generators
that are its members. And if we do it again, we get rid of the [9] --

In [60]: [list(x) for x in chunks]
Out[60]: [[], [], [], []]

I'll admit that chunk() is needlessly tricky for most purposes. I wrote
it to accept a really lengthy, possibly unbounded, iterator and write
out 10,000-line files from it, and also to play with Python's new
functional capabilities.

-- Wade

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


Re: How do I add users using Python scripts on a Linux machine

2007-01-04 Thread Piet van Oostrum
> Sebastian 'lunar' Wiesner <[EMAIL PROTECTED]> (SW) wrote:

>SW> I don't see a problem with SUID on scripts. If you restrict write access
>SW> to the owner, modification is hardly possible. 
>SW> However, if you allow world-wide write access to your binaries and
>SW> scripts, both can easily be modified...

The scenario is as follows: Suppose the script starts with the line:
#!/usr/bin/python

(using #!/usr/bin/env python would be disastrous because the user could
supply his own `python interpreter' in his PATH.)

Now a malicious user can make a link to this file in his own directory,
e.g. to /Users/eve/myscript1. Because permissions are part of the file
(inode), not of the file name, this one is also suid.

Now she execs /Users/eve/myscript1. The kernel, when honoring suid scripts,
would startup python with effective uid root with the command line:
/usr/bin/env /Users/eve/myscript1

Now in another process eve changes the link /Users/eve/myscript1 to
point to another script /Users/eve/myscript2. If she manages to change the
link between the startup of the python executable and the interpreter
opening the file /Users/eve/myscript1, she has her own script running as
root.

Of course the timing is a bit critical but if you try often enough some
time it will succeed. The problem is the time window between starting the
executable and opening the script. There is no guarantee that the file will
be the same. It can only be made safe if interpreters can be passed inodes
or opened files by the kernel, but that is not how most interpreters work.
At least not python.
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pow() works but sqrt() not!?

2007-01-04 Thread Boris Borcic
siggi wrote:
> Hi all,
> 
> this is a newbie question on :
> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on
> win32
> PC with WinXP
> 
> In
> http://www.python.org/doc/2.3.5/lib/module-math.html
> I read:
> 
> "sqrt( x) Return the square root of x."
> 
> Now the test for module math with function pow():
> ---
 pow(9,9)
> 387420489
> 
>  Fine, but sqrt() fails:
> ---

BTW note that (of course) you can write pow(x,.5) or x**.5 for sqrt(x)
without any preliminary import statement
-- 
http://mail.python.org/mailman/listinfo/python-list


Best way to implement a timed queue?

2007-01-04 Thread Thomas Ploch
Hello folks,

I am having troubles with implementing a timed queue. I am using the
'Queue' module to manage several queues. But I want a timed access, i.e.
only 2 fetches per second max. I am horribly stuck on even how I
actually could write it. Has somebody done that before? And when yes,
how is the best way to implement it?

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


connection hangs

2007-01-04 Thread jeff . dyke
I am using ftplib in some code that does exactly what you would expect.
 It ftp's files.  Its running inside a service running on windows xp
and windows 2003 servers, approximately 20 installations each
installation sends between 100 and 1000 files per day. Occasionally the
process will hang completely and the only way to restart the service is
to kill the pythonservice.exe (via End Process in Task Manager) service
and start it.

I have turned on the full debugging, ftpobject.debug(1), and redirected
that stdout to a file and when the process hangs i see hundreds of
identical lines (*cmd* 'TYPE I') in the debug files.  See log except
below.  This command i see is only executed in two places, during the
storbinary and retrbinary methods.   When it hangs, it never gets a
response from the server and eventually locks up.

The connection does have a socket timeout of 10 seconds on the
connection, modifying the length of time has no affect on this issue.
Everything will work fine for weeks/months and then all of a sudden a
network issue will occur and the process will hang.  The process ONLY
hangs when transferring over the internet, it has never happened on a
LAN connection, even when i have removed all connectivity from the FTP
server mid upload.

Has anyone ever seen this?  or have any ideas how i could code around
it.


Thanks
Jeff

--- debug log 
*resp* '227 Entering Passive Mode  (##.##.##.##,173,244).'
*cmd* 'NLST *filematch*.xml'
*resp* '125 Data connection already open; Transfer starting.'
*resp* '226 Transfer complete.'
*cmd* 'USER username'
*resp* '331 Password required for username.'
*cmd* 'PASS '
*resp* '230 User username logged in.'
*cmd* 'TYPE I'
*resp* '200 Type set to I.'
*cmd* 'PASV'
*resp* '227 Entering Passive Mode (##.##.##.##,174,4).'
*cmd* u'STOR /path/to/filename.ext'
*resp* '125 Data connection already open; Transfer starting.'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
*cmd* 'TYPE I'
  you get the idea

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


Packaging up a Python/Twisted Matrix application...

2007-01-04 Thread Chaz Ginger
I have a rather large Python/Twisted Matrix application that will be run 
on Windows, Linux and perhaps Macs. I was wondering if there are any 
tools that can be used to create an installer that will bring in Python, 
Twisted Matrix, my application libraries and anything else I need?

I have tried using ezsetup with no luck (it seems not everything can be 
installed with it). I was hoping to find something as nice (and 
complete) as Perl's CPAN but can't seem to find anything.

Does anyone have any recommendations?

Peace,
Chaz.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Packaging up a Python/Twisted Matrix application...

2007-01-04 Thread Felipe Almeida Lessa
On 1/4/07, Chaz Ginger <[EMAIL PROTECTED]> wrote:
> I have a rather large Python/Twisted Matrix application that will be run
> on Windows, Linux and perhaps Macs. I was wondering if there are any
> tools that can be used to create an installer that will bring in Python,
> Twisted Matrix, my application libraries and anything else I need?

I haven't tried with Twisted, but I had success in using py2exe + Inno
Setup on a program dependent on Python + ReportLab + pygtk. As both
ReportLab and pygtk got even C extensions, I don't see why this setup
wouldn't work with Twisted.

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


Re: code optimization (calc PI) / New Algorithme for PI

2007-01-04 Thread Michael M.

Mainly, it was fload-div. Changed to int-div (python //) runs faster.

Yes, this "gmpy" sounds good for calc things like that.
But not available on my machine.
ImportError: No module named gmpy

Anyway, thanks for posting. This gmpy module can be very intersting.
But right now, the focus was, if it's possible to translate a strange C 
code into Python. And it is. Sure ;-)

Maybe, someone can also translate a very simple algorithm for calc a 
range of PI in Python. (Available Code for C.)
http://crd.lbl.gov/~dhbailey/

http://crd.lbl.gov/~dhbailey/bbp-codes/piqpr8.c

But seems to be removed? It was working last days. (Maybe removed from 
server.)


An other well known is: (but someone implemented this already in Python, 
slow, and, depends on the previouse calc values, like most other 
algorithmes.)

pi   01   01   01   01   01 01 01 01 01 01
__ = __ - __ + __ - __ + __-__+__-__+__-__
04   01   03   05   07   09 11 13 15 17 19 ...

   pi/4 = 1/1 - 1/3 + 1/5 - 1/7 + 1/9 ...


Or things like that:
http://numbers.computation.free.fr/Constants/PiProgram/pifast.html




> There is more than one way to skin this cat.  A better algorithm helps
> a lot.
> 
> If I really wanted lots of digits of pi from python I'd do it like
> this.  This is an example of the right tool for the job. 0.5ms looks
> pretty good to me!
> 
>>>> import math, gmpy
>>>> bits = int(800/math.log10(2))
>>>> start = time(); pi=gmpy.pi(bits); dt = time()-start
>>>> print "That took",dt,"seconds"
>That took 0.00055193901062 seconds
>>>> pi
>
> mpf('3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127372458700660631558817488152092096282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218611738193261179310511854807446237996274956735188575272489122793818301194912983367336244065664308602139494639522473719070217986094370277053921717629317675238467481846766940513200056812714526356082778577134275778960917363717872146844090122495343014654958537105079227968925892354201995611212902196086403441815981362977477130996051870721134998372978049951059731732816096318595024459455e0',2657)
>>>> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Packaging up a Python/Twisted Matrix application...

2007-01-04 Thread Chris Mellon
On 1/4/07, Chaz Ginger <[EMAIL PROTECTED]> wrote:
> I have a rather large Python/Twisted Matrix application that will be run
> on Windows, Linux and perhaps Macs. I was wondering if there are any
> tools that can be used to create an installer that will bring in Python,
> Twisted Matrix, my application libraries and anything else I need?
>
> I have tried using ezsetup with no luck (it seems not everything can be
> installed with it). I was hoping to find something as nice (and
> complete) as Perl's CPAN but can't seem to find anything.
>
> Does anyone have any recommendations?
>
> Peace,
> Chaz.
> --

For windows, py2exe is the de facto standard and it works fine with Twisted.

There are similar scripts for the other platforms but I'm not familiar
with them, I understand py2app is the standard for OS X.

Note that OS X and pretty much every version of linux ship with
Python, you might re-think your need to distribute a binary and
instead just use a distutils install.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to implement a timed queue?

2007-01-04 Thread Jan Dries
Thomas Ploch wrote:
> I am having troubles with implementing a timed queue. I am using the
> 'Queue' module to manage several queues. But I want a timed access, i.e.
> only 2 fetches per second max. I am horribly stuck on even how I
> actually could write it. Has somebody done that before? And when yes,
> how is the best way to implement it?

I don't know about "the best way" to implement it, but I once solved a 
similar problem with the following scenario.

The idea is that you create a "token" queue, a Queue object of the 
desired depth, 2 in your case. You then have a separate thread that, in 
a loop, puts two "tokens" on the queue and then puts itself to sleep for 
one second.

And the worker thread or threads that must be doing whatever twice per 
second try to get an object from the queue prior to doing their thing.

The following piece of code does the trick. Note that it allows worker 
threads to do something two times every second, and not once every half 
second, though it could easily be modified to accomodate that too.
Also note that the code below keeps running forever as worker threads 
never stop working. You will probably want to change that.

Regards,
Jan


import time
from Queue import Queue,Full,Empty
from thread import start_new_thread

class Manager(object):
 def __init__(self, number_of_workers=10, max_per_sec=5):
 self.MAX_PER_SEC = max_per_sec
 self.NUMBER_OF_WORKERS = number_of_workers
 self.timelimit = Queue(self.MAX_PER_SEC)
 self.donelock = Queue(0)
 self.finished = False

 def do_work(self,number):
 print "Starting worker thread %s" % number
 while True:
 if self.get_time():
 # do whatever can only be done x times per second
 print "Worker %s doing work" % number
 time.sleep(3)  # simulate worker doing some work

 self.signal_done()

 def signal_done(self):
 self.donelock.put(None,True)

 def wait_done(self):
 for i in range(0,self.MAX_PER_SEC):
 self.donelock.get(True)
 self.finished = True

 def feed_time(self):
 while not self.is_finished():
 for i in range(0,self.MAX_PER_SEC):
 self.insert_time()
 time.sleep(1)

 def insert_time(self):
 try:
 self.timelimit.put_nowait(None)
 except Full:
 pass

 def get_time(self):
 try:
 self.timelimit.get(True,10)
 return True
 except Empty:
 return False

 def is_finished(self):
 return self.finished

 def start_worker_threads(self):
 for i in range(0,self.NUMBER_OF_WORKERS):
 start_new_thread(self.do_work,(i + 1,))

 def start_time_thread(self):
 start_new_thread(self.feed_time,())

 def run(self):
 self.start_time_thread()
 self.start_worker_threads()
 self.wait_done()

def main():
 Manager(10,2).run()


if __name__ == "__main__":
 main()

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


Re: code optimization (calc PI) / New Algorithme for PI

2007-01-04 Thread casevh

> Yes, this "gmpy" sounds good for calc things like that.
> But not available on my machine.
> ImportError: No module named gmpy

What type of machine?

The home page for gmpy is http://sourceforge.net/projects/gmpy/

I have Windows versions available at http://home.comcast.net/~casevh/

casevh

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


Re: pow() works but sqrt() not!?

2007-01-04 Thread siggi
Thanks for that, too!

Would be interesting to learn how these different algorithms influence the 
precision of the result!?



"Boris Borcic" <[EMAIL PROTECTED]> schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
> siggi wrote:
>> Hi all,
>>
>> this is a newbie question on :
>> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] 
>> on
>> win32
>> PC with WinXP
>>
>> In
>> http://www.python.org/doc/2.3.5/lib/module-math.html
>> I read:
>>
>> "sqrt( x) Return the square root of x."
>>
>> Now the test for module math with function pow():
>> ---
> pow(9,9)
>> 387420489
>>
>>  Fine, but sqrt() fails:
>> ---
>
> BTW note that (of course) you can write pow(x,.5) or x**.5 for sqrt(x)
> without any preliminary import statement 


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


Re: code optimization (calc PI) / New Algorithme for PI

2007-01-04 Thread Michael M.
[EMAIL PROTECTED] wrote:

>>Yes, this "gmpy" sounds good for calc things like that.
>>But not available on my machine.
>>ImportError: No module named gmpy
> 
> 
> What type of machine?

Windoof with Cygwin.

> 
> The home page for gmpy is http://sourceforge.net/projects/gmpy/
> 
> I have Windows versions available at http://home.comcast.net/~casevh/
> 
> casevh
> 

If the binary works, I don't know. Maybe there is also a gmpy module 
already in Cygwin.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Wrapper for C# Com Object

2007-01-04 Thread bg_ie

Thomas Heller skrev:

> [EMAIL PROTECTED] schrieb:
> > [EMAIL PROTECTED] skrev:
> >
> >> Hi,
> >>
> >> I wish to write a Python wrapper for my C# COM object but am unsure
> >> where to start. I have a dll and a tlb file, and I can use this object
> >> in C via the following code -
> >>
> >> // ConsolApp.cpp : Defines the entry point for the console application.
> >> //
> >> #include "stdafx.h"
> >> #include "windows.h"
> >> #include "stdio.h"
> >> #import "C:\Documents and Settings\X\Mina dokument\Visual Studio
> >> 2005\Projects\X_COMObject\X_COMObject\bin\Debug\X_COMObject.tlb"
> >> using namespace X_COMObject;
> >>
> >> int _tmain(int argc, _TCHAR* argv[])
> >> {
> >>CoInitialize(NULL);
> >>
> >>X_COMObject::XCOM_InterfacePtr p(__uuidof(X_COMObject::XCOM_Class));
> >>XCOM_Interface *X_com_ptr ;
> >>X_com_ptr = p ;
> >>X_com_ptr->SetID(10);
> >>int x = X_com_ptr->GetID();
> >>printf("%d",x);
> >>getchar();
> >>
> >>return 0;
> >> }
> >>
> >> Can anyone offer me some tips as to how to do this in Python?
> >>
> >> Thanks very much for your help,
> >>
> >> Barry.
> >
> > This is what I've done so far, but I know I'm not doing this correctly.
> > Can anyone help me out?
> >
> > #import pythoncom
> > #pythoncom.CoInitialize()
>
> The above is unneeded if you use comtypes as below (and is unneeded
> when using pythoncom, as well).
>
> > from comtypes.client import GetModule, CreateObject
> >
> > module = GetModule("C:\\Documents and Settings\\X\\Mina
> > dokument\\Visual Studio
> > 2005\\Projects\\X_COMObject\\X_COMObject\\bin\\Debug\\X_COMObject.tlb")
> >
> You don't intantiate the interface, you have to instantiate the COM object.
> Something like
>
>   CreateObject("XCOM_Class")
>
> but of course you have to use the correct argument in the call - the progid
> of the COM object.
> Alternatively you can use the CoClass from the typelibrary, look into the
> generated module in the comtypes\gen directory for a class derived from
> comtypes.CoClass.
>
> InternetExplorer, for example, can be started in these ways:
>
> # using the progid:
> ie = CreateObject("InternetExplorer.Application")
>
> # using the clsid:
> ie = CreateObject("{0002DF01---C000-0046}")
>
>
> # using the coclass from the generated module:
> mod = GetModule("shdocvw.dll")
> ie = CreateObject(mod.InternetExplorer)
>
> Thomas

Thanks very much for your help.

I tried running the following code -

import win32com.client
scanObj = win32com.client.Dispatch("X_COMObject")

but im getting the following error -

Traceback (most recent call last):
  File
"C:\Python22\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
line 310, in RunScript
exec codeObject in __main__.__dict__
  File "C:\Python25\test.py", line 20, in ?
scanObj = win32com.client.Dispatch("Scania_COMObject")
  File "C:\Python22\Lib\site-packages\win32com\client\__init__.py",
line 95, in Dispatch
dispatch, userName =
dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
  File "C:\Python22\Lib\site-packages\win32com\client\dynamic.py", line
98, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "C:\Python22\Lib\site-packages\win32com\client\dynamic.py", line
78, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx,
pythoncom.IID_IDispatch)
com_error: (-2147221005, 'Invalid Class String', None, None)

I ran my C++ code again and it works fine. I also checked COM Browser
and my X_COMObject is present and I'm spelling it right.

Any ideas what the problem migth be?

Thanks again,

Barry.

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


Re: Sorting on multiple values, some ascending, some descending

2007-01-04 Thread Neil Cerutti
On 2007-01-03, dwelden <[EMAIL PROTECTED]> wrote:
> I have successfully used the sort lambda construct described in
> http://mail.python.org/pipermail/python-list/2006-April/377443.html.
> However, how do I take it one step further such that some
> values can be sorted ascending and others descending? Easy
> enough if the sort values are numeric (just negate the value),
> but what about text?
>
> Is the only option to define an external sorting function to
> loop through the list and perform the comparisons one value at
> a time?

Another trick is to factor the key application out of the sort.
This may be a good idea if when you want to minimize the number
of times your key function is called.

The idea is to mangle the list temporarily so you can use an
unkeyed sort, and then unmangle the sorted data. Here's a silly
example using a phone directory that's not stored in a format
that's easy to sort.

>>> a = [("Neil Cerutti", "8025552954"), ("Ted Smith", "8025552281"), ("Barny 
>>> Fife", "8025551105")]
>>> b = [(" ".join(reversed(x.split())), y) for (x, y) in a]
>>> b
[('Cerutti Neil', '8025552954'), ('Smith Ted', '8025552281'), ('Fife Barny', 
'8025551105')]
>>> b.sort()
>>> b
[('Cerutti Neil', '8025552954'), ('Fife Barny', '8025551105'), ('Smith Ted', 
'8025552281')]
>>> a = [(" ".join(reversed(x.split())), y) for (x, y) in b]
>>> a
[('Neil Cerutti', '8025552954'), ('Barny Fife', '8025551105'), ('Ted Smith', 
'8025552281')]

-- 
Neil Cerutti
Eddie Robinson is about one word: winning and losing. --Eddie Robinson's agent
Paul Collier
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: minidom utf-8 encoding

2007-01-04 Thread fscked

Martin v. Löwis wrote:
> fscked schrieb:
> > Hi guys/gals.
> >
> > I am trying to write and xml file from data parsed from a csv.
> >
> > I can get everything to work except that I cannot get minidom to do -->
> > ö which needless to say is driving me nuts.
> >
> > Any suggestions?
>
> Works fine for me:
>
> py> d = minidom.Document()
> py> r = d.createElement("root")
> py> r.appendChild(d.createTextNode(u"\xf6"))
> 
> py> d.appendChild(r)
> 
> py> d.toxml()
> u'\n\xf6'
> py> print d.toxml()
> 
> ö
>
> Regards,
> Martin

Well, let me clarify. If I just print it to the screen/console it works
fine, but when I do:

out.write( doc.toprettyxml())

it just removes the character that would be the "ö".

I can post the code if anyone wants to see it, but it is fairly
straightforward.

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


Using External Libraries with python?

2007-01-04 Thread Ognjen Bezanov
Hello,

I have some external C libraries I would like to use with python.

I have been searching on the internet and found many such
modules/bindings for libraries (e.g. Py-Lame) but have not yet
come across any information of how to actually go about creating such
bindings, so I was wondering if anybody here could point me in the right
direction?

Thank you!

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


Re: Best way to implement a timed queue?

2007-01-04 Thread Bjoern Schliessmann
Thomas Ploch wrote:

> I am having troubles with implementing a timed queue. I am using
> the 'Queue' module to manage several queues. But I want a timed
> access, i.e. only 2 fetches per second max. I am horribly stuck on
> even how I actually could write it. Has somebody done that before?
> And when yes, how is the best way to implement it?

If you use an event loop system you could derive a class from your
queue class whose "pop" method only returns an element if some
timer has run out. After the maximum number of fetches you'd have
to reset the timer.

Regards,


Björn

-- 
BOFH excuse #327:

The POP server is out of Coke

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


what is this?

2007-01-04 Thread Eric Price

Hello;
I'm studying some code examples from the python cookbook site. I came across 
this:


def colsplit(l, cols):
   rows = len(l) / cols
   if len(l) % cols:
   rows += 1
   m = []
   for i in range(rows):
   m.append(l[i::rows])
   return m

What I'd like to know is what is the double colon? What does it do?
   m.append(l[i::rows])

Thanks,
Eric

_
Type your favorite song.  Get a customized station.  Try MSN Radio powered 
by Pandora. http://radio.msn.com/?icid=T002MSN03A07001


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

Re: minidom utf-8 encoding

2007-01-04 Thread Martin v. Löwis
fscked schrieb:
> Well, let me clarify. If I just print it to the screen/console it works
> fine, but when I do:
> 
> out.write( doc.toprettyxml())
> 
> it just removes the character that would be the "ö".
> 
> I can post the code if anyone wants to see it, but it is fairly
> straightforward.

I find that hard to believe. There is no code in Python that does
removal of characters, and I can't see any other reason why it gets
removed.

OTOH, what I do get when writing to a file is a UnicodeError, when
it tries to convert the Unicode string that toxml gives to a byte
string.

So I recommend you pass encoding="utf-8" to the toprettyxml invocation
also.

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


Re: Using External Libraries with python?

2007-01-04 Thread Martin v. Löwis
Ognjen Bezanov schrieb:
> I have some external C libraries I would like to use with python.
> 
> I have been searching on the internet and found many such
> modules/bindings for libraries (e.g. Py-Lame) but have not yet
> come across any information of how to actually go about creating such
> bindings, so I was wondering if anybody here could point me in the right
> direction?

There are several methods. One is to write a Python C module by hand,
using the Python C API:

http://docs.python.org/ext/ext.html
http://docs.python.org/api/api.html

Essentially, all you need is a DLL/shared-object with an init
function.

Other solutions include tools that generate extension modules
automatically (such as SWIG or Pyrex), or using libraries on
top of the C API (such as Boost.Python).

I personally always use the C API directly.

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


Re: what is this?

2007-01-04 Thread Huayang Xia
Sequence slicing [starting-at-index :  but-less-than-index [ : step]].
Start defaults to 0, end to len(sequence), step to 1.
So l[i::rows] means: slicing start from i, ending with len(l) and step
with rows. So function colsplit(l, cols) returns a list of sequence
with conversion of:

Assume cols = 4:
From:

ABCD
ABCD
ABCD
AB

To:
CCCDDD



On Jan 4, 11:42 am, "Eric Price"
<[EMAIL PROTECTED]> wrote:
> Hello;
> I'm studying some code examples from the python cookbook site. I came across
> this:
>
> def colsplit(l, cols):
> rows = len(l) / cols
> if len(l) % cols:
> rows += 1
> m = []
> for i in range(rows):
> m.append(l[i::rows])
> return m
>
> What I'd like to know is what is the double colon? What does it do?
> m.append(l[i::rows])
>
> Thanks,
> Eric
>
> _
> Type your favorite song.  Get a customized station.  Try MSN Radio powered
> by Pandora.http://radio.msn.com/?icid=T002MSN03A07001

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


Re: Sorting on multiple values, some ascending, some descending

2007-01-04 Thread Peter Otten
Neil Cerutti wrote:

> Another trick is to factor the key application out of the sort.
> This may be a good idea if when you want to minimize the number
> of times your key function is called.
> 
> The idea is to mangle the list temporarily so you can use an
> unkeyed sort, and then unmangle the sorted data. Here's a silly
> example using a phone directory that's not stored in a format
> that's easy to sort.

No need to jump through these hoops; list.sort(key=keyfunc) calls keyfunc()
exactly once per list item:

>>> from random import shuffle
>>> items = range(-5, 10)
>>> shuffle(items)
>>> count = 0
>>> def key(value):
... global count
... count += 1
... return abs(value)
...
>>> items.sort(key=key)
>>> count
15

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


Re: Best way to implement a timed queue?

2007-01-04 Thread Martin v. Löwis
Thomas Ploch schrieb:
> I am having troubles with implementing a timed queue. I am using the
> 'Queue' module to manage several queues. But I want a timed access, i.e.
> only 2 fetches per second max. I am horribly stuck on even how I
> actually could write it. Has somebody done that before? And when yes,
> how is the best way to implement it?

You could put a wrapper around the queue which synchronizes the get
operations, and then delays access until 1s after the last-but-one
access.

The following code is untested:

import threading, time

class ThrottledQueue(threading.Queue):
  def __init__(self):
threading.Queue.__init__(self)
self.old = self.older = 0
self.get_lock = threading.Lock()

  def get(self):
with self.get_lock:  # synchronize get
  # check whether the next get should be in the future
  now = time.time()
  next = self.older + 1
  if now < next: time.sleep(next-now)
  # really fetch one item; this may block
  result = threading.Queue.get(self)
  self.older = self.old
  # set the last get time to the time when the get completed,
  # not when it started
  self.old = time.time()
return result

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


Why is pow a builtin, anyways?

2007-01-04 Thread Carl Banks
siggi wrote:
> Now the test for module math with function pow():
> ---
> >>> pow(9,9)
> 387420489
>
>  Fine, but sqrt() fails:
> ---
> >>> sqrt(9)
> I get this error message
>
> 'Traceback (most recent call last):
>   File "", line 1, in 
> sqrt(9)
> NameError: name 'sqrt' is not defined'

The third argument to the builtin pow is a special usage for
cryptography, and something specific like that needs no representation
in the builtin namespace.  The ** operator covers all other uses.


Carl Banks

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


Re: minidom utf-8 encoding

2007-01-04 Thread fscked

Martin v. Löwis wrote:
<...snip...>

> I find that hard to believe. There is no code in Python that does
> removal of characters, and I can't see any other reason why it gets
> removed.
>
> OTOH, what I do get when writing to a file is a UnicodeError, when
> it tries to convert the Unicode string that toxml gives to a byte
> string.
>
> So I recommend you pass encoding="utf-8" to the toprettyxml invocation
> also.
>
> Regards,
> Martin

OK, now I am really confused. After trying all variations of opening
and writing and encoding and all the other voodoo I can find on the web
for hours, I decide to put the script back to how it was when it did
everything but remove the unicode characters.

And now it just works...

I hate it when that happens. In case you are wondering here is the code
that caused me all this (seemingly odd) pain:

import csv
import codecs
from xml.dom.minidom import Document

out = open("test.xml", "w")

# Create the minidom document
doc = Document()

# Create the  base element
boxes = doc.createElement("boxes")
myfile = open('ClientsXMLUpdate.txt')
csvreader = csv.reader(myfile)
for row in csvreader:
mainbox = doc.createElement("box")
doc.appendChild(boxes)
r2 = csv.reader(myfile)
b = r2.next()
mainbox.setAttribute("city", b[10])
mainbox.setAttribute("country", b[9])
mainbox.setAttribute("phone", b[8])
mainbox.setAttribute("address", b[7])
mainbox.setAttribute("name", b[6])
mainbox.setAttribute("pl_heartbeat", b[5])
mainbox.setAttribute("sw_ver", b[4])
mainbox.setAttribute("hw_ver", b[3])
mainbox.setAttribute("date_activated", b[2])
mainbox.setAttribute("mac_address", b[1])
mainbox.setAttribute("boxid", b[0])
boxes.appendChild(mainbox)


# Print our newly created XML
out.write( doc.toprettyxml ())


And it just works...

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


Re: question on creating class

2007-01-04 Thread wcc
Thanks for all replies. I'll just to have to figure our which suggested
method I should use.  To answer Jussi's question, this is why I asked
the question.  I have the book by Mark:  Python Programming on Win32.
In Charpter 12: Advanced Python and COM there is a sample code named:
DynamicPolicy.py.  It can be used to expose all methods from a python
module to a COM server which can be accessed later from other
languages, say VBA. It works great.  There are quite a few modules that
I want to implement a COM server for.  One of the step to create the
COM server is to define a class.  Instead of revising this code for
each module, I wondered if I can create mutilple COM servers in one
program.  I'll pass a module name and the corresponding class name to
some function (to be written), and the class will be created.  Btw, I'm
novice to all this, hopefully my explanation isn't way off.  Thank to
all again. 

--
wcc

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


Re: where to ask questions related to comtypes?

2007-01-04 Thread wcc
Thank you Thomas.

On Jan 3, 11:10 pm, Thomas Heller <[EMAIL PROTECTED]> wrote:
> wcc schrieb:
>
> > Hello group,
>
> > Is there a separate mailing list for comtypes? Or this is the
> > appropriate place to post questions related to this package(from Thomas
> > Heller)?It seems the python-win32 mailing list is the place where the most 
> > COM knowledge
> is, so that would be most appropriate.  Other places are *this* list or the
> ctypes-users lists (since comtypes is based on ctypes).
> 
> Thomas

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


Re: Sorting on multiple values, some ascending, some descending

2007-01-04 Thread Neil Cerutti
On 2007-01-04, Peter Otten <[EMAIL PROTECTED]> wrote:
> Neil Cerutti wrote:
>> Another trick is to factor the key application out of the
>> sort. This may be a good idea if when you want to minimize the
>> number of times your key function is called.
>> 
>> The idea is to mangle the list temporarily so you can use an
>> unkeyed sort, and then unmangle the sorted data. Here's a
>> silly example using a phone directory that's not stored in a
>> format that's easy to sort.
>
> No need to jump through these hoops; list.sort(key=keyfunc)
> calls keyfunc() exactly once per list item:
>
 from random import shuffle
 items = range(-5, 10)
 shuffle(items)
 count = 0
 def key(value):
> ... global count
> ... count += 1
> ... return abs(value)
> ...
 items.sort(key=key)
 count
> 15

Thanks for the correction! That's very useful information.

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


Re: When argparse will be in the python standard installation

2007-01-04 Thread Steven Bethard
Martin v. Löwis wrote:
> Steven Bethard schrieb:
>> If someone has an idea how to include argparse features into optparse,
>> I'm certainly all for it. But I tried and failed to do this myself, so I
>> don't know how to go about it.
> 
> It's not necessary that the implementation is retained, only that the
> interface is preserved. So if you can come up with an implementation
> that supports all optparse applications, and adds the additional
> features, your implementation could replace the current optparse.
> If you need to make incompatible changes, it would be best if you
> could produce a list of such changes, so that optparse users can
> review them to find out whether they are affected.

FWIW, here's a short list of issues that could be easily addressed:

* alias ArgumentParser to OptionParser
* alias add_argument to add_option
* alias Values to Namespace
* alias OptionError and OptionValueError to ArgumentError
* alias add_help= keyword argument of ArgumentParser to add_help_option=
* alias namespace= keyword argument of parse_args to options=
* add the has_option, get_option and remove_option methods
* add the set_conflict_handler method
* add the destroy method
* add the set_usage method
* add the string names for types (e.g. "string", "str", "int", etc.) as
   aliases to the type objects (argparse already has a type registry for
   exactly these kinds of things)


Some slightly harder issues:

* ArgumentParser.parse_args returns a single namespace object, not an
   (options, args) tuple, since argparse handles positional arguments.
   This could probably be addressed by adding an __iter__ method to the
   Namespace object which would return (self, [])

* argparse uses standard string formatting specifiers, e.g. %(default)s
   and %(prog)s instead of optparse's %default and %prog. It could
   probably be hacked to support both though.

* argparse doesn't support {enable,disable}_interspersed_args() because
   their primary use case was for handling sub-parsers, which argparse
   handles through the add_subparsers method. It could probably be hacked
   to work though I guess.


And the issues that I don't see any good way to address:

* argparse makes the default value for a "store_true" action False, and
   the default value for a "store_false" action True. This is what users
   expect, but different from optparse where the default is always None.

* the ArgumentParser constructor doesn't accept the option_list=,
   option_class= or formatter= keyword arguments. Since argparse uses
   Action subclasses instead of a single Option class, the former two
   don't make much sense. And formatter= has been replaced with
   formatter_class= where the API of the formatter was dramatically
   changed. (That said, the formatter API is undocumented in both
   optparse and argparse.)

* the choices argument is now checked *after* arguments have been
   type-converted. This is intentional, so that you can specify, say
   xrange(100) instead of ["0", "1", "2", "3", ... "99"]. There is also
   no "choices" type anymore since any action can also specify their
   choices.

* argparse doesn't support ``callback`` actions because the same effects
   are better handled by defining a simple type-checking function and
   passing it as the type= keyword argument, or by subclassing
   argparse.Action and passing this as the action= keyword argument.
   I could probably add callback actions by creating an appropriate
   Action subclass and registering it. However, any code relying on
   parser.{largs,rargs,values} would break because the parsing algorithm
   is completely different in argparse.

* The `Extending optparse`_ section in the docs is pretty much
   completely inapplicable. One of the major goals of argparse was to get
   rid of the need to hack class attributes like TYPES, STORE_ACTIONS,
   etc. Instead, these things are handled by defining simple
   string-to-object functions that are passed to type= or by defining
   appropriate subclasses of argparse.Action which are passed to action=.
   Trying to support these sorts of things would be nearly impossible.


I guess I don't know how to proceed from here. I'm reluctant to start 
adding the code necessary to support even the easily solved issues when 
the issues that I don't know how to solve seem like they could be deal 
breakers.

STeVe

.. _Extending optparse: 
http://docs.python.org/lib/optparse-extending-optparse.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what is this?

2007-01-04 Thread Paul Watson
Eric Price wrote:
> Hello;
> I'm studying some code examples from the python cookbook site. I came 
> across this:
> 
> def colsplit(l, cols):
>rows = len(l) / cols
>if len(l) % cols:
>rows += 1
>m = []
>for i in range(rows):
>m.append(l[i::rows])
>return m
> 
> What I'd like to know is what is the double colon? What does it do?
>m.append(l[i::rows])
> 
> Thanks,
> Eric

http://docs.python.org/tut/tut.html
http://docs.python.org/tut/node5.html#SECTION00514
http://docs.python.org/ref/slicings.html

Probably most helpful to you is:

http://developer.mozilla.org/es4/proposals/slice_syntax.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what is this?

2007-01-04 Thread Paul Watson
Paul Watson wrote:
> Eric Price wrote:
>> Hello;
>> I'm studying some code examples from the python cookbook site. I came 
>> across this:
>>
>> def colsplit(l, cols):
>>rows = len(l) / cols
>>if len(l) % cols:
>>rows += 1
>>m = []
>>for i in range(rows):
>>m.append(l[i::rows])
>>return m
>>
>> What I'd like to know is what is the double colon? What does it do?
>>m.append(l[i::rows])
>>
>> Thanks,
>> Eric
> 
> http://docs.python.org/tut/tut.html
> http://docs.python.org/tut/node5.html#SECTION00514
> http://docs.python.org/ref/slicings.html
> 
> Probably most helpful to you is:
> 
> http://developer.mozilla.org/es4/proposals/slice_syntax.html

Sorry.  Probably most helpful to you is:

http://docs.python.org/lib/built-in-funcs.html

slice(  [start,] stop[, step])
 Return a slice object representing the set of indices specified by 
range(start, stop, step). The start and step arguments default to None. 
Slice objects have read-only data attributes start, stop and step which 
merely return the argument values (or their default). They have no other 
explicit functionality; however they are used by Numerical Python and 
other third party extensions. Slice objects are also generated when 
extended indexing syntax is used. For example: "a[start:stop:step]" or 
"a[start:stop, i]".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using External Libraries with python?

2007-01-04 Thread Chris Mellon
On 1/4/07, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> Ognjen Bezanov schrieb:
> > I have some external C libraries I would like to use with python.
> >
> > I have been searching on the internet and found many such
> > modules/bindings for libraries (e.g. Py-Lame) but have not yet
> > come across any information of how to actually go about creating such
> > bindings, so I was wondering if anybody here could point me in the right
> > direction?
>
> There are several methods. One is to write a Python C module by hand,
> using the Python C API:
>
> http://docs.python.org/ext/ext.html
> http://docs.python.org/api/api.html
>
> Essentially, all you need is a DLL/shared-object with an init
> function.
>
> Other solutions include tools that generate extension modules
> automatically (such as SWIG or Pyrex), or using libraries on
> top of the C API (such as Boost.Python).
>
> I personally always use the C API directly.
>
> Regards,
> Martin

Don't forget calling the using the external library directly from
Python by using ctypes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Set type?

2007-01-04 Thread _
How do you check to see if a variable is a set?  I would like to use

if type(var) is types.SetType:
   blah

but that is not available in types module.  I am using 2.4

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


Re: what is this?

2007-01-04 Thread Eric Price
>From: Paul Watson <[EMAIL PROTECTED]>

>Probably most helpful to you is:
>
>http://developer.mozilla.org/es4/proposals/slice_syntax.html

Oh, the step. Okay, thanks ;)
Eric

_
Communicate instantly! Use your Hotmail address to sign into Windows Live 
Messenger now. http://get.live.com/messenger/overview

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


Re: Set type?

2007-01-04 Thread belinda thom
I've seen people do that using an exception, e.g.

try:
   foo
except :
   #variable foo not defined


On Jan 4, 2007, at 10:48 AM, _ wrote:

> How do you check to see if a variable is a set?  I would like to use
>
> if type(var) is types.SetType:
>blah
>
> but that is not available in types module.  I am using 2.4
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Set type?

2007-01-04 Thread Robert Kern
_ wrote:
> How do you check to see if a variable is a set?  I would like to use
> 
> if type(var) is types.SetType:
>blah
> 
> but that is not available in types module.  I am using 2.4

In [1627]: type(set()) is set
Out[1627]: True

-- 
Robert Kern

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

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


Re: Set type?

2007-01-04 Thread Fredrik Lundh
_ wrote:

> How do you check to see if a variable is a set?  I would like to use
> 
> if type(var) is types.SetType:
>blah
> 
> but that is not available in types module.  I am using 2.4

 # set or subclass of set
 if isinstance(var, set):
 ...

 # exact match
 if type(var) is set:
 ...

also see

 http://preview.tinyurl.com/yjnoc5



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


Re: Using External Libraries with python?

2007-01-04 Thread Fredrik Lundh
Ognjen Bezanov wrote:

> I have some external C libraries I would like to use with python.
> 
> I have been searching on the internet and found many such
> modules/bindings for libraries (e.g. Py-Lame) but have not yet
> come across any information of how to actually go about creating such
> bindings, so I was wondering if anybody here could point me in the right
> direction?

in addition to the tools that have already been mentioned, the relevant 
FAQ articles also provide useful information:

http://effbot.org/pyfaq/extending-index.htm



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


Re: Set type?

2007-01-04 Thread Klaas

Fredrik Lundh wrote:

> > if type(var) is types.SetType:
> >blah
> >
> > but that is not available in types module.  I am using 2.4
>
>  # set or subclass of set
>  if isinstance(var, set):
>  ...

or
if isinstance(var, (set, frozenset)):
   ...

-Mike

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


py2exe setup strange error

2007-01-04 Thread Croteam
Hello,

I was trying to install my script (.py) to (.exe) and when I run setup
script with cmd I get the
error:

python mysetup.py py2exe

error: COREDLL.dll: No such file or directory







   Thanks!!!

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


Re: Why does Python never add itself to the Windows path?

2007-01-04 Thread robert
Ben Sizer wrote:
> robert wrote:
>> Ben Sizer wrote:
>>> My opinion is that this is not as big a problem as some may feel that
>>> it is. Unlike Unix systems, the PATH variable is rarely used.
>> It is a big problem.
>>
>> It is not less than the majority of Python users (at least those who do 
>> things on the command line) who deal with multiple Python versions.
> 
> So you think most Python users have more than one version of Python
> installed? I disagree - but even if it is true, how come this isn't a
> big problem on Unix? Can you name a single distribution that doesn't
> install Python to the path?

As said - yes they install the 'pythonx.y' binary or just 'python' default link 
_into_ the path (/usr/local/bin or /usr/bin). Yet they don't manipulate any 
PATH.


>> This would create funny PATH variables - almost a "psychic behavior with 
>> history".
> 
> It is quite trivial to see if Python is already on the path, and act
> differently based on that.

When you run an installer you first lookup the PATH and according to your look 
you hit or not-hit the (future) checkbox in the installer and/or edit the PATH 
later to only have one python main folder in it?  
You could as well edit the PATH at all yourself as one can do it now.

>> Windows is at all less a multi user system. I don't even know a case where 
>> two (Python) Programmers use _one_ box and then also want separate Python's 
>> - just know home mates (parasites) who occasionally share the web browser or 
>> so...
> 
> So... that's another reason why there's rarely a problem in setting
> that PATH variable.

mix-up with PATH is already there for a single user. I named a most negative 
example (Borland) and would not use such checkbox in a Python installer which 
would allow to manipulate the PATH in hardly  predictable manner.

>> Linking also a default python.exe into the system32 upon a (non-default) 
>> checkbox mark in the installer should be simple, clear and do everything 
>> what 99.9% want - and most "compatible" to *nix.
> 
> No, it doesn't : the /scripts directory is also important for many
> Python packages and that isn't addressed by shifting python.exe into
> system32.

Now you want also the scripts directory on the PATH? I don't even see this 
stuff on linux py's nor PATH's.

But as somebody said, we could have 3 or 4 options in the installer. Just who 
will supply MvL with the patch, which is truely not trivial.

Most cheap and consistent is:

Create pythonXY.exe always next to the pythonXY.dll auto. This is the same as 
having usr/local/pythonX.Y on linux. (Personally I anyway like to call exactly 
the python i want.)

Then a future option 2 - as I'd favor it next to the current "do nothing" - 
would probably also most simple for system installations:

If checkbox "copy python.exe into System Folder" then copy/overwrite python.exe 
into System Folder. There is not much magic and not much precedence worries 
about it and every developer knows clearly what happens. If multi-pythons, one 
knows that this would create the new default "python" on the command line 
unless one has custom things in front on the PATH. 

Then there could be advanced options 3, 4, .. for PATHs: With questions: 
Replacing in User- and/or System-PATH?, prepending-to-User/System-PATH?, 
appending-to-User/System-PATH, the same for the Script-folders and all fancy 
things and side-effects etc.  - if consistent patches will ever be supplied ...
I'd not use these options a lot anyway because I like Python to answer my 
questions - not reverse :-)


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


Re: A python library to convert RTF into PDF ?

2007-01-04 Thread leonel . gayard
> Why not use OO.org to convert DOC to PDF? It does so natively, IIRC.

I can't insert variables if the template is a DOC file. This is why we
are using RTF.


Felipe Almeida Lessa wrote:
> On 3 Jan 2007 10:52:02 -0800, [EMAIL PROTECTED]
> <[EMAIL PROTECTED]> wrote:
> > I have tried to
> > convert them to tex using OpenOffice, but the result is ugly as hell.
>
> Why not use OO.org to convert DOC to PDF? It does so natively, IIRC.
> 
> -- 
> Felipe.

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


bug in copy.deepcopy or in getattr or in my understanding?

2007-01-04 Thread Emin
Dear experts,

I got some unexpected behavior in getattr and copy.deepcopy (see
transcript below). I'm not sure if this is actually a bug in
copy.deepcopy or if I'm doing something too magical with getattr.
Comments would be appreciated.

Thanks,
-Emin

#  Transcript follows ##


Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> # THE FOLLOWING BREAKS
>>> class a:
... def foo(self):
... print 'hi'
...
>>> class b(a):
... def __init__(self):
... self.y = getattr(self,'foo')
...
>>> c = b()
>>> import copy
>>> copy.deepcopy(c)
Traceback (most recent call last):
  File "", line 1, in 
  File "c:\Python25\lib\copy.py", line 162, in deepcopy
y = copier(x, memo)
  File "c:\Python25\lib\copy.py", line 291, in _deepcopy_inst
state = deepcopy(state, memo)
  File "c:\Python25\lib\copy.py", line 162, in deepcopy
y = copier(x, memo)
  File "c:\Python25\lib\copy.py", line 254, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "c:\Python25\lib\copy.py", line 189, in deepcopy
y = _reconstruct(x, rv, 1, memo)
  File "c:\Python25\lib\copy.py", line 322, in _reconstruct
y = callable(*args)
  File "c:\Python25\lib\copy_reg.py", line 92, in __newobj__
return cls.__new__(cls, *args)
TypeError: instancemethod expected at least 2 arguments, got 0
>>> # THE FOLLOWING WORKS
>>> class b(a):
... def __init__(self):
... self.x = self.__class__.__bases__[0].__dict__['foo']
... 
>>> c=b()
>>> copy.deepcopy(c)
<__main__.b instance at 0x00EADE18>

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


Re: Draw rectangle on a Window DC

2007-01-04 Thread paul
Raymond schrieb:
> Hi:
> 
> I want to Draw rectangle on Dc when gived a position. Can you teach me? Let
> me view your code?
Well, you haven't given us much background but I'd suggest if your boss
asks you to draw a rectangle on your corporate domain controller and the
position allows this, you better do so or you'll get fired.
Use chalk so you can wipe it off the case if your boss changes his/her
mind. Disclaimer: I haven't tested this and the DC might get unstable or
crash...

scnr
 Paul

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

subclassing a module: misleading(?) error message

2007-01-04 Thread Erik Johnson
I ran into a problem I didn't understand at first. I got part of it figured
out. Let me first demonstrate the original problem:

> cat Super.py

class Super(object):
def __init__(self):
self._class = 'Super'
def hello(self):
print "%s says 'Hello'" % self._class
> cat Sub.py

import Super

class Sub(Super):
def __init__(self):
self._class = 'Sub'
>
> python
Python 2.3.4 (#1, Feb  7 2005, 15:50:45)
[GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from Super import Super
>>> from Sub import Sub
Traceback (most recent call last):
  File "", line 1, in ?
  File "Sub.py", line 4, in ?
class Sub(Super):
TypeError: function takes at most 2 arguments (3 given)
>>>

My question is NOT "What's wrong here?"
(The answer to that is that the import in Sub.py should be:  from Super
import Super
i.e., I tried to use the module itself where I meant to subclass the class
defined in that module).

My questions are:

Why does python complain about a function here? (it's a class definition
statement, right?)
Is there really a function being called here?
If so:
What function was called?
What two arguments is it expecting?
What three were given?

Thanks,
-ej


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


Re: When argparse will be in the python standard installation

2007-01-04 Thread John J. Lee
Steven Bethard <[EMAIL PROTECTED]> writes:

> Martin v. Löwis wrote:
> > Steven Bethard schrieb:
> >> If someone has an idea how to include argparse features into optparse,
> >> I'm certainly all for it. But I tried and failed to do this myself, so I
> >> don't know how to go about it.
> > It's not necessary that the implementation is retained, only that the
> > interface is preserved. So if you can come up with an implementation
> > that supports all optparse applications, and adds the additional
> > features, your implementation could replace the current optparse.
> > If you need to make incompatible changes, it would be best if you
> > could produce a list of such changes, so that optparse users can
> > review them to find out whether they are affected.
> 
> FWIW, here's a short list of issues that could be easily addressed:
> 
> * alias ArgumentParser to OptionParser
[...snip long list of proposed aliases and additions...]

> Some slightly harder issues:
[...]

You propose here to attempt to merge optparse and argparse into a
single interface (single class, by the sound of it).

I stopped reading after a bit, but at least up to that point, all of
these issues could (and certainly should, if argparse is added to the
stdlib, even in Python 3) be addressed by instead providing both
OptionParser and an OptsAndArgsParser class (or whatever you'd call
the latter).  OptionParser would then support exactly the current
optparse.OptionParser interface.  OptsAndArgsProcessor would support
your new interface.  Presumably most of the actual implementation code
would be shared.


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

Re: subclassing a module: misleading(?) error message

2007-01-04 Thread Carl Banks
Erik Johnson wrote:
> My questions are:
>
> Why does python complain about a function here? (it's a class definition
> statement, right?)

Because you're calling the function with the wrong number of arguments.

> Is there really a function being called here?

Yes.  (Well, it's not exactly a function, but you are calling
something.)

> If so:
> What function was called?

types.ModuleType

> What two arguments is it expecting?

The name of the module and a docstring.

> What three were given?

1. The name of the class
2. The tuple of bases
3. A dict containing the symbols defined inside the class statement.

You are aware, I presume, that types (be it classes or built-in types)
are callable.  For example, to create an instance of class of class X,
you would call X().  And to create a list, you can call list().  Well,
in the same way, you can call type(), with the three arguments above,
to create classes.  And that's just what the class statement does under
the covers (usually).

The following class definition:

class A(object):
b = 1

is exactly equivalent to this explicit call to type:

A = type("A",(object,),{"b":1})

However, there are some cases where, instead of creating the class
object itself, type will instead call some other function to create it.
 One way is if you define __metaclass__ in the class namespace: then
type will call the object spec.  Another way is if there are any bases
which have a type other than type.  (Remember, bases are supposed to be
type objects.)

That's what happened to you.  type saw that type(Super) was
types.ModuleType, not type, so it called that instead of creating the
class itself.  However, types.ModuleType doesn't accept that same
arguments that a normal type constructor does, so you get the error.

Does that clear things up?  Probably not.  For a detailed explanation
of how this all works, look for some resources on learning
"metaclasses" or "metatypes" in Python.


Carl Banks

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


Problem Running Working Code on Mac

2007-01-04 Thread goodepic
I'm newish to python and just got my first mac, so sorry if this is
stupid.  I have a little app developed by someone else in wxGlade that
implements a complex stats package and language package, all in python.
 It works fine on my work PC, but not on my laptop.  I have a new
macbook 2ghz core duo, running os x 10.4.8 with python 2.5 installed (I
didn't erase the base 2.3, just put /usr/local/bin at the start of
$PATH), along with the latest wxPython, can't remember the version
number.  I need to add a few more components from the stats package,
and I'd like eventually to pretty up the cheap GUI I was given, but
that'd be icing.  When I try either python  or pythonw
, I get this error:

WARNING:root:Could not import module "PyPar", defining sequential
interface
WARNING:root:No MySQLdb module available
WARNING:root:No pgdb module (PostgreSQL) available
Traceback (most recent call last):
  File "febrlgui.py", line 513, in 
frame_1 = MyFrame(None, -1, "")
  File "febrlgui.py", line 198, in __init__
self.__set_properties()
  File "febrlgui.py", line 355, in __set_properties
self.a_box1.SetSelection(-1)
  File
"//Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/wx-2.8-mac-ansi/wx/_core.py",
line 11487, in SetSelection
return _core_.ItemContainer_SetSelection(*args, **kwargs)
wx._core.PyAssertionError: C++ assertion "IsValid(n)" failed at
/BUILD/wxPython-src-2.8.0.1/src/mac/carbon/choice.cpp(242) in
GetString(): wxChoice::GetString(): invalid index

Of course I'm traveling soon and need to be able to work on this on my
macbook, so it's down to panic time.  Any help is GREATLY appreciated.

Thanks,
Matt

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


Re: Problem Running Working Code on Mac

2007-01-04 Thread goodepic
Also, if it makes a difference, the lines quoted in the error message
were actually written automatically by wxGlade.

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


Re: subclassing a module: misleading(?) error message

2007-01-04 Thread Huayang Xia
So you know you are subclassing a module.

There is an answer @
http://www.velocityreviews.com/forums/showpost.php?p=1819038&postcount=2

On Jan 4, 3:49 pm, "Erik Johnson"  wrote:
> I ran into a problem I didn't understand at first. I got part of it figured
> out. Let me first demonstrate the original problem:
>
> > cat Super.pyclass Super(object):
> def __init__(self):
> self._class = 'Super'
> def hello(self):
> print "%s says 'Hello'" % self._class
>
> > cat Sub.pyimport Super
>
> class Sub(Super):
> def __init__(self):
> self._class = 'Sub'
>
> > pythonPython 2.3.4 (#1, Feb  7 2005, 15:50:45)
> [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> from Super import Super
> >>> from Sub import SubTraceback (most recent call last):
>   File "", line 1, in ?
>   File "Sub.py", line 4, in ?
> class Sub(Super):
> TypeError: function takes at most 2 arguments (3 given)
>
> My question is NOT "What's wrong here?"
> (The answer to that is that the import in Sub.py should be:  from Super
> import Super
> i.e., I tried to use the module itself where I meant to subclass the class
> defined in that module).
>
> My questions are:
>
> Why does python complain about a function here? (it's a class definition
> statement, right?)
> Is there really a function being called here?
> If so:
> What function was called?
> What two arguments is it expecting?
> What three were given?
> 
> Thanks,
> -ej

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


Re: Problem Running Working Code on Mac

2007-01-04 Thread hg
goodepic wrote:

> I'm newish to python and just got my first mac, so sorry if this is
> stupid.  I have a little app developed by someone else in wxGlade that
> implements a complex stats package and language package, all in python.
>  It works fine on my work PC, but not on my laptop.  I have a new
> macbook 2ghz core duo, running os x 10.4.8 with python 2.5 installed (I
> didn't erase the base 2.3, just put /usr/local/bin at the start of
> $PATH), along with the latest wxPython, can't remember the version
> number.  I need to add a few more components from the stats package,
> and I'd like eventually to pretty up the cheap GUI I was given, but
> that'd be icing.  When I try either python  or pythonw
> , I get this error:
> 
> WARNING:root:Could not import module "PyPar", defining sequential
> interface
> WARNING:root:No MySQLdb module available
> WARNING:root:No pgdb module (PostgreSQL) available
> Traceback (most recent call last):
>   File "febrlgui.py", line 513, in 
> frame_1 = MyFrame(None, -1, "")
>   File "febrlgui.py", line 198, in __init__
> self.__set_properties()
>   File "febrlgui.py", line 355, in __set_properties
> self.a_box1.SetSelection(-1)
>   File
> "//Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/wx-2.8-mac-ansi/wx/_core.py",
> line 11487, in SetSelection
> return _core_.ItemContainer_SetSelection(*args, **kwargs)
> wx._core.PyAssertionError: C++ assertion "IsValid(n)" failed at
> /BUILD/wxPython-src-2.8.0.1/src/mac/carbon/choice.cpp(242) in
> GetString(): wxChoice::GetString(): invalid index
> 
> Of course I'm traveling soon and need to be able to work on this on my
> macbook, so it's down to panic time.  Any help is GREATLY appreciated.
> 
> Thanks,
> Matt


I'd get rid of the warnings first by installing the correct librairies
(PyPar, MySQLDB, pgdb)  who knows what the side effect are ?

hg

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


cache line length of a machine

2007-01-04 Thread John

How do I find out the cache line length of a machine in python?

Thanks,
--j

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


Re: When argparse will be in the python standard installation

2007-01-04 Thread Steven Bethard
Steven Bethard schrieb:
 > If someone has an idea how to include argparse features into optparse,
 > I'm certainly all for it. But I tried and failed to do this myself, so
 > I don't know how to go about it.

Martin v. Löwis wrote:
 > It's not necessary that the implementation is retained, only that the
 > interface is preserved.
[snip]
 > If you need to make incompatible changes, it would be best if you
 > could produce a list of such changes

Steven Bethard writes:
 > FWIW, here's a short list of issues that could be easily addressed:
 >
 > * alias ArgumentParser to OptionParser
[snip]

John J. Lee wrote:
> all of these issues could ... be addressed by instead providing both
> OptionParser and an OptsAndArgsParser class (or whatever you'd call
> the latter).

You're essentially proposing to move argparse.ArgumentParser to the 
optparse module. (The ArgumentParser class handles both optional and 
positional command-line args -- it *is* your OptsAndArgsProcessor).

That's certainly an easy option for me =) but does it address Martin and 
Fredrik's concerns that there are already too many argument parsing 
libraries in the stdlib?

> Presumably most of the actual implementation code
> would be shared.

Well, the "harder issues" I listed in the previous post were basically 
the reasons that sharing the implementation code would be difficult. I 
don't know how to do it without breaking OptionParser in backwards 
incompatible ways. (The documented ways of extending optparse make this 
particularly difficult since they make public a number of internal 
optparse details.)

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

[ANN] argparse 0.4 - Command-line parsing library

2007-01-04 Thread Steven Bethard
Announcing argparse 0.4
---

argparse home:
   http://argparse.python-hosting.com/

argparse single module download:
   http://argparse.python-hosting.com/file/trunk/argparse.py?format=raw

argparse bundled downloads at PyPI:
   http://www.python.org/pypi/argparse/

New in this release
===

* The add_argument method now allows a positional argument with
nargs='*' to specify a default value::

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', nargs='*', default=['def'])
>>> parser.parse_args('1 2 3'.split())
Namespace(foo=['1', '2', '3'])
>>> parser.parse_args([])
Namespace(foo=['def'])

About argparse
==

The argparse module is an optparse-inspired command line parser that
improves on optparse by:

* handling both optional and positional arguments
* supporting parsers that dispatch to sub-parsers
* producing more informative usage messages
* supporting actions that consume any number of command-line args
* allowing types and actions to be specified with simple callables
instead of hacking class attributes like STORE_ACTIONS or
CHECK_METHODS

as well as including a number of other more minor improvements on the
optparse API. To whet your appetite, here's a simple program that sums
its command-line arguments and writes them to a file::

   parser = argparse.ArgumentParser()
   parser.add_argument('integers', type=int, nargs='+')
   parser.add_argument('--log', type='outfile', default=sys.stdout)
   args = parser.parse_args()
   args.log.write('%s\n' % sum(args.integers))
   args.log.close()
-- 
http://mail.python.org/mailman/listinfo/python-list


Turn off line wrap for lists?

2007-01-04 Thread _
(I did google for this, I promise)

How do I get python NOT to insert newlines into string representations
of lists when I do something like this:

strCollector += "%s" % (['a', 'list', 'with', 'lots', 'of', 'elements']
* 100)

?

I would like to set a default never to do this, if possible. (Never mix
formatting with display, or tequila with bourbon -- bad, bad, bad!)

FYI I am using this to export data into tab delimited format, so the
lines can be as long as they need to be, but a newline means a new
record.

FYI (2), this is in web application too, so I am afraid I might have to
set the default in a bunch of different modules.

TIA

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


Re: Turn off line wrap for lists?

2007-01-04 Thread Carsten Haese
On Thu, 2007-01-04 at 17:01 -0800, _ wrote:
> (I did google for this, I promise)
> 
> How do I get python NOT to insert newlines into string representations
> of lists when I do something like this:
> 
> strCollector += "%s" % (['a', 'list', 'with', 'lots', 'of', 'elements']
> * 100)

What makes you think that that inserts newline characters? My python
doesn't do that:

>>> a = "%s" % (['a', 'list', 'with', 'lots', 'of', 'elements'] * 100)
>>> "\n" in a
False

> FYI I am using this to export data into tab delimited format

You could avoid reinventing the wheel by using the "csv" module.

-Carsten


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


Re: Turn off line wrap for lists?

2007-01-04 Thread Michael Tobis

_ wrote:
> (I did google for this, I promise)
>
> How do I get python NOT to insert newlines into string representations
> of lists when I do something like this:
>
> strCollector += "%s" % (['a', 'list', 'with', 'lots', 'of', 'elements']
> * 100)

It shouldn't and doesn't insert newlines.

##
>>> strCollector = "%s" % (['a', 'list', 'with', 'lots', 'of', 'elements'] * 
>>> 100)
>>> strCollector.split("\n")[0] == strCollector
True
##
mt

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


Re: minidom utf-8 encoding

2007-01-04 Thread Martin v. Löwis
fscked schrieb:
> # Create the  base element
> boxes = doc.createElement("boxes")
> myfile = open('ClientsXMLUpdate.txt')
> csvreader = csv.reader(myfile)
> for row in csvreader:
> mainbox = doc.createElement("box")
> doc.appendChild(boxes)
> r2 = csv.reader(myfile)
> b = r2.next()
> mainbox.setAttribute("city", b[10])
> 
> And it just works...

You should not use it like that: it will only work if the CSV file is
encoded in UTF-8. If the CSV file uses any other encoding, the resulting
XML file will be ill-formed.

What you should do instead is

...
encoding_of_csv_file = some_value_that_the_producer_of_the_file_told_you
...
 ...
 mainbox.setAttribute("city", b[10].decode(encoding_of_csv_file))

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


Re: pow() works but sqrt() not!?

2007-01-04 Thread Dan Bishop
On Jan 4, 10:00 am, "siggi" <[EMAIL PROTECTED]> wrote:
> Thanks for that, too!
>
> Would be interesting to learn how these different algorithms [for pow] 
> influence the
> precision of the result!?

For an integer (i.e., int or long) x and a nonnegative integer y, x**y
is exact:

>>> 101 ** 12
1126600022495000792000924000792000495000220661201L
(73 significant digits, correctly ending in "01")

math.pow uses floating-point arithmetic (even if you pass it integers),
and so has limited precision:

>>> print '%.73f' % math.pow(101, 12)
11266000238472777842004463257260700063242258506335663988477526016
(Only the first 17 digits are correct.)

For floats, the ** operator does the same thing math.pow does.

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


Re: pow() works but sqrt() not!?

2007-01-04 Thread Gabriel Genellina

At Thursday 4/1/2007 10:12, siggi wrote:


Thanks for the explanation. I am astonished what an interpreted language is
able to do!


Python is as interpreted as Java. Its numerical capabilities are more 
or less independent of this fact, I'd say.



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: Draw rectangle on a Window DC

2007-01-04 Thread Gabriel Genellina

At Thursday 4/1/2007 07:07, Raymond wrote:

I want to Draw rectangle on Dc when gived a position. Can you teach 
me? Let me view your code?


This is more a Windows question. See 
http://msdn.microsoft.com/library/en-us/gdi/rectangl_4b03.asp


py>from win32gui import GetDC
py>hdc=GetDC(0)
py>from win32gui import Rectangle
py>Rectangle(hdc, 100,100, 300,300)
py>ReleaseDC(hdc,0)
0
py>

You should see a white square on your screen.


--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

clarification on open file modes

2007-01-04 Thread tubby
Does a py script written to open and read binary files on Windows affect 
files on a Linux or Mac machine in a negative way? My concern is 
portability and safety. I want scripts written within Windows to work 
equally well on Linux and Mac computers.

Is this the safest, most portable way to open files on any platform:

fp = open(file_name, 'rb')
fp.close()

I understand that doing the following on Windows to a binary file (a 
jpeg or exe files for example) can cause file corruption, is that correct?

fp = open(file_name, 'r')
fp.close()

How can a simple open in read mode corrupt data???
-- 
http://mail.python.org/mailman/listinfo/python-list


What is proper way to require a method to be overridden?

2007-01-04 Thread jeremito
I am writing a class that is intended to be subclassed.  What is the
proper way to indicate that a sub class must override a method?

Thanks,
Jeremy

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


Re: bug in copy.deepcopy or in getattr or in my understanding?

2007-01-04 Thread Gabriel Genellina

At Thursday 4/1/2007 17:26, Emin wrote:


I got some unexpected behavior in getattr and copy.deepcopy (see
transcript below). I'm not sure if this is actually a bug in
copy.deepcopy or if I'm doing something too magical with getattr.
Comments would be appreciated.


Both examples are different. #1 stores a *bound* method into an 
instance attribute. Bound methods carry a reference to "self", this 
creates a cyclic reference that may cause problems to the garbage 
collector (and confuses deepcopy, apparently).

#2 uses and *unbound* method and it's the usual way.


>>> class a:
... def foo(self):
... print 'hi'
...
>>> class b(a): #1
... def __init__(self):
... self.y = getattr(self,'foo')

>>> class b(a): #2
... def __init__(self):
... self.x = self.__class__.__bases__[0].__dict__['foo']


For #2 you can simply say:

class b(a):
x = a.foo

If you have to choose at runtime (a simplified version of your own code):

class b(a):
def __init__(self):
name = select_method_to_use(..., default="foo")
self.x = getattr(a, name)

You *know* your bases because you wrote them in the class statement 
(or use super() instead of playing with __bases__); and getattr works 
fine here so you don't need to mess with the __dict__ details.


(Note that #1 was *almost* right, you had to replace self by the base class)


--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: pow() works but sqrt() not!?

2007-01-04 Thread Grant Edwards
On 2007-01-05, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> At Thursday 4/1/2007 10:12, siggi wrote:
>
>>Thanks for the explanation. I am astonished what an interpreted
>>language is able to do!
>
> Python is as interpreted as Java.

But it's far more interactive -- at least when compared with my
limited experience with Java.

> Its numerical capabilities are more or less independent of
> this fact, I'd say.

-- 
Grant Edwards   grante Yow!  What PROGRAM are
  at   they watching?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subclassing a module: misleading(?) error message

2007-01-04 Thread Gabriel Genellina

At Thursday 4/1/2007 17:49, Erik Johnson wrote:


Python 2.3.4 (#1, Feb  7 2005, 15:50:45)
Traceback (most recent call last):
  File "", line 1, in ?
  File "Sub.py", line 4, in ?
class Sub(Super):
TypeError: function takes at most 2 arguments (3 given)

Why does python complain about a function here? (it's a class definition
statement, right?)
Is there really a function being called here?
If so:
What function was called?
What two arguments is it expecting?
What three were given?


The same thing on Python 2.4.2 (at least) prints a much more meaningful error:

Traceback (most recent call last):
  File "", line 1, in ?
TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)


--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: What is proper way to require a method to be overridden?

2007-01-04 Thread Thomas Ploch
jeremito schrieb:
> I am writing a class that is intended to be subclassed.  What is the
> proper way to indicate that a sub class must override a method?
> 
> Thanks,
> Jeremy
> 

What do you mean by 'indicate'? Writing it to the docstring of the
class/method? Writing a comment?

class Foo:
"""
When inheriting from Foo, method foo must be
overridden. Otherwise SPAM.
"""
def foo(self):
print 'bar'

class Bar(Foo):
def __init__(self):
Foo.__init__(self)

# Has to be defined to override the base class's method
# when inheriting from class Foo. Otherwise: SPAM
def foo(self):
print 'foo'

I don't know any other way.

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


Weekly Python Patch/Bug Summary

2007-01-04 Thread Kurt B. Kaiser
Patch / Bug Summary
___

Patches :  418 open ( +5) /  3522 closed ( +1) /  3940 total ( +6)
Bugs:  959 open (+13) /  6405 closed ( +5) /  7364 total (+18)
RFE :  250 open ( +2) /   245 closed ( -1) /   495 total ( +1)

New / Reopened Patches
__

update to PEP 344 - exception attributes  (2007-01-02)
CLOSED http://python.org/sf/1626538  opened by  Jim Jewett

backticks will not be used at all  (2007-01-03)
   http://python.org/sf/1627052  opened by  Jim Jewett

Fix for #1601399 (urllib2 does not close sockets properly)  (2007-01-03)
   http://python.org/sf/1627441  opened by  John J Lee

Win32: Fix build when you have TortoiseSVN but no .svn/*  (2007-01-04)
   http://python.org/sf/1628061  opened by  Larry Hastings

Win32: Add bytesobject.c to pythoncore.vcproj  (2007-01-04)
   http://python.org/sf/1628062  opened by  Larry Hastings

socket.readline() interface doesn't handle EINTR properly  (2007-01-04)
   http://python.org/sf/1628205  opened by  Maxim Sobolev

Patches Closed
__

update to PEP 344 - exception attributes  (2007-01-02)
   http://python.org/sf/1626538  closed by  ping

New / Reopened Bugs
___

sqlite3 documentation omits: close(), commit(), autocommit  (2006-12-30)
   http://python.org/sf/1625205  opened by  kitbyaydemir

re module documentation on search/match is unclear  (2006-12-31)
   http://python.org/sf/1625381  opened by  Richard Boulton

'imp' documentation does not mention that lock is re-entrant  (2006-12-31)
   http://python.org/sf/1625509  opened by  Dustin J. Mitchell

add ability to specify name to os.fdopen  (2007-01-01)
   http://python.org/sf/1625576  opened by  Mark Diekhans

'Installing Python Modules' does not work for Windows  (2007-01-02)
   http://python.org/sf/1626300  opened by  Christopher Lambacher

Would you mind renaming object.h to pyobject.h?  (2007-01-02)
   http://python.org/sf/1626545  opened by  Anton Tropashko

posixmodule.c leaks crypto context on Windows  (2007-01-03)
   http://python.org/sf/1626801  opened by  Yitz Gale

website issue reporter down  (2007-01-03)
   http://python.org/sf/1627036  opened by  Jim Jewett

mention side-lists from python-dev description  (2007-01-03)
   http://python.org/sf/1627039  opened by  Jim Jewett

xml.dom.minidom parse bug  (2007-01-03)
CLOSED http://python.org/sf/1627096  opened by  Pierre Imbaud

xml.dom.minidom parse bug  (2007-01-03)
CLOSED http://python.org/sf/1627244  opened by  Pierre Imbaud

an extra comma in condition command crashes pdb  (2007-01-03)
   http://python.org/sf/1627316  opened by  Ilya Sandler

Typo in module index for Carbon.CarbonEvt  (2007-01-03)
CLOSED http://python.org/sf/1627373  opened by  Brett Cannon

Status bar on OSX garbled  (2007-01-03)
   http://python.org/sf/1627543  opened by  sigzero

RotatingFileHandler cannot recover from failed doRollover()  (2007-01-03)
   http://python.org/sf/1627575  opened by  Forest Wilkinson

documentation error for "startswith" string method  (2007-01-04)
CLOSED http://python.org/sf/1627690  opened by  Keith Briggs

plat-mac videoreader.py auido format info  (2007-01-04)
   http://python.org/sf/1627952  opened by  Ryan Owen

documentation error for "startswith" string method  (2007-01-04)
   http://python.org/sf/1627956  opened by  Keith Briggs

Bugs Closed
___

test_logging hangs on cygwin  (2006-04-06)
   http://python.org/sf/1465643  closed by  sf-robot

xml.dom.minidom parse bug  (2007-01-03)
   http://python.org/sf/1627096  closed by  loewis

xml.dom.minidom parse bug  (2007-01-03)
   http://python.org/sf/1627244  closed by  nnorwitz

Typo in module index for Carbon.CarbonEvt  (2007-01-03)
   http://python.org/sf/1627373  closed by  nnorwitz

documentation error for "startswith" string method  (2007-01-04)
   http://python.org/sf/1627690  closed by  loewis

Logging problem on Windows XP  (2006-09-27)
   http://python.org/sf/1566280  closed by  loewis

New / Reopened RFE
__

smarter temporary file object  (2001-04-12)
   http://python.org/sf/415692  reopened by  gvanrossum

optparse "store" action should not gobble up next  option  (2007-01-03)
   http://python.org/sf/1627266  opened by  Raghuram Devarakonda

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


Re: What is proper way to require a method to be overridden?

2007-01-04 Thread Robert Kern
jeremito wrote:
> I am writing a class that is intended to be subclassed.  What is the
> proper way to indicate that a sub class must override a method?

raise NotImplementedError

-- 
Robert Kern

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

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


Re: clarification on open file modes

2007-01-04 Thread Gabriel Genellina

At Thursday 4/1/2007 23:46, tubby wrote:


I understand that doing the following on Windows to a binary file (a
jpeg or exe files for example) can cause file corruption, is that correct?

fp = open(file_name, 'r')
fp.close()

How can a simple open in read mode corrupt data???


You can't corrupt *that* file if you only open it. But if you *read* 
it and process the input data, you'll get some garbage. And if you 
write such data (to the same file or another one), it will be corrupted.
Using "rb" or "wb" for binary files won't do any harm on systems 
where it doesn't matter, and it's the right way on systems where it does.



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

  1   2   >