Re: descriptor & docstring

2008-04-28 Thread Gabriel Genellina
En Tue, 29 Apr 2008 01:29:40 -0300, George Sakkis  
<[EMAIL PROTECTED]> escribió:

On Apr 28, 10:59 pm, "Gabriel Genellina"


def property_default(prop_name, default_value=None, doc=None):

     attr_name = '_'+prop_name

     def fget(self, attr_name=attr_name,
                    default_value=default_value):
         return getattr(self, attr_name, default_value)

     def fset(self, value,
                    attr_name=attr_name,
                    default_value=default_value):
         if value == default_value:
             delattr(self, attr_name)
         else:
             setattr(self, attr_name, value)

     return property(fget=fget, fset=fset, doc=doc)

When setting the same value as the default, the instance attribute is  
removed (so the default will be used when retrieving the value later).  
I think this is what you intended to do.


Note that this will fail if the value is already equal to the default
and you try to reset it to the default, so it needs an extra
hasattr(self, attr_name) before the delattr. Regardless, I would be
surprised with the following behaviour:


r = Rectangle()
r.length = 4
type(r.length)



r.length = 12
type(r.length)




Yep, probably the best thing to do is to always call setattr and avoid  
special cases.



Another simpler alternative would be to (ab)use a decorator:

def defaultproperty(func):
attr = '_' + func.__name__
default = func.func_defaults[0]
return property(
fget = lambda self: getattr(self, attr, default),
fset = lambda self,value: setattr(self, attr, value),
doc = func.__doc__)


class Rectangle(object):
'''A beautiful Rectangle'''

@defaultproperty
def length(default=12.0):
'''This is the length property'''



Nice, although that empty function looks somewhat strange...

--
Gabriel Genellina

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


Re: File IO Issues, help :(

2008-04-28 Thread Peter Otten
Kevin K wrote:

> On Apr 29, 12:55 am, Peter Otten <[EMAIL PROTECTED]> wrote:
>> Kevin K wrote:
>> > On Apr 29, 12:38 am, "Eric Wertman" <[EMAIL PROTECTED]> wrote:
>> >> chuck in a jsfile.close().  The buffer isn't flushing with what you
>> >> are doing now.  jsfile.flush() might work... not sure.  Closing and
>> >> re-opening the file for sure will help though.
>>
>> > Yeah sorry I forgot to include the close() in the quote but its there.
>> > In fact I moved it up a bit and still no luck heres the new code:
>>
>> > jsfile = open("../timeline.js", "r+")
>> > jscontent = jsfile.readlines()
>> > jsfile.truncate()
>>
>> > for line in jscontent:
>> > if re.search('var d =', line):
>> > line = "var d = \""+mint['1'].ascdate()+"\"\n"
>> > print line
>> > jsfile.write(line)
>> > jsfile.close()
>>
>> > I tried this can got the same result...??
>>
>> """
>> truncate(...)
>> truncate([size]) -> None.  Truncate the file to at most size bytes.
>>
>> Size defaults to the current file position, as returned by tell().
>> """
>>
>> After the readlines() call the current file position is at the end of the
>> file. Try jsfile.truncate(0).
>>
>> Also note that readlines() reads the whole file into memory. For large
>> files it would therefore be better to write to a new file and rename it
>> afterwards.
>>
>> Peter
> 
> Thanks Peter that seemed to be most of the problem, however I now have
> a bunch of null characters in the file. Could it be an unwanted line
> in the list that im writing?

Oops, truncate() doesn't affect the file position. You probably need

jsfile.truncate(0)
jsfile.seek(0)

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


Re: Sphinx 0.2 released

2008-04-28 Thread Stefan Behnel
Hi Georg,

Georg Brandl wrote:
> I'm pleased to announce the release 0.2 of Sphinx, the Python documentation
> generation tool. There were some intermediate smaller releases in the 0.1
> series, but for 0.2 there are quite a lot new features and fixes.
> 
> What is it?
> ===
> 
> Sphinx is a tool that makes it easy to create intelligent and beautiful
> documentation for Python projects (or other documents consisting of
> multiple reStructuredText source files).

I'm wondering, would there be any way to bridge to epydoc? It would be cool to
have the two integrated so that you could generate API docs and written docs
in one step, with the same look-and-feel.

(BTW: yes, I'm advocating not to implement another API documentation tool, but
to integrate with an existing one. I would think epydoc matches the
requirements quite well here).

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


Re: python script as executable

2008-04-28 Thread Arnaud Delobelle
sandipm <[EMAIL PROTECTED]> writes:

> Hi,
> I have written a python script to run from cron.
> I  have put #!/usr/bin/env python at top. file executes correctly when
> I run using python filename.py but
> it fails to execute when try to run it like script/command.
> it throws error:
> :No such file or directory
>
> I am editing file from eclipse for python from windows. and then
> uploading on linus machine to run it.
>
>
> any pointers?

Have you made your file executable (man chmod)?

-- 
Arnaud

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


Re: File IO Issues, help :(

2008-04-28 Thread Kevin K
On Apr 29, 12:55 am, Peter Otten <[EMAIL PROTECTED]> wrote:
> Kevin K wrote:
> > On Apr 29, 12:38 am, "Eric Wertman" <[EMAIL PROTECTED]> wrote:
> >> chuck in a jsfile.close().  The buffer isn't flushing with what you
> >> are doing now.  jsfile.flush() might work... not sure.  Closing and
> >> re-opening the file for sure will help though.
>
> > Yeah sorry I forgot to include the close() in the quote but its there.
> > In fact I moved it up a bit and still no luck heres the new code:
>
> > jsfile = open("../timeline.js", "r+")
> > jscontent = jsfile.readlines()
> > jsfile.truncate()
>
> > for line in jscontent:
> > if re.search('var d =', line):
> > line = "var d = \""+mint['1'].ascdate()+"\"\n"
> > print line
> > jsfile.write(line)
> > jsfile.close()
>
> > I tried this can got the same result...??
>
> """
> truncate(...)
> truncate([size]) -> None.  Truncate the file to at most size bytes.
>
> Size defaults to the current file position, as returned by tell().
> """
>
> After the readlines() call the current file position is at the end of the
> file. Try jsfile.truncate(0).
>
> Also note that readlines() reads the whole file into memory. For large files
> it would therefore be better to write to a new file and rename it
> afterwards.
>
> Peter

Thanks Peter that seemed to be most of the problem, however I now have
a bunch of null characters in the file. Could it be an unwanted line
in the list that im writing?

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


Re: File IO Issues, help :(

2008-04-28 Thread Peter Otten
Kevin K wrote:

> On Apr 29, 12:38 am, "Eric Wertman" <[EMAIL PROTECTED]> wrote:
>> chuck in a jsfile.close().  The buffer isn't flushing with what you
>> are doing now.  jsfile.flush() might work... not sure.  Closing and
>> re-opening the file for sure will help though.
>>
> 
> Yeah sorry I forgot to include the close() in the quote but its there.
> In fact I moved it up a bit and still no luck heres the new code:
> 
> jsfile = open("../timeline.js", "r+")
> jscontent = jsfile.readlines()
> jsfile.truncate()
> 
> for line in jscontent:
> if re.search('var d =', line):
> line = "var d = \""+mint['1'].ascdate()+"\"\n"
> print line
> jsfile.write(line)
> jsfile.close()
> 
> I tried this can got the same result...??

"""
truncate(...)
truncate([size]) -> None.  Truncate the file to at most size bytes.

Size defaults to the current file position, as returned by tell().
"""

After the readlines() call the current file position is at the end of the
file. Try jsfile.truncate(0).

Also note that readlines() reads the whole file into memory. For large files
it would therefore be better to write to a new file and rename it
afterwards.

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


Re: python script as executable

2008-04-28 Thread sandipm
thanks it worked

On Apr 29, 10:49 am, "Eric Wertman" <[EMAIL PROTECTED]> wrote:
> Try to ftp it in ascii mode, or find a dos2unix utility .. the file
> has probably got \r\n (windows) line terminators in it.. causes
> problems.   I guess it's also possible that /usr/bin/env doesn't
> exist... not likely though.
>
> On Tue, Apr 29, 2008 at 1:36 AM, sandipm <[EMAIL PROTECTED]> wrote:
> > Hi,
> >  I have written a python script to run from cron.
> >  I  have put #!/usr/bin/env python at top. file executes correctly when
> >  I run using python filename.py but
> >  it fails to execute when try to run it like script/command.
> >  it throws error:
> >  :No such file or directory
>
> >  I am editing file from eclipse for python from windows. and then
> >  uploading on linus machine to run it.
>
> >  any pointers?
>
> >  sandip
> >  --
> >  http://mail.python.org/mailman/listinfo/python-list

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


Re: File IO Issues, help :(

2008-04-28 Thread Kevin K
On Apr 29, 12:38 am, "Eric Wertman" <[EMAIL PROTECTED]> wrote:
> chuck in a jsfile.close().  The buffer isn't flushing with what you
> are doing now.  jsfile.flush() might work... not sure.  Closing and
> re-opening the file for sure will help though.
>

Yeah sorry I forgot to include the close() in the quote but its there.
In fact I moved it up a bit and still no luck heres the new code:

jsfile = open("../timeline.js", "r+")
jscontent = jsfile.readlines()
jsfile.truncate()

for line in jscontent:
if re.search('var d =', line):
line = "var d = \""+mint['1'].ascdate()+"\"\n"
print line
jsfile.write(line)
jsfile.close()

I tried this can got the same result...??
--
http://mail.python.org/mailman/listinfo/python-list


Re: python script as executable

2008-04-28 Thread Eric Wertman
Try to ftp it in ascii mode, or find a dos2unix utility .. the file
has probably got \r\n (windows) line terminators in it.. causes
problems.   I guess it's also possible that /usr/bin/env doesn't
exist... not likely though.


On Tue, Apr 29, 2008 at 1:36 AM, sandipm <[EMAIL PROTECTED]> wrote:
> Hi,
>  I have written a python script to run from cron.
>  I  have put #!/usr/bin/env python at top. file executes correctly when
>  I run using python filename.py but
>  it fails to execute when try to run it like script/command.
>  it throws error:
>  :No such file or directory
>
>  I am editing file from eclipse for python from windows. and then
>  uploading on linus machine to run it.
>
>
>  any pointers?
>
>  sandip
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: So you think PythonCard is old? Here's new wine in an old bottle.

2008-04-28 Thread John Henry
On Apr 28, 12:41 pm, John Henry <[EMAIL PROTECTED]> wrote:
> On Apr 27, 12:23 pm, Fred Pacquier <[EMAIL PROTECTED]> wrote:
>
>
>
> > Do keep us posted !
>
> > TIA,
> > fp
>
> Check it out now.
>
> Only one to be added is the Multicolumn List (table), and then menus.
> The other widgets (Togglebutton, BitmapCanvas, Gauge, Notebook,
> CodeEditor) will not be implemented initially.
>
> http://test.powersystemadvisors.com

table and menus all work
--
http://mail.python.org/mailman/listinfo/python-list


python script as executable

2008-04-28 Thread sandipm
Hi,
I have written a python script to run from cron.
I  have put #!/usr/bin/env python at top. file executes correctly when
I run using python filename.py but
it fails to execute when try to run it like script/command.
it throws error:
:No such file or directory

I am editing file from eclipse for python from windows. and then
uploading on linus machine to run it.


any pointers?

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


Re: File IO Issues, help :(

2008-04-28 Thread Eric Wertman
chuck in a jsfile.close().  The buffer isn't flushing with what you
are doing now.  jsfile.flush() might work... not sure.  Closing and
re-opening the file for sure will help though.

On Tue, Apr 29, 2008 at 1:26 AM, Kevin K <[EMAIL PROTECTED]> wrote:
> Hey everyone, I'm new to python and am trying to do a little project
>  with it. I'm running into problems writing over a file. I read from
>  the file and loop through for a specfic case in which I change
>  something. After I open and give it opening options (w, r, etc) one of
>  two things happens: either the file gets truncated and my writing
>  never takes place (or it seems it doesnt) or everything is appended to
>  the file and I have a double of what I started with, its never just
>  the updated file. Can someone shed some light on this for me?? Code
>  below:
>
>  jsfile = open("../timeline.js", "r+")
>  jscontent = jsfile.readlines()
>  jsfile.truncate()
>
>  for line in jscontent:
> if re.search('var d =', line):
> line = "var d = \""+mint['1'].ascdate()+"\"\n"
> print line
> jsfile.write(line)
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


File IO Issues, help :(

2008-04-28 Thread Kevin K
Hey everyone, I'm new to python and am trying to do a little project
with it. I'm running into problems writing over a file. I read from
the file and loop through for a specfic case in which I change
something. After I open and give it opening options (w, r, etc) one of
two things happens: either the file gets truncated and my writing
never takes place (or it seems it doesnt) or everything is appended to
the file and I have a double of what I started with, its never just
the updated file. Can someone shed some light on this for me?? Code
below:

jsfile = open("../timeline.js", "r+")
jscontent = jsfile.readlines()
jsfile.truncate()

for line in jscontent:
if re.search('var d =', line):
line = "var d = \""+mint['1'].ascdate()+"\"\n"
print line
jsfile.write(line)
--
http://mail.python.org/mailman/listinfo/python-list


Re: descriptor & docstring

2008-04-28 Thread George Sakkis
On Apr 28, 10:59 pm, "Gabriel Genellina"

> def property_default(prop_name, default_value=None, doc=None):
>
>      attr_name = '_'+prop_name
>
>      def fget(self, attr_name=attr_name,
>                     default_value=default_value):
>          return getattr(self, attr_name, default_value)
>
>      def fset(self, value,
>                     attr_name=attr_name,
>                     default_value=default_value):
>          if value == default_value:
>              delattr(self, attr_name)
>          else:
>              setattr(self, attr_name, value)
>
>      return property(fget=fget, fset=fset, doc=doc)
>
> When setting the same value as the default, the instance attribute is  
> removed (so the default will be used when retrieving the value later). I  
> think this is what you intended to do.

Note that this will fail if the value is already equal to the default
and you try to reset it to the default, so it needs an extra
hasattr(self, attr_name) before the delattr. Regardless, I would be
surprised with the following behaviour:

>>> r = Rectangle()
>>> r.length = 4
>>> type(r.length)

>>> r.length = 12
>>> type(r.length)


Another simpler alternative would be to (ab)use a decorator:

def defaultproperty(func):
attr = '_' + func.__name__
default = func.func_defaults[0]
return property(
fget = lambda self: getattr(self, attr, default),
fset = lambda self,value: setattr(self, attr, value),
doc = func.__doc__)


class Rectangle(object):
'''A beautiful Rectangle'''

@defaultproperty
def length(default=12.0):
'''This is the length property'''

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


Re: cytpes **int

2008-04-28 Thread Gabriel Genellina
En Mon, 28 Apr 2008 18:55:15 -0300, Diez B. Roggisch <[EMAIL PROTECTED]>  
escribió:

VernM schrieb:

I am using ctypes to wrap a set of functions in a DLL. It has been
going very well, and I am very impressed with ctypes. I want to call a
c function with a signature of: void func(int **cube), where the array
if ints in cube is modified by func. I want to setup cube with int
values, and access them after the call to func. I unerstand how to
setup the ctypes array, but how do I pass **cube to the function, and
how do I access the results?


it should be simple.

use something like (untestet):

b = POINTER(c_int)()
func(byref(b))


[snip two other similar alternatives]

That's true for "a pointer to a pointer to int", and it's valid if the  
functions references **b or b[0][0] - but in this case int** probably  
means "[pointer to] an array of arrays of int" and presumibly the function  
will try to access b[3][2] (or whatever indices are in range).
The duality pointer/array in C is dangerous when defining interfases - you  
have to know how the value is intended to be accessed.
(I assume the function modifies the integer values, but not the pointers  
themselves)


# build an array of 10x10 ints
Arr10int = c_int * 10
Pint = POINTER(c_int)
PPint = POINTER(Pint)
Arr10pint = Pint * 10
a = Arr10pint()
for i in range(10):
a[i] = Arr10int()
... initialize the array ...
... load the function ...
# call the function
somefunction.argtypes = (PPint,)
somefunction.restype = None
somefunction(a)

--
Gabriel Genellina

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


Re: Python Math libraries - How to?

2008-04-28 Thread Cousin Stanley

>
> Here is the arithmetic program I made that it worked before I added
> the "import math" line.  
>
> #volumen.py
> # A program to compute the volume and surface area of a sphere
> import math
>
> 
> NameError: global name 'pi' is not defined
> 

>>> from math import *
>>>
>>> def surface( r ) :
... return 4 * pi * r ** 2
...
>>> def volume( r ) :
... return ( 4. / 3. ) * pi * r ** 3
...
>>> for n in range( 1 , 11 ) :
... s = surface( n )
... v = volume( n )
... print '%2d  %9.4f  %9.4f ' % ( n , s , v )
...


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona

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


Re: Python Math libraries - How to?

2008-04-28 Thread Terry Reedy

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

You have several ways to import a module, and your choice determines how
you access things.

Method 1:

import math

Then use:  math.pi, math.sqrt, math.sin, math.cos, ...

Method 2:

from math import pi, sqrt

Then use pi, and sqrt.
But other module attributes (like sin, and cos) are not accessible.


Method 3:

from math import *

Then use pi, sqrt, cos, sin, and anything else defined by the module.
(This is sometime  frowned upon, but there's no reason to do so here.)
|
=
|
There are two good reasons for the frown.

One is for the potential conflict between builtin names, imported names 
(from possibly multiple modules), and names defined in the module. 
Builtins and math both have 'pow' functions that I believe are slightly 
different (or maybe once were).  Math and cmath have 13 functions with 
duplicate names but different input and output (2.5).  Importing * from 
both would be disasterous.

The other is that someone not familiar with the imported module(s) will not 
know where a particular name came from when reading the code.  Both 
problems are obvious worse with multiple imports.

Method 4: (my favorite when using multiple names from a module)

import math as m

Then use m.pi, etc.

tjr






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


Re: descriptor & docstring

2008-04-28 Thread Gabriel Genellina
En Mon, 28 Apr 2008 14:35:40 -0300, cyril giraudon  
<[EMAIL PROTECTED]> escribió:



Hello,

I try to use python descriptors to define attributes with default
value (the code is reported below).
But apparently, it breaks the docstring mechanism.

help(Basis) shows the right help but help(Rectangle) shows only two
lines :
"
Help on class Rectangle in module basis2:

Rectangle = 
"
If the Rectangle.length attribute is removed, the help is OK.

Secondly, the __doc__ attribute of a PhysicalValue instance doesn't
seem to be read.

I don't understand.

Any idea ?


This looks like a soup of descriptors, metaclasses and properties...
I'll write a two step example. I assume that you want to define an  
attribute with a default value: when not explicitely set, it returns the  
default value. This can be implemented with an existing descriptor:  
property. The only special thing is to handle the default value.


Step 1: Our first attempt will let us write something like this:

class X(object:
  length = property_default("length", 12., "This is the length property")

We have to write property_default so it returns a property object with the  
right fget and fset methods. Let's use the same convention as your code,  
property "foo" will store its value at attribute "_foo".


def property_default(prop_name, default_value=None, doc=None):

attr_name = '_'+prop_name

def fget(self, attr_name=attr_name,
   default_value=default_value):
return getattr(self, attr_name, default_value)

def fset(self, value,
   attr_name=attr_name,
   default_value=default_value):
if value == default_value:
delattr(self, attr_name)
else:
setattr(self, attr_name, value)

return property(fget=fget, fset=fset, doc=doc)

When setting the same value as the default, the instance attribute is  
removed (so the default will be used when retrieving the value later). I  
think this is what you intended to do.

That's all. The classes look like this:

# just to use a more meaningful name, if you wish
PhysicalValue = property_default

# A basis class
class Basis(object):
  """
  Tempest basis class
  """

# A concrete class
class Rectangle(Basis):
  """
  A beautiful Rectangle
  """
  length = PhysicalValue("length", 12., "This is the length property")

py> r = Rectangle()
py> print r.length
12.0
py> r.length = 13.5
py> print r.length
13.5
py> dir(r)
['__class__', ... '_length', 'length']
py> r.length = 12
py> dir(r)
['__class__', ... 'length']

Help works too:

py> help(Rectangle)
Help on class Rectangle in module __main__:

class Rectangle(Basis)
 |  A beautiful Rectangle
 |
 |  Method resolution order:
 |  Rectangle
 |  Basis
 |  __builtin__.object
 |  [...]

py> help(Rectangle.length)
Help on property:

This is the length property



Step 2: The problem with the property_default declaration above is that it  
repeats the name "length". If we want to comply with the DRY principle, we  
can use a metaclass (note that the previous solution doesn't require a  
custom metaclass). In the class declaration, we only have to store the  
parameters needed to define the property; later, when the class is created  
(the metaclass __new__ method), we replace those parameters with an actual  
property object. The fget/gset implementation is the same as above.


class property_default(object):
"""Store info for defining a property with a default value.
Replaced with a real property instance at class creation time.
"""
def __init__(self, default_value, doc=None):
self.default_value = default_value
self.doc = doc

# just to use a more meaningful name, if you wish
class PhysicalValue(property_default): pass

class PropDefaultMetaClass(type):
def __new__(cls, name, bases, dct):
# replace all property_default declarations
# with an actual property object
# (we can't modify dct at the same time
# we iterate over it, so collect the new items
# into another dictionary)
newprops = {}
for prop_name, prop in dct.iteritems():
if isinstance(prop, property_default):
attr_name = '_'+prop_name
def fget(self, attr_name=attr_name,
   default_value=prop.default_value):
return getattr(self, attr_name, default_value)
def fset(self, value,
   attr_name=attr_name,
   default_value=prop.default_value):
if value == default_value:
delattr(self, attr_name)
else:
setattr(self, attr_name, value)
newprops[prop_name] = property(
  fget=fget, fset=fset,
  doc=prop.doc)
dct.update(newprops)
return super(MyMetaClass, cls).__new__(cls, name, bases, dct)

# 

Re: Python Math libraries - How to?

2008-04-28 Thread aguirre . adolfo
Thank you :-), I´ll do
Adolfo
>
> pi is not a global name. When you do "import math",you aren't adding
> everything to the name space, you are just telling python that you are
> going to be using that file. You then refer to it as math.*, such as
> "math.pi", or "math.pow(r,3)". To use it the way you want to, you
> would have to do "from math import pi" instead of "import math"

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


Re: Python Math libraries - How to?

2008-04-28 Thread aguirre . adolfo
>
> Thank you. I´ll try all methods to figure out the convenience of each
Adolfo
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to unget a line when reading from a file/stream iterator/generator?

2008-04-28 Thread George Sakkis
On Apr 28, 10:10 pm, [EMAIL PROTECTED] wrote:
> George,
>
> > Is there an elegant way to unget a line when reading from a file/stream 
> > iterator/generator?
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502304
>
> That's exactly what I was looking for!
>
> For those following this thread, the above recipe creates a generic
> object that wraps any iterator with an 'unget' ("push") capability.
> Clean and elegant!
>
> Thank you,
> Malcolm

A small suggestion: since unget is expected to be called infrequently,
next should better be faster for the common case instead of penalizing
it with a try/except:

def next(self):
if not self.pushed_back:
return self.it.next()
else:
return self.pushed_back.pop()

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


Re: Python Math libraries - How to?

2008-04-28 Thread aguirre . adolfo
Hi, thak you. I get the following:
>
> > *** Error message *
>
> > Traceback (most recent call last):
> >   File "C:/Python25/z - MIS PROGRAMAS/volumen-b.py", line 20,
> >   in
> > 
> > main()
> >   File "C:/Python25/z - MIS PROGRAMAS/volumen-b.py", line 13,
> >   in main
> > volume = 4/3*pi*r3
> > NameError: global name 'pi' is not defined

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


Re: xcode able to run script?

2008-04-28 Thread Stormbringer
On Apr 28, 1:52 pm, Alex Pavluck <[EMAIL PROTECTED]> wrote:
> Does anyone know if it is possible to test your scripts from within
> the xcode editor?  I am currently using Uilipad on windows and there
> is a sub window that lets you view your output when you launch the
> script from within the ide.  hopefully this makes sense.
>
> thanks, Alex

Use SPE, it has this functionality plus a lot more.You can get it at:

http://pythonide.blogspot.com/

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



Re: Python Math libraries - How to?

2008-04-28 Thread Benjamin Kaplan
On Mon, Apr 28, 2008 at 10:07 PM,  <[EMAIL PROTECTED]> wrote:
> Hi, I am a very newbie who would very much appreciate some hints.
>
>  Python 2.52. on Windows XP for now. Soon on Ubuntu 8
>
>  I am teaching myself Python following free tutorials. I can solve
>  problems using arithmetic, but when I try to upgrade the programs
>  using math libraries nothing seems to work. I downloaded a 2002
>  tutorial from Zelle "An Introduction to Computer Science" where he
>  uses a "import math" statement to calculate a square root. I tried the
>  "pi" library function but it didn´t work. I tried using def Pi()  it
>  did not work either. I am yet to find a tutorial that explains how to
>  declare (or initialize) and pass numbers to the functions such as
>  "cos(x)" and the pi which does not have a variable in it. Is just a
>  constant.
>
>  Here is the arithmetic program I made that it worked before I added
>  the "import math" line.  I  erased the constant p = 3.1416 and added
>  the "i" for the library function "pi" in the algorithms. But I get an
>  error message not recognizing "pi"
>
>
>
>  #volumen.py
>  # A program to compute the volume and surface area of a sphere
>  import math
>
>  def main():
>
> print "This program calculates the volume and surface area of a
>  sphere"
> print
> r = input("Please enter the radious: ")
> print
> r3 = r*r*r
> volume = 4/3*pi*r3
> r2 = r*r
> surface = 4*pi*r2
> print "The Volume is", volume, " Cubic centimeters"
> print
> print "The Surface area is", surface, " square centimeters"
>
>  main()
>
>  *** Error message *
>
>  Traceback (most recent call last):
>   File "C:/Python25/z - MIS PROGRAMAS/volumen-b.py", line 20, in
>  
> main()
>   File "C:/Python25/z - MIS PROGRAMAS/volumen-b.py", line 13, in main
> volume = 4/3*pi*r3
>  NameError: global name 'pi' is not defined
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>

pi is not a global name. When you do "import math",you aren't adding
everything to the name space, you are just telling python that you are
going to be using that file. You then refer to it as math.*, such as
"math.pi", or "math.pow(r,3)". To use it the way you want to, you
would have to do "from math import pi" instead of "import math"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Math libraries - How to?

2008-04-28 Thread John Henderson
[EMAIL PROTECTED] wrote:

> Hi, I am a very newbie who would very much appreciate some
> hints.
> 
> Python 2.52. on Windows XP for now. Soon on Ubuntu 8
> 
> I am teaching myself Python following free tutorials. I can
> solve problems using arithmetic, but when I try to upgrade the
> programs using math libraries nothing seems to work. I
> downloaded a 2002 tutorial from Zelle "An Introduction to
> Computer Science" where he uses a "import math" statement to
> calculate a square root. I tried the
> "pi" library function but it didn´t work. I tried using def
> Pi()  it did not work either. I am yet to find a tutorial that
> explains how to declare (or initialize) and pass numbers to
> the functions such as "cos(x)" and the pi which does not have
> a variable in it. Is just a constant.
> 
> Here is the arithmetic program I made that it worked before I
> added
> the "import math" line.  I  erased the constant p = 3.1416 and
> added the "i" for the library function "pi" in the algorithms.
> But I get an error message not recognizing "pi"
> 
> 
> 
> #volumen.py
> # A program to compute the volume and surface area of a sphere
> import math


Change that line, "import math", to:

from math import *

and it'll work.  I'm learning too, so some proficient person
might be able to explain the difference to both of us :)

John


> 
> def main():
> 
> print "This program calculates the volume and surface area
> of a
> sphere"
> print
> r = input("Please enter the radious: ")
> print
> r3 = r*r*r
> volume = 4/3*pi*r3
> r2 = r*r
> surface = 4*pi*r2
> print "The Volume is", volume, " Cubic centimeters"
> print
> print "The Surface area is", surface, " square
> centimeters"
> 
> main()
> 
> *** Error message *
> 
> Traceback (most recent call last):
>   File "C:/Python25/z - MIS PROGRAMAS/volumen-b.py", line 20,
>   in
> 
> main()
>   File "C:/Python25/z - MIS PROGRAMAS/volumen-b.py", line 13,
>   in main
> volume = 4/3*pi*r3
> NameError: global name 'pi' is not defined

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

Re: Python Math libraries - How to?

2008-04-28 Thread Gary Herron

[EMAIL PROTECTED] wrote:

Hi, I am a very newbie who would very much appreciate some hints.

Python 2.52. on Windows XP for now. Soon on Ubuntu 8

I am teaching myself Python following free tutorials. I can solve
problems using arithmetic, but when I try to upgrade the programs
using math libraries nothing seems to work. I downloaded a 2002
tutorial from Zelle "An Introduction to Computer Science" where he
uses a "import math" statement to calculate a square root. I tried the
"pi" library function but it didn´t work. I tried using def Pi()  it
did not work either. I am yet to find a tutorial that explains how to
declare (or initialize) and pass numbers to the functions such as
"cos(x)" and the pi which does not have a variable in it. Is just a
constant.

Here is the arithmetic program I made that it worked before I added
the "import math" line.  I  erased the constant p = 3.1416 and added
the "i" for the library function "pi" in the algorithms. But I get an
error message not recognizing "pi"
  


You have several ways to import a module, and your choice determines how 
you access things.


Method 1:

import math

Then use:  math.pi, math.sqrt, math.sin, math.cos, ...

Method 2:

from math import pi, sqrt

Then use pi, and sqrt.
But other module attributes (like sin, and cos) are not accessible.


Method 3:

from math import *

Then use pi, sqrt, cos, sin, and anything else defined by the module.
(This is sometime  frowned upon, but there's no reason to do so here.)

Gary Herron






#volumen.py
# A program to compute the volume and surface area of a sphere
import math

def main():

print "This program calculates the volume and surface area of a
sphere"
print
r = input("Please enter the radious: ")
print
r3 = r*r*r
volume = 4/3*pi*r3
r2 = r*r
surface = 4*pi*r2
print "The Volume is", volume, " Cubic centimeters"
print
print "The Surface area is", surface, " square centimeters"

main()

*** Error message *

Traceback (most recent call last):
  File "C:/Python25/z - MIS PROGRAMAS/volumen-b.py", line 20, in

main()
  File "C:/Python25/z - MIS PROGRAMAS/volumen-b.py", line 13, in main
volume = 4/3*pi*r3
NameError: global name 'pi' is not defined
--
http://mail.python.org/mailman/listinfo/python-list
  


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


Re: How to unget a line when reading from a file/stream iterator/generator?

2008-04-28 Thread python
George,

> Is there an elegant way to unget a line when reading from a file/stream 
> iterator/generator?

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502304

That's exactly what I was looking for! 

For those following this thread, the above recipe creates a generic
object that wraps any iterator with an 'unget' ("push") capability.
Clean and elegant!

Thank you,
Malcolm
--
http://mail.python.org/mailman/listinfo/python-list


Python Math libraries - How to?

2008-04-28 Thread aguirre . adolfo
Hi, I am a very newbie who would very much appreciate some hints.

Python 2.52. on Windows XP for now. Soon on Ubuntu 8

I am teaching myself Python following free tutorials. I can solve
problems using arithmetic, but when I try to upgrade the programs
using math libraries nothing seems to work. I downloaded a 2002
tutorial from Zelle "An Introduction to Computer Science" where he
uses a "import math" statement to calculate a square root. I tried the
"pi" library function but it didn´t work. I tried using def Pi()  it
did not work either. I am yet to find a tutorial that explains how to
declare (or initialize) and pass numbers to the functions such as
"cos(x)" and the pi which does not have a variable in it. Is just a
constant.

Here is the arithmetic program I made that it worked before I added
the "import math" line.  I  erased the constant p = 3.1416 and added
the "i" for the library function "pi" in the algorithms. But I get an
error message not recognizing "pi"



#volumen.py
# A program to compute the volume and surface area of a sphere
import math

def main():

print "This program calculates the volume and surface area of a
sphere"
print
r = input("Please enter the radious: ")
print
r3 = r*r*r
volume = 4/3*pi*r3
r2 = r*r
surface = 4*pi*r2
print "The Volume is", volume, " Cubic centimeters"
print
print "The Surface area is", surface, " square centimeters"

main()

*** Error message *

Traceback (most recent call last):
  File "C:/Python25/z - MIS PROGRAMAS/volumen-b.py", line 20, in

main()
  File "C:/Python25/z - MIS PROGRAMAS/volumen-b.py", line 13, in main
volume = 4/3*pi*r3
NameError: global name 'pi' is not defined
--
http://mail.python.org/mailman/listinfo/python-list


Python Math libraries - How to?

2008-04-28 Thread aguirre . adolfo
Hi, I am a very newbie who would very much appreciate some hints.

Python 2.52. on Windows XP for now. Soon on Ubuntu 8

I am teaching myself Python following free tutorials. I can solve
problems using arithmetic, but when I try to upgrade the programs
using math libraries nothing seems to work. I downloaded a 2002
tutorial from Zelle "An Introduction to Computer Science" where he
uses a "import math" statement to calculate a square root. I tried the
"pi" library function but it didn´t work. I tried using def Pi()  it
did not work either. I am yet to find a tutorial that explains how to
declare (or initialize) and pass numbers to the functions such as
"cos(x)" and the pi which does not have a variable in it. Is just a
constant.

Here is the arithmetic program I made that it worked before I added
the "import math" line.  I  erased the constant p = 3.1416 and added
the "i" for the library function "pi" in the algorithms. But I get an
error message not recognizing "pi"



#volumen.py
# A program to compute the volume and surface area of a sphere
import math

def main():

print "This program calculates the volume and surface area of a
sphere"
print
r = input("Please enter the radious: ")
print
r3 = r*r*r
volume = 4/3*pi*r3
r2 = r*r
surface = 4*pi*r2
print "The Volume is", volume, " Cubic centimeters"
print
print "The Surface area is", surface, " square centimeters"

main()

*** Error message *

Traceback (most recent call last):
  File "C:/Python25/z - MIS PROGRAMAS/volumen-b.py", line 20, in

main()
  File "C:/Python25/z - MIS PROGRAMAS/volumen-b.py", line 13, in main
volume = 4/3*pi*r3
NameError: global name 'pi' is not defined
--
http://mail.python.org/mailman/listinfo/python-list


Re: Receive data from socket stream

2008-04-28 Thread Gabriel Genellina

En Mon, 28 Apr 2008 19:29:33 -0300, <[EMAIL PROTECTED]> escribió:


A question regarding cStringIO.StringIO(): is there a way to do get
getvalue() to return all the bytes after the current file position
(not before)? For example

buf = cStringIO.StringIO()
buf.write("foo bar")
buf.seek(3)
buf.getvalue(True) # the True argument means
   # to return the bytes up
   # to the current file position

That returns 'foo'. Is there a way to get it to return ' bar'?


buf.read() - the obvious answer, once you know it :)

--
Gabriel Genellina

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


Re: Automating IE 6.0

2008-04-28 Thread Mike Driscoll

Michael Harris wrote:


I tried to use the sample code to print a webpage via ie and I get the 
following error:


 


Traceback (most recent call last):

  File 
"C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", 
line 310, in RunScript


exec codeObject in __main__.__dict__

  File "C:\ie.py", line 14, in 

ie.ExecWB(win32com.client.constants.OLECMDID_PRINT, 
win32com.client.constants.OLECMDEXECOPT_DONTPROMPTUSER)


NameError: name 'win32com' is not defined

 


I have the win32com module installed and I clicked on makepy.py and selected 
Microsoft Internet Controls (1.1).  The code was:
 
from win32com.client import Dispatch

from time import sleep
ie = Dispatch("InternetExplorer.Application")
ie.Visible = 1
ie.Navigate("http://www.cnn.com"; )
if ie.Busy:
 sleep(2)
# print the current IE document without prompting the user for the
printerdialog
ie.ExecWB(win32com.client.constants.OLECMDID_PRINT,win32com.client.constants
.OLECMDEXECOPT_DONTPROMPTUSER)
 


Why am I getting this error?

I don't know why this is happening, so I recommend posting it to the 
pywin32 group: http://mail.python.org/mailman/listinfo/python-win32


You might also check out the PAMIE project: 
http://sourceforge.net/projects/pamie


SendKeys would also work, but it's kind of messy.

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


Re: Simple unicode-safe version of str(exception)?

2008-04-28 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:

> >> I have code like this:
> >> except Exception, e:
> >>self.setState(self.Failed, str(e))
> >> which fails if the exception contains a unicode argument.
> > 
> > Fails how?
> 
> ASCII encoding error, I suppose. It fails only if a) one argument
> is a Unicode object, and b) that Unicode object contains non-ASCII
> parameters.

Seem ironic that this fails even though pretty nearly anything
else is a valid input to str() -- socket, dict, whatever?

A sort of generic solution might be to follow str's behavior
with respect to '__str__', extending it to fall back to repr()
whatever goes wrong.


def xtr(a):
try:
return str(a)
except:
return repr(a)

...
self.setState(self.Failed, xtr(e))

   Donn Cave, [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list

Re: Question regarding Queue object

2008-04-28 Thread Terry
On Apr 28, 10:48 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> I've never used it myself but you may find candygram 
> interesting;http://candygram.sourceforge.net, which AFAIK implements 
> Erlang-style
> message queues in Python.

Thank you. I will look at candygram and stackless. I believe my
solution lies in either of them.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question regarding Queue object

2008-04-28 Thread Terry
On Apr 28, 5:30 pm, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> David <[EMAIL PROTECTED]> wrote:
> >  Another idea would be to have multiple queues, one per thread or per
> >  message type "group". The producer thread pushes into the appropriate
> >  queues (through an intelligent PutMsg function), and the consumer
> >  threads pull from the queues they're interested in and ignore the
> >  others.
>
> Unfortunately a thread can only wait on one Queue at once (without
> polling).  So really the only efficient solution is one Queue per
> thread.
>
> Make an intelligent PutMsg function which knows which Queue (or
> Queues) each message needs to be put in and all the threads will have
> to do is Queue.get() and be sure they've got a message they can deal
> with.
>
> --
> Nick Craig-Wood <[EMAIL PROTECTED]> --http://www.craig-wood.com/nick


I do have one Queue per thread. The problem is the thread can not peek
into the Queue and select msg with certain ID first.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple unicode-safe version of str(exception)?

2008-04-28 Thread Martin v. Löwis
>> I have code like this:
>> except Exception, e:
>>self.setState(self.Failed, str(e))
>> which fails if the exception contains a unicode argument.
> 
> Fails how?

ASCII encoding error, I suppose. It fails only if a) one argument
is a Unicode object, and b) that Unicode object contains non-ASCII
parameters.

>> I did, of course, try unicode(e) but that fails.
> 
> Converting unicode to unicode doesn't help.

e is an exception object, not a Unicode object.

Regards,
Martin

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


Re: Tremendous slowdown due to garbage collection

2008-04-28 Thread Martin v. Löwis
> I do not argue that Python's default GC parameters must change -- only
> that applications with lots of objects may want to consider a
> reconfiguration.

That's exactly what I was trying to say: it's not that the parameters
are useful for *all* applications (that's why they are tunable
parameters), just that the defaults shouldn't change (as the OP was
requesting).

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


Re: Receive data from socket stream

2008-04-28 Thread s0suk3
On Apr 28, 4:42 am, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Nick Craig-Wood <[EMAIL PROTECTED]> writes:
> > What you are missing is that if the recv ever returns no bytes at all
> > then the other end has closed the connection.  So something like this
> > is the correct thing to write :-
>
> >   data = ""
> >   while True:
> >   new = client.recv(256)
> >   if not new:
> >   break
> >   data += new
>
> This is a good case for the iter() function:
>
> buf = cStringIO.StringIO()
> for new in iter(partial(client.recv, 256), ''):
> buf.write(new)
> data = buf.getvalue()
>
> Note that appending to a string is almost never a good idea, since it
> can result in quadratic allocation.

A question regarding cStringIO.StringIO(): is there a way to do get
getvalue() to return all the bytes after the current file position
(not before)? For example

buf = cStringIO.StringIO()
buf.write("foo bar")
buf.seek(3)
buf.getvalue(True) # the True argument means
   # to return the bytes up
   # to the current file position

That returns 'foo'. Is there a way to get it to return ' bar'?
--
http://mail.python.org/mailman/listinfo/python-list


Re: py3k concerns. An example

2008-04-28 Thread Martin v. Löwis
> Unless I mix my psuedodicts with standard dicts
> in the same list, for example, or pass them to
> functions intended to accept any dict-like object,
> including the especially important case of standard
> dicts.
> 
> Who knows?  Maybe I'm wrong about this being a much of
> problem. 

I think so. I expect that in the typical application, you either
won't notice the difference in behavior at all, or you get an
exception the first time, in which case you can easily adjust
the code to support both cases. This expectation is supported
by experience both from adjusting the Python standard library
itself, and from converting Django to Python 3.

In my experience (from the same applications), by far the most
significant change in Python 3 is the change to the meaning of
string literals, and the disposal of the 2.x str type.

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


Re: Given a string - execute a function by the same name

2008-04-28 Thread Max M

[EMAIL PROTECTED] skrev:

I'm parsing a simple file and given a line's keyword, would like to call
the equivalently named function.

There are 3 ways I can think to do this (other than a long if/elif
construct):

1. eval() 


2. Convert my functions to methods and use getattr( myClass, "method" )

3. Place all my functions in dictionary and lookup the function to be
called

Any suggestions on the "best" way to do this?


No reason to use eval.

use either getattr(obj, "method")() or functions['method']

They are basically the same thing.

The dict of functions is a bit safer. You don't risk calling a built in 
method on your object . Which you risk doing with something like: 
getattr(obj, 'join')




--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

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


Re: cytpes **int

2008-04-28 Thread Diez B. Roggisch

VernM schrieb:

I am using ctypes to wrap a set of functions in a DLL. It has been
going very well, and I am very impressed with ctypes. I want to call a
c function with a signature of: void func(int **cube), where the array
if ints in cube is modified by func. I want to setup cube with int
values, and access them after the call to func. I unerstand how to
setup the ctypes array, but how do I pass **cube to the function, and
how do I access the results?


it should be simple.

use something like (untestet):

b = POINTER(c_int)()
func(byref(b))


Or

a = c_int()
b = pointer(a)
func(byref(b)

Or

b = POINTER(c_int)()
func(pointer(b))


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


Re: Installed python 2.5 over 2.4 and lost installed packages

2008-04-28 Thread Jason
On Apr 28, 1:46 pm, [EMAIL PROTECTED] wrote:
> On Apr 27, 8:42 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote:
>
> > On Apr 27, 8:15 am, [EMAIL PROTECTED] wrote:
> > > I recently updated os x from python 2.4 to 2.5 (from python.org) and
> > > in doing so I lost my old python path entries.
> > > So what is the right thing to do in this situation?
> > > Is cp'ing the files from one place to another safe or advisable?
> > As long as the Python extensions or packages are pure ones, then
> > copying them over shouldn't hurt anything. If you have some that have
> > C/C++ links (such as PIL or pywin32), then you'll need to reinstall
> > those manually.
>
> I tried that and the C extensions burned me.  Syck (for YAML) and
> mercurial (I think ... there were  at least 2 problems) posted
> warnings or bailed out with errors.  Looks like I will delay until I
> have the time and energy to chase all my dependencies.  Perhaps once
> my server (Ubuntu) moves to 2.6 I'll update my Mac at the same time.
>
> From now on I am storing my install packages somewhere accessible
> instead of deleting them once I'm done with them.  I wish I could
> generate a manifest of installed packages to make upgrading easier.
>
> Cheers,
> James.

If you used Easy Install [1] to install your extra packages, go to
your site-packages directory.  You should find a file called "easy-
install.pth".  All packages that Easy Install provided should be in
there.

[1] Found at: http://peak.telecommunity.com/DevCenter/EasyInstall

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


Re: Little novice program written in Python

2008-04-28 Thread Rogério Brito

On 04/25/2008 09:30 AM, Nick Craig-Wood wrote:

When you are up to speed in python I suggest you check out gmpy for
number theory algorithms.


Thanks. That is quite useful to know when I don't want to code explicitly the 
details of the algorithm.



Thanks, Rogério.

--
Rogério Brito : [EMAIL PROTECTED],ime.usp}.br : GPG key 1024D/7C2CAEB8
http://www.ime.usp.br/~rbrito : http://meusite.mackenzie.com.br/rbrito
Projects: algorithms.berlios.de : lame.sf.net : vrms.alioth.debian.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Little novice program written in Python

2008-04-28 Thread Rogério Brito

On 04/25/2008 05:00 AM, John Machin wrote:

On Apr 25, 5:44 pm, Robert Bossy <[EMAIL PROTECTED]> wrote:

If the OP insists in not examining a[0] and a[1], this will do exactly
the same as the while version:

for p in a[2:]:
if p:
print p


... at the cost of almost doubling the amount of memory required.


Yes, despite the asymptotic consumption of memory being the same, the practical 
one is also a concern. And in my original version of that loop (sketched in 
paper) was a for loop, but with C syntax.


--
Rogério Brito : [EMAIL PROTECTED],ime.usp}.br : GPG key 1024D/7C2CAEB8
http://www.ime.usp.br/~rbrito : http://meusite.mackenzie.com.br/rbrito
Projects: algorithms.berlios.de : lame.sf.net : vrms.alioth.debian.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: descriptor & docstring

2008-04-28 Thread cyril giraudon
A precision, I use python 2.5.2 under linux mandiva 2007.0

Cyril.


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


Re: Little novice program written in Python

2008-04-28 Thread Rogério Brito

On 04/25/2008 01:30 AM, Steve Holden wrote:

Rogério Brito wrote:
I'm just getting my feet wet on Python and, just for starters, I'm 
coding some elementary number theory algorithms (yes, I know that most 
of them are already implemented as modules, but this is an exercise in 
learning the language idioms).
Your Python is actually pretty good - if Raymond Hettinger pronounces it 
OK then few would dare to disagree.


Thank you.

As for your English, though, the word you sought was "Pythonic" (not 
that you will ever find such a word in Webster's dictionary). To suggest 
that your code is Pythonesque would mean you found it farcical or 
ridiculous (like a Monty Python sketch), which it clearly is not.


I didn't know about the pejorative meaning of Pythonesque. :-) Thanks for the 
comment on my English (which should be obvious that I'm not a native speaker).



PS: I think either my mailer or yours has mangled the indentation.


I think that it was mine.


Thanks, Rogério Brito.

--
Rogério Brito : [EMAIL PROTECTED],ime.usp}.br : GPG key 1024D/7C2CAEB8
http://www.ime.usp.br/~rbrito : http://meusite.mackenzie.com.br/rbrito
Projects: algorithms.berlios.de : lame.sf.net : vrms.alioth.debian.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Little novice program written in Python

2008-04-28 Thread Rogério Brito

On 04/25/2008 01:09 AM, Dennis Lee Bieber wrote:

On Thu, 24 Apr 2008 21:31:15 -0300, Rogério Brito <[EMAIL PROTECTED]>
declaimed the following in comp.lang.python:

a = [i for i in range(0,n+1)]


Uhm... At least in 2.4 and earlier, range() returns a list... No
need for the list-comp in that era... range() also begins with 0


Thanks for the suggestion. As I stated in my original message, I'm only 
"side-learning" Python, and I naturally think in list-comprehensions (it is like 
a set in Mathematics and you've seen that my program is Mathematical in its nature).


This is exactly the kind of suggestion that I was looking for.


Thanks, Rogério.

--
Rogério Brito : [EMAIL PROTECTED],ime.usp}.br : GPG key 1024D/7C2CAEB8
http://www.ime.usp.br/~rbrito : http://meusite.mackenzie.com.br/rbrito
Projects: algorithms.berlios.de : lame.sf.net : vrms.alioth.debian.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to unget a line when reading from a file/stream iterator/generator?

2008-04-28 Thread George Sakkis
On Apr 28, 2:07 pm, [EMAIL PROTECTED] wrote:
> Is there an elegant way to unget a line when reading from a file/stream
> iterator/generator?
>
> By "unget" I mean a way to push back a line into the source stream and
> backtrack the iterator/generator one step?
>
> The only alternative I can see is to put my line reading in a while-True
> loop (vs. a for-loop) that manually calls my file/stream
> iterator/generator's .next() method while manually handling the
> StopIteration exception. Doesn't sound too elegant.
>
> Is there a Pythonic design pattern/best practice that I can apply here?
>
> Thank you,
> Malcolm

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502304

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


Python-URL! - weekly Python news and links (Apr 28)

2008-04-28 Thread Gabriel Genellina
QOTW:  "Posting to comp.lang.python is pair programming with the entire
internet ;-)" - Nick Craig-Wood
http://groups.google.com/group/comp.lang.python/msg/6f13cfca8a92c1a2

"When it got to the point where managers were asking, 'Why didn't you use
the config check tool?', it was a done deal." - Roy Smith, on Python adoption
http://mail.python.org/pipermail/advocacy/2008-April/000575.html


Ideas to design a Python client/server application involving many
aynchronous queries and real-time display of data:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/5e46184e940886b9/

Explicit variable declaration for functions:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/6c4a508edd2fbe04/

An example showing the difference between inheritance and composition:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/44612866d4d2fedb/

Lists: item and slice assignment are confusing for a novice Python
programmer:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/d00b0c848a3003fc/

Converting xhtml to html isn't as trivial as one might expect:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/4bbbcecf89693a74/

Using the subprocess module with non-blocking pipes:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/a6dd7b98211bbd4c/

Calling Python from PHP

http://groups.google.com/group/comp.lang.python/browse_thread/thread/ffb9d476ee4cd523/

People worried about code breakage in Python 3.0 (continued from last week)

http://groups.google.com/group/comp.lang.python/browse_thread/thread/f07feff4f01be76f/

Python Advocacy: success stories

http://groups.google.com/group/comp.lang.python/browse_thread/thread/1bd91aca0c86c57c/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish "the efforts of Python enthusiats":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

Steve Bethard continues the marvelous tradition early borne by
Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim
Lesher of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few

Re: Simple unicode-safe version of str(exception)?

2008-04-28 Thread Bjoern Schliessmann
Russell E. Owen wrote:

> I have code like this:
> except Exception, e:
>self.setState(self.Failed, str(e))
> which fails if the exception contains a unicode argument.

Fails how?
 
> I did, of course, try unicode(e) but that fails.

Converting unicode to unicode doesn't help. Instead of just e, try
using e.encode("some-encoding") where some-encoding should be your
system's default encoding like utf-8 or iso8859-1.

Regards,


Björn

-- 
BOFH excuse #434:

Please state the nature of the technical emergency

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


Re: Installed python 2.5 over 2.4 and lost installed packages

2008-04-28 Thread james
On Apr 27, 8:42 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote:
> On Apr 27, 8:15 am, [EMAIL PROTECTED] wrote:

> > I recently updated os x from python 2.4 to 2.5 (from python.org) and
> > in doing so I lost my old python path entries.

> > So what is the right thing to do in this situation?
> > Is cp'ing the files from one place to another safe or advisable?

> As long as the Python extensions or packages are pure ones, then
> copying them over shouldn't hurt anything. If you have some that have
> C/C++ links (such as PIL or pywin32), then you'll need to reinstall
> those manually.

I tried that and the C extensions burned me.  Syck (for YAML) and
mercurial (I think ... there were  at least 2 problems) posted
warnings or bailed out with errors.  Looks like I will delay until I
have the time and energy to chase all my dependencies.  Perhaps once
my server (Ubuntu) moves to 2.6 I'll update my Mac at the same time.

>From now on I am storing my install packages somewhere accessible
instead of deleting them once I'm done with them.  I wish I could
generate a manifest of installed packages to make upgrading easier.

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


Re: So you think PythonCard is old? Here's new wine in an old bottle.

2008-04-28 Thread John Henry
On Apr 27, 12:23 pm, Fred Pacquier <[EMAIL PROTECTED]> wrote:
>
> Do keep us posted !
>
> TIA,
> fp

Check it out now.

Only one to be added is the Multicolumn List (table), and then menus.
The other widgets (Togglebutton, BitmapCanvas, Gauge, Notebook,
CodeEditor) will not be implemented initially.

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


Simple unicode-safe version of str(exception)?

2008-04-28 Thread Russell E. Owen
I have code like this:
except Exception, e:
   self.setState(self.Failed, str(e))
which fails if the exception contains a unicode argument.

I did, of course, try unicode(e) but that fails.

The following works, but seems rather messy:

except Exception, e:
errStr = ",".join([unicode(s) for s in f.args])
self.setState(self.Failed, errStr)

Is there a simpler solution that works in Python 2.3-2.5?

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


Newbie Help - Alarms

2008-04-28 Thread Paul Jefferson
Hi,
I'm new to this having previously done some programming in Game Maker.
In Game Maker there was a function (Alarm) that lets you run a block of code
run every x seconds without freezing up the whole program waiting for it.
Is there an equavalant for this built in Python beacuse I can't find it?
Thanks for any help,
Paul
--
http://mail.python.org/mailman/listinfo/python-list

Re: So you think PythonCard is old? Here's new wine in an old bottle.

2008-04-28 Thread Fred Pacquier
John Henry <[EMAIL PROTECTED]> said :

> The performance of Qooxdoo is quite amazing - for a Javascript based
> web application.  Don't know about cell-phones though.  You can try
> their showcase web site I cited earlier.

Just for the record, Nokia Internet tablets (770, N800, N810) are the only 
things made by Nokia that are not cell-phones... They're ARM machines with 
a 800x480 4" screen, Wifi, Bluetooth, and Linux. And Python, pyGTK and 
Pygame. Probably pyQt next as they just bought Trolltech. But no wxPython.

I was not speaking of running just the client part in the device's browser, 
either - but the full Monty (haha) with the web server and the application 
engine, python, middleware and all. I'm doing it right now using a full-
blown framework (web2py), so it's not unreasonable. There's no Ajax in 
there though, so I'm wondering what kind of impact those tools you mention 
would have, server side.
 
> Yes, who would have throught we don't have to give up on Pythoncard?
 
Proof of superior vision, architecture and design, all that time ago...
--
http://mail.python.org/mailman/listinfo/python-list


Re: list.reverse()

2008-04-28 Thread Arnaud Delobelle
Mark Bryan Yu <[EMAIL PROTECTED]> writes:

> This set of codes works:
>
 x = range(5)
 x.reverse()
 x
> [4, 3, 2, 1, 0]
>
> But this doesn't:
>
 x = range(5).reverse()
 print x
> None
>
> Please explain this behavior. range(5) returns a list from 0 to 4 and
> reverse just reverses the items on the list that is returned by
> range(5). Why is x None (null)?

have you tried typing help(list.reverse) at the interactive prompt?

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


Re: How to unget a line when reading from a file/stream iterator/generator?

2008-04-28 Thread Arnaud Delobelle
[EMAIL PROTECTED] writes:

> Is there an elegant way to unget a line when reading from a file/stream
> iterator/generator?
>
> By "unget" I mean a way to push back a line into the source stream and
> backtrack the iterator/generator one step?
>
> The only alternative I can see is to put my line reading in a while-True
> loop (vs. a for-loop) that manually calls my file/stream
> iterator/generator's .next() method while manually handling the
> StopIteration exception. Doesn't sound too elegant.
>
> Is there a Pythonic design pattern/best practice that I can apply here?

It seems to me that the answer depends on what you do with your
unget'ed line (i.e. there is no included general purpose 'unget'
replacement).  If you provided some (pseudo-)code, someone might be
able to find an elegant way to perform the task without the need to
push back an element into an iterator.

As a last resort, you could always wrap your iterator into a some
'Backtrackable' class.

class Backtrackable(object):
  def __init__(self, iterator):
  self.iterator = iter(iterator)
  self._back = False
  self._last = None
  def __iter__(self):
  return self
  def next(self):
  if self._back:
  next = self._last
  else:
  self._last = next = self.iterator.next()
  self._back = False
  return next
  def back(self):
  if self._back:
  raise('Cannot backtrack twice')
  self._back = True

>>> b = Backtrackable([1,2,3])
>>> b.next()
1
>>> b.next()
2
>>> b.back()
>>> b.next()
2
>>> b.next()
3
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cookie Confusion - How to Set a Cookie

2008-04-28 Thread Aaron Watters
On Apr 28, 9:42 am, [EMAIL PROTECTED] wrote:
> I see the cookie in my HTTP header
> but do not get anything in the cookie text file.  I'm working on
> linux.
>
> print "Content-type: text/html"
> cookie = Cookie.SimpleCookie()
> cookie['Test'] = 'abc'
> print cookie
> print
>
> Are there rules about where in the header the set cookie line should
> be?

Hi Christian.  I think the cookie can go anywhere in
the header, but I usually put it before the content-type.
If you want to store the cookie to a file,
or even better, to a database of some sort, you have to
do it yourself, the Cookie module doesn't do it for you,
I hope.

  # store cookie to /tmp/cookie.txt
  file("/tmp/cookie.txt","w").write(str(cookie))

For parsing cookies, I stole and modified this from
the Django source (for use in a cgi script):

===
from Cookie import SimpleCookie
import os

# stolen and modified from Django
def parse_cookie(cookie=None, environ=None):
if cookie is None:
if environ is None:
environ = os.environ
cookie = environ.get('HTTP_COOKIE', '')
if cookie == '':
return {}
c = SimpleCookie()
c.load(cookie)
cookiedict = {}
for key in c.keys():
cookiedict[key] = c.get(key).value
return cookiedict

===
All the best.  -- Aaron Watters

===
http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=monster
--
http://mail.python.org/mailman/listinfo/python-list


Re: list.reverse()

2008-04-28 Thread Gary Herron

Mark Bryan Yu wrote:

This set of codes works:

  

x = range(5)
x.reverse()
x


[4, 3, 2, 1, 0]

But this doesn't:

  

x = range(5).reverse()
print x


None

Please explain this behavior. range(5) returns a list from 0 to 4 and
reverse just reverses the items on the list that is returned by
range(5). Why is x None (null)?
--
http://mail.python.org/mailman/listinfo/python-list
  
Because you are misusing reverse.  It is an operation on a list that 
reverses the list in place.   It is meant to be used only in the 
situation where you already have the list and want to reorder it:


x =  list ...
x.reverse() # reorders, but returns nothing
... now use x ...


You might look at the builtin reversed(list): 
http://www.python.org/doc/faq/programming/#how-do-i-iterate-over-a-sequence-in-reverse-order


Gary Herron



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


Re: Tremendous slowdown due to garbage collection

2008-04-28 Thread John Nagle

Dieter Maurer wrote:

Christian Heimes <[EMAIL PROTECTED]> writes on Sat, 12 Apr 2008 18:47:32 +0200:

[EMAIL PROTECTED] schrieb:

which made me suggest to use these as defaults, but then



We observed similar very bad behaviour -- in a Web application server.
Apparently, the standard behaviour is far from optimal when the
system contains a large number of objects and occationally, large
numbers of objects are created in a short time.
We have seen such behaviour during parsing of larger XML documents, for
example (in our Web application).


   Our solution to that was to modify BeautifulSoup to use weak pointers.
All the pointers towards the root and towards previous parts of the
document are "weak".  As a result, reference counting alone is sufficient
to manage the tree.  We still keep GC enabled, but it doesn't find much
to collect.

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


Python 2.6, building SDL for Pygame

2008-04-28 Thread L. Lindstrom
I build the Pygame releases for Windows. Pygame wraps the Simple 
Directmedia Layer (SDL) C library. I am doing preliminary research into 
porting Pygame to Python 2.6. For Pythons 2.4 and 2.5 the Pygame 
extension modules are built with MinGW. They link cleanly against 
msvcr71.dll. A custom SDL, also linked to msvcr71.dll, is used. It is 
built with Msys/MinGW using the configure/make tool chain.


For Python 2.6 I expect Visual Studio 2008 will be required to build the 
Pygame extension modules. However, I am at a loss as to how to build SDL 
so it also links against msvcr90.dll. Windows' side=by-side assemblies 
get in the way. The Msys build process fails. The first test program 
configure compiles and runs refuses to load msvcr90.dll. It raises an 
R6034 error. How important is it that a C library uses the same C 
run-time as the Python extension module that wraps it? If it is not 
critical then the SDL library will just use msvcrt.dll for Pygame and 
Python 2.6.



--
Lenard Lindstrom
"[EMAIL PROTECTED]" % ('len-l', 'telus', 'net')
--
http://mail.python.org/mailman/listinfo/python-list


cytpes **int

2008-04-28 Thread VernM
I am using ctypes to wrap a set of functions in a DLL. It has been
going very well, and I am very impressed with ctypes. I want to call a
c function with a signature of: void func(int **cube), where the array
if ints in cube is modified by func. I want to setup cube with int
values, and access them after the call to func. I unerstand how to
setup the ctypes array, but how do I pass **cube to the function, and
how do I access the results?
--
http://mail.python.org/mailman/listinfo/python-list


list.reverse()

2008-04-28 Thread Mark Bryan Yu
This set of codes works:

>>> x = range(5)
>>> x.reverse()
>>> x
[4, 3, 2, 1, 0]

But this doesn't:

>>> x = range(5).reverse()
>>> print x
None

Please explain this behavior. range(5) returns a list from 0 to 4 and
reverse just reverses the items on the list that is returned by
range(5). Why is x None (null)?
--
http://mail.python.org/mailman/listinfo/python-list


How to unget a line when reading from a file/stream iterator/generator?

2008-04-28 Thread python
Is there an elegant way to unget a line when reading from a file/stream
iterator/generator?

By "unget" I mean a way to push back a line into the source stream and
backtrack the iterator/generator one step?

The only alternative I can see is to put my line reading in a while-True
loop (vs. a for-loop) that manually calls my file/stream
iterator/generator's .next() method while manually handling the
StopIteration exception. Doesn't sound too elegant.

Is there a Pythonic design pattern/best practice that I can apply here?

Thank you,
Malcolm
--
http://mail.python.org/mailman/listinfo/python-list


xcode able to run script?

2008-04-28 Thread Alex Pavluck
Does anyone know if it is possible to test your scripts from within
the xcode editor?  I am currently using Uilipad on windows and there
is a sub window that lets you view your output when you launch the
script from within the ide.  hopefully this makes sense.

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


Automating IE 6.0

2008-04-28 Thread Michael Harris
I tried to use the sample code to print a webpage via ie and I get the
following error:

 

Traceback (most recent call last):

  File
"C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py"
, line 310, in RunScript

exec codeObject in __main__.__dict__

  File "C:\ie.py", line 14, in 

ie.ExecWB(win32com.client.constants.OLECMDID_PRINT,
win32com.client.constants.OLECMDEXECOPT_DONTPROMPTUSER)

NameError: name 'win32com' is not defined

 

I have the win32com module installed and I clicked on makepy.py and
selected Microsoft Internet Controls (1.1).  The code was:
 
from win32com.client import Dispatch
from time import sleep
ie = Dispatch("InternetExplorer.Application")
ie.Visible = 1
ie.Navigate("http://www.cnn.com";  )
if ie.Busy:
 sleep(2)
# print the current IE document without prompting the user for the
printerdialog
ie.ExecWB(win32com.client.constants.OLECMDID_PRINT,win32com.client.const
ants
.OLECMDEXECOPT_DONTPROMPTUSER)
 

Why am I getting this error?

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

descriptor & docstring

2008-04-28 Thread cyril giraudon
Hello,

I try to use python descriptors to define attributes with default
value (the code is reported below).
But apparently, it breaks the docstring mechanism.

help(Basis) shows the right help but help(Rectangle) shows only two
lines :
"
Help on class Rectangle in module basis2:

Rectangle = 
"
If the Rectangle.length attribute is removed, the help is OK.

Secondly, the __doc__ attribute of a PhysicalValue instance doesn't
seem to be read.

I don't understand.

Any idea ?

Thanks a lot

Cyril.



# A descriptor class with default value handling
class PhysicalValue(object):
  """
  A physical value descriptor
  """
  def __init__(self, default_value):
self.default_value = default_value
self.__doc__ = "Hello from Physical Value"

  def __get__(self, obj, type=None):
if obj.__dict__.has_key(self.key):
  return getattr(obj, self.key)
else:
  return self.default_value

  def __set__(self, obj, value):
if value is DefaultValue:
  setattr(obj, self.key, self.default_value)
else:
  setattr(obj, self.key, value)

# A meta class which adds instance attributes
# If hasattr(cls, "attr") then add "_attr" attribute.
class MyMetaClass(type):
  def __init__(cls, name, bases, dct):
super(MyMetaClass, cls).__init__(name, bases, dct)
print "Add property to ", name
def init(self):
  pvl = [item for item in cls.__dict__.items()
 if isinstance(item[1], PhysicalValue)]
  for pv in pvl:
print "Add _%s property to %s" % (pv[0], name)
cls.__dict__[pv[0]].key = "_" + pv[0]
setattr(self, "_" + pv[0], getattr(self, pv[0]))
cls.__init__ = init

# A basis class
class Basis(object):
  """
  Tempest basis class
  """
  __metaclass__ = MyMetaClass

# A concrete class
class Rectangle(Basis):
  """
  A beautiful Rectangle
  """
  length = PhysicalValue(12.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expression - Matching Multiples of 3 Characters exactly.

2008-04-28 Thread blaine
On Apr 28, 6:30 am, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> blaine <[EMAIL PROTECTED]> wrote:
> >  I'm trying to write a string matching algorithm for genomic
> >  sequences.  I'm pulling out Genes from a large genomic pattern, with
> >  certain start and stop codons on either side.  This is simple
> >  enough... for example:
>
> >  start = AUG stop=AGG
> >  BBAUGWWAGGBB
>
> >  So I obviously want to pull out AUGWWAGG (and all other matches).
> >  This works great with my current regular expression.
>
> >  The problem, however, is that codons come in sets of 3 bases.  So
> >  there are actually three different 'frames' I could be using.  For
> >  example:
> >  ABCDEFGHIJ
> >  I could have ABC DEF GHI or BCD EFG HIJ or CDE FGH IJx etc.
>
> >  So finally, my question.  How can I represent this in a regular
> >  expression? :)  This is what I'd like to do:
> >  (Find all groups of any three characters) (Find a start codon) (find
> >  any other codons) (Find an end codon)
>
> >  Is this possible? It seems that I'd want to do something like this: (\w
> >  \w\w)+(AUG)(\s)(AGG)(\s)* - where \w\w\w matches EXACTLY all sets of
> >  three non-whitespace characters, followed by AUG \s AGG, and then
> >  anything else.
>
> I'm not sure what the \s are doing in there - there doesn't appear to
> be any whitespace in your examples.
>
> >  I hope I am making sense.  Obviously, however, this will make sure
> >  that ANY set of three characters exist before a start codon.  Is
> >  there a way to match exactly, to say something like 'Find all sets
> >  of three, then AUG and AGG, etc.'.
>
> I think you want
>
> ^(\w\w\w)*(AUG)((\w\w\w)*?)(AGG)
>
> which will match up 0 or more triples, match AUG match 0 or more triples
> then AGG.  The ? makes it a minimum match otherwise you'll match more
> than you expect if there are two AUG...AGG sequences in a given genome.
>
>   >>> import re
>   >>> m=re.compile(r"^(\w\w\w)*(AUG)((\w\w\w)*?)(AGG)")
>   >>> m.search("BBAUGWWAGGBB").groups()
>   ('BBB', 'AUG', 'WW', 'WWW', 'AGG')
>   >>> m.search("BBBQBBBAUGWWAGGBB")
>   >>> m.search("BBBQQBBBAUGWWAGGBB")
>   >>> m.search("BBBQQBBQBAUGWWAGGBB")
>   <_sre.SRE_Match object at 0xb7de33e0>
>   >>> m.search("BBBQQBBQBAUGWWAGGBB").groups()
>   ('BQB', 'AUG', 'WW', 'WWW', 'AGG')
>   >>> m.search("BBBQQBBQBAUGWQWAGGBB")
>   >>> m.search("BBBQQBBQBAUGQWWAGGBB")
>   >>> m.search("BBBQQBBQBAUGWWQWWQWWAGGBB")
>   >>> m.search("BBBQQBBQBAUGWWQWAWQWWAGGBB")
>   <_sre.SRE_Match object at 0xb7de33e0>
>   >>> m.search("BBBQQBBQBAUGWWQWAWQWWAGGBB").groups()
>   ('BQB', 'AUG', 'WWQWAWQWW', 'QWW', 'AGG')
>   >>>
>
> >  This way, I could scan for genes, remove the first letter, scan for
> >  more genes, remove the first letter again, and scan for more genes.
> >  This would hypothetically yield different genes, since the frame
> >  would be shifted.
>
> Of you could just unconstrain the first match and it will do them all
> at once :-
>
> (AUG)((\w\w\w)*?)(AGG)
>
> You could run this with re.findall, but beware that this will only
> return non-overlapping matches which may not be what you want.
>
> I'm not sure re's are the best tool for the job, but they should give
> you a quick idea of what the answers might be.
>
> --
> Nick Craig-Wood <[EMAIL PROTECTED]> --http://www.craig-wood.com/nick

Thank you! Your suggestion was overly helpful.

Also thank you for the package suggestions.  BioPython is on my plate
to check out, but I needed a kind of quick fix for this one.  The
documentation for biopython seems pretty thick - I'm not a biologist
so I'm not even sure what kind of packages I'm even looking for.

thanks!
Blaine
--
http://mail.python.org/mailman/listinfo/python-list


Re: Remove multiple inheritance in Python 3000

2008-04-28 Thread Dieter Maurer
Nick Stinemates <[EMAIL PROTECTED]> writes on Thu, 24 Apr 2008 08:26:57 -0700:
> On Tue, Apr 22, 2008 at 04:07:01AM -0700, GD wrote:
> > Please remove ability to multiple inheritance in Python 3000.

I hope your request will not be followed.

> > Multiple inheritance is bad for design, rarely used and contains many
> > problems for usual users.

Multiple inheritance is very productive by supporting mixin classes.
I use it extensively and get clean code quickly developped.

I hate Java because it does not support multiple inheritance
and forces me to write lots of tedious error prone delegations
to work around this limitation.

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


Re: Given a string - execute a function by the same name

2008-04-28 Thread Arnaud Delobelle
[EMAIL PROTECTED] writes:

> I'm parsing a simple file and given a line's keyword, would like to call
> the equivalently named function.
>
> There are 3 ways I can think to do this (other than a long if/elif
> construct):
>
> 1. eval() 
>
> 2. Convert my functions to methods and use getattr( myClass, "method" )
>
> 3. Place all my functions in dictionary and lookup the function to be
> called

4. Put all my functions in a module and use getattr(module, 'function')

-- 
Arnaud



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


Re: Given a string - execute a function by the same name

2008-04-28 Thread Gary Herron

[EMAIL PROTECTED] wrote:

I'm parsing a simple file and given a line's keyword, would like to call
the equivalently named function.

There are 3 ways I can think to do this (other than a long if/elif
construct):

1. eval() 


2. Convert my functions to methods and use getattr( myClass, "method" )

3. Place all my functions in dictionary and lookup the function to be
called

Any suggestions on the "best" way to do this?

Thank you,
Malcolm
--
http://mail.python.org/mailman/listinfo/python-list
  


You are on the right track with (2), but you need not do any conversion. 
 All objects that have attributes (and a function is an attribute) can 
be looked up with getattr.


For instance, from a module (function getcwd from modules os):

>>> import os
>>> getattr(os,'getcwd')

>>> getattr(os,'getcwd')()
'/home/gherron'


You can use getattr with objects, classes, modules, and probably more.

Gary Herron



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


bisect intersection

2008-04-28 Thread Robert Bossy

Hi,

I stumbled into a sorted list intersection algorithm by Baeza-Yates 
which I found quite elegant. For the lucky enough to have a springerlink 
access, here's the citation:

http://dblp.uni-trier.de/rec/bibtex/conf/cpm/Baeza-Yates04

I implemented this algorithm in python and I thought I could share it. 
I've done some tests and, of course, it can't compete against dict/set 
intersection, but it will perform pretty well. Computing union and 
differences are left as an exercise...


from bisect import bisect_left

def bisect_intersect(L1, L2):
   inter = []
   def rec(lo1, hi1, lo2, hi2):
   if hi1 <= lo1: return
   if hi2 <= lo2: return
   mid1 = (lo1 + hi1) // 2
   x1 = L1[mid1]
   mid2 = bisect_left(L2, x1, lo=lo2, hi=hi2)
   rec(lo1, mid1, lo2, mid2)
   if mid2 < hi2 and x1 == L2[mid2]:
   inter.append(x1)
   rec(mid1+1, hi1, mid2+1, hi2)
   else:
   rec(mid1+1, hi1, mid2, hi2)
   rec(0, len(L1), 0, len(L2))
   inter.sort()
   return inter


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


Re: Given a string - execute a function by the same name

2008-04-28 Thread Matimus
On Apr 28, 9:33 am, [EMAIL PROTECTED] wrote:
> I'm parsing a simple file and given a line's keyword, would like to call
> the equivalently named function.
>
> There are 3 ways I can think to do this (other than a long if/elif
> construct):
>
> 1. eval()
>
> 2. Convert my functions to methods and use getattr( myClass, "method" )
>
> 3. Place all my functions in dictionary and lookup the function to be
> called
>
> Any suggestions on the "best" way to do this?
>
> Thank you,
> Malcolm

You can always import yourself and use getattr on that module.

in file "mytest.py":

def foo():
print "foo called"

def call_by_name(name, *args, **kwargs):
import mytest

f = getattr(mytest, "foo")
f(*args,  **kwargs)

if __name__ == "__main__":
call_by_name('foo')



Alternatively you can import __main__ if you are always going to be
running directly from that file.

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


Re: Given a string - execute a function by the same name

2008-04-28 Thread marek . rocki
One solution may be to use globals():

>>> globals()['foo']()

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


Re: Tremendous slowdown due to garbage collection

2008-04-28 Thread Dieter Maurer
"Martin v. Löwis" wrote at 2008-4-27 19:33 +0200:
>> Martin said it but nevertheless it might not be true.
>> 
>> We observed similar very bad behaviour -- in a Web application server.
>> Apparently, the standard behaviour is far from optimal when the
>> system contains a large number of objects and occationally, large
>> numbers of objects are created in a short time.
>> We have seen such behaviour during parsing of larger XML documents, for
>> example (in our Web application).
>
>I don't want to claim that the *algorithm* works for all typically
>applications well. I just claim that the *parameters* of it are fine.
>The OP originally proposed to change the parameters, making garbage
>collection run less frequently. This would a) have bad consequences
>in terms of memory consumption on programs that do have allocation
>spikes, and b) have no effect on the asymptotic complexity of the
>algorithm in the case discussed.

In our case, it helped to change the parameters:

  As usual in Python, in our case cyclic garbage is very rare.
  On the other hand, we have large caches with lots of objects,
  i.e. a large number of long living objects.
  Each generation 2 garbage collection visits the complete
  object set. Thus, if it is called too often, matters can
  deteriorate drastically.

  In our case, the main problem has not been the runtime
  but that during GC the GIL is hold (understandably).
  This meant that we had every few minutes a scheduling
  distortion in the order of 10 to 20 s (the time of
  our generation 2 gc).

We changed the parameters to let generation 2 GC happen
at about 1/1000 of its former frequency.


I do not argue that Python's default GC parameters must change -- only
that applications with lots of objects may want to consider a
reconfiguration.



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


Re: Given a string - execute a function by the same name

2008-04-28 Thread Robert Bossy

[EMAIL PROTECTED] wrote:

I'm parsing a simple file and given a line's keyword, would like to call
the equivalently named function.

There are 3 ways I can think to do this (other than a long if/elif
construct):

1. eval() 


2. Convert my functions to methods and use getattr( myClass, "method" )

3. Place all my functions in dictionary and lookup the function to be
called

Any suggestions on the "best" way to do this?
(3) is the securest way since the input file cannot induce unexpected 
behaviour.
With this respect (1) is a folly and (2) is a good compromise since you 
still can write a condition before passing "method" to getattr(). Btw, 
if you look into the guts, you'll realize that (2) is nearly the same as 
(3)...


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


Given a string - execute a function by the same name

2008-04-28 Thread python
I'm parsing a simple file and given a line's keyword, would like to call
the equivalently named function.

There are 3 ways I can think to do this (other than a long if/elif
construct):

1. eval() 

2. Convert my functions to methods and use getattr( myClass, "method" )

3. Place all my functions in dictionary and lookup the function to be
called

Any suggestions on the "best" way to do this?

Thank you,
Malcolm
--
http://mail.python.org/mailman/listinfo/python-list


Re: class or class-instance ?

2008-04-28 Thread Stef Mientki




There is a

isclass

in the module inspect.

Diez


thanks Diez,
that's exactly what I was looking for.

cheers,
Stef

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


Re: Receive data from socket stream

2008-04-28 Thread Jean-Paul Calderone

On Mon, 28 Apr 2008 07:26:13 -0700 (PDT), [EMAIL PROTECTED] wrote:

[snip]


BTW, has anybody used sockets as file-like objects
(client.makefile())? Is it more secure? More efficient?


It's not more (or less) secure.  In certain cases, it's significantly less
efficient.  It's for simplicity of programming, not much else.

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


Re: Regular Expression - Matching Multiples of 3 Characters exactly.

2008-04-28 Thread Helmut Jarausch

blaine wrote:

Hey everyone,
  For the regular expression gurus...

I'm trying to write a string matching algorithm for genomic
sequences.  I'm pulling out Genes from a large genomic pattern, with
certain start and stop codons on either side.  This is simple
enough... for example:

start = AUG stop=AGG
BBAUGWWAGGBB

So I obviously want to pull out AUGWWAGG (and all other matches).
This works great with my current regular expression.

The problem, however, is that codons come in sets of 3 bases.  So
there are actually three different 'frames' I could be using.  For
example:
ABCDEFGHIJ
I could have ABC DEF GHI or BCD EFG HIJ or CDE FGH IJx etc.

So finally, my question.  How can I represent this in a regular
expression? :)  This is what I'd like to do:
(Find all groups of any three characters) (Find a start codon) (find
any other codons) (Find an end codon)

Is this possible? It seems that I'd want to do something like this: (\w
\w\w)+(AUG)(\s)(AGG)(\s)* - where \w\w\w matches EXACTLY all sets of
three non-whitespace characters, followed by AUG \s AGG, and then
anything else.  I hope I am making sense.  Obviously, however, this
will make sure that ANY set of three characters exist before a start
codon.  Is there a way to match exactly, to say something like 'Find
all sets of three, then AUG and AGG, etc.'.  This way, I could scan
for genes, remove the first letter, scan for more genes, remove the
first letter again, and scan for more genes.  This would
hypothetically yield different genes, since the frame would be
shifted.



As an alternative - if you do need speed - have a look at

http://www.egenix.com/products/python/mxBase/mxTextTools/


Helmut.
--
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
--
http://mail.python.org/mailman/listinfo/python-list


Wing IDE 3.1beta3 released

2008-04-28 Thread Wingware

Hi,

Wingware has released version 3.1 beta3 of Wing IDE, an integrated development
environment for the Python programming language. It is available from:

http://wingware.com/wingide/beta

This release includes the following changes:

* How-To and improvements for using Wing IDE with Google App Engine
* Scan for sys.path changes in main debug file (e.g. for Zope buildouts)
* Preference to auto-strip trailing white space on save
* Many vi mode improvements
* Testing tool enhancements, including better support for test names
  that are not method names
* Sped up stepping in the debugger
* Set encoding for stdin/out/err in debug processes for better handling
  of non-ascii input and output
* Fixed problems with debugging stackless tasklets
* Python Shell allows spawned threads to run, rather than stopping all threads
* Improved support for debugging code invoked by execfile()
* Better autocompletion support for an x defined by 'import x.y.z'
* More bug fixes, including also all those found in Wing 3.0.5

Please see the change log for a detailed list of changes:

http://wingware.com/pub/wingide/prerelease/3.1.0-b3/CHANGELOG.txt

Version 3.1 introduces a number of new features and includes bug fixes not
found in the 3.0 series, as follows:

* Files within .zip or .egg files can be displayed in the editor
* Support for pkg_resources based namespace packages
* Support for doctest and nose unit test frameworks (**)
* Updated code analysis support for Python 2.5 constructs
* Improved support for tasklets in Stackless Python
* In-line argument entry of code templates/snippets (tab and back tab to
  traverse fields; arrow keys to change template indent, Esc to exit data
  entry mode) (**)
* Include templates by name in autocompleter (**)
* Simple word list driven auto-completion when working in non-Python files (*)
* Open from Project for quick selection of files from the Project by
  typing a fragment (*)
* Find Symbol for quick Goto-Definition for symbols in the current Python
  file by typing a fragment (*)
* Show gi_running and gi_frame in Stack Data for generators
* Sort menus and lists using more natural sorting so x2.py comes before x10.py
* Preference to strip trailing white space on save
* Scan for straightforward sys.path changes in main debug file
* How-To and improvements for using Wing IDE with Google App Engine
* Many bug fixes not in Wing 3.0.x

(*)'d items are available in Wing IDE Personal or Professional only.
(**)'d items are available in Wing IDE Professional only.

*About Wing IDE*

Wing IDE is an integrated development environment for the Python programming
language.  It provides powerful debugging, editing, code intelligence,
testing, and search capabilities that reduce development and debugging
time, cut down on coding errors, and make it easier to understand
and navigate Python code.

Wing IDE is available in three product levels:  Wing IDE Professional is
the full-featured Python IDE, Wing IDE Personal offers a reduced feature
set at a low price, and Wing IDE 101 is a free scaled back version designed
for teaching entry level programming courses with Python.

System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or
Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit).

*Purchasing & Upgrading*

Wing IDE Professional & Wing IDE Personal are commercial software and require
a license to run. Wing 3.1 is a free upgrade for all Wing IDE 3.0 users. Any
2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the
normal price to upgrade.

To upgrade a 2.x license or purchase a new 3.x license:

Upgradehttps://wingware.com/store/upgrade
Purchase   https://wingware.com/store/purchase

--

The Wingware Team
Wingware | Python IDE
Advancing Software Development

www.wingware.com

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


Wing IDE 3.0.5 released

2008-04-28 Thread Wingware

Hi,

We're happy to announce version 3.0.5 of Wing IDE, an integrated development
environment for the Python programming language. It is available from:

http://wingware.com/downloads

Version 3.0.5 is a bug fix release that adds many vi mode improvements,
improves stability, and fixes other usability bugs.

See the change log at http://wingware.com/pub/wingide/3.0.5/CHANGELOG.txt
for details.

It is a free upgrade for all Wing 3.0 users.

*About Wing IDE*

Wing IDE is an integrated development environment for the Python programming
language.  It provides powerful debugging, editing, code intelligence,
testing, and search capabilities that reduce development and debugging
time, cut down on coding errors, and make it easier to understand
and navigate Python code.

New features added in Wing 3.0 include:

* Multi-threaded debugger
* Debug value tooltips in editor, debug probe, and interactive shell
* Autocompletion and call tips in debug probe and interactive shell
* Automatically updating project directories
* Testing tool, currently supporting unittest derived tests (*)
* OS Commands tool for executing and interacting with external commands (*)
* Rewritten indentation analysis and conversion (*)
* Introduction of Wing IDE 101, a free edition for beginning programmers
* Available as a .deb package for Debian and Ubuntu
* Support for Stackless Python
* Support for 64 bit Python on Windows and Linux

(*)'d items are available in Wing IDE Professional only.

System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or
Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit).

*Purchasing and Upgrading*

Wing IDE Professional & Wing IDE Personal are commercial software and require
a license  to run.  To upgrade a 2.x license or purchase a new 3.x license:

Upgradehttps://wingware.com/store/upgrade
Purchase   https://wingware.com/store/purchase

Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost
1/2 the normal price to upgrade.

--

The Wingware Team
Wingware | Python IDE
Advancing Software Development

www.wingware.com

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


Re: Question regarding Queue object

2008-04-28 Thread [EMAIL PROTECTED]
I've never used it myself but you may find candygram interesting;
http://candygram.sourceforge.net, which AFAIK implements Erlang-style
message queues in Python.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Retrieving int from hex in a file.

2008-04-28 Thread Grant Edwards
On 2008-04-28, Filipe Teixeira <[EMAIL PROTECTED]> wrote:
> Hi.
>
> I have to open a binary file from an old computer and recover the
> information stored (or at least try to). I use:
>
> f=open('file.bin','rb')
> a=f.read()
> f.close()
>
> a in now a string full of hex representations in the form:
>
> a[6]='\x14'
> a[7]='\x20'

a is now a string of binary data.  It doesn't contain a "hex
representation" of anything.  Hex is a way of printing stuff on
paper or on a screen.  Python doesn't store anything in hex.

> I would like to convert these hex representations to int,

That's your mistake: you don't have hex data. Nothing is being
stored in hex in your example.

> but this (the most obvious way) doesn't seem to be working
>
 q=a[6]
 q
> '\x14'
 int(q,16)

That converts a hex string into an integer, you've not got a
hex string.  You have a string containing binary data.

"4A4B4C" is a hex string.  It's 6 bytes long and contains the
ASCII characters '4' 'A' '4' 'B' '4' 'C'.

"\x4a\x4b\4c" is just a three-byte long chunk of binary data.
It was _typed_ in hex, but it's stored in binary not in hex.
It's identical to "JKL".

> Traceback (most recent call last):
>   File "", line 1, in ?
> ValueError: invalid literal for int():

>
> How can I do this?

You can use the struct module, or you can do it explicitly like
this:

>>> a = 'abcdef\x12\x34qwer'
>>> n = (ord(a[6])<<8) | ord(a[7])
>>> n
4660
>>> hex(n)
'0x1234'
>>> 

-- 
Grant Edwards   grante Yow! When you get your
  at   PH.D. will you get able to
   visi.comwork at BURGER KING?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Receive data from socket stream

2008-04-28 Thread Hrvoje Niksic
Nick Craig-Wood <[EMAIL PROTECTED]> writes:

>>  Note that appending to a string is almost never a good idea, since it
>>  can result in quadratic allocation.
>
> My aim was clear exposition rather than the ultimate performance!

That would normally be fine.  My post wasn't supposed to pick
performance nits, but to point out potentially quadratic behavior.

> Anyway str += was optimised in python 2.4 or 2.5 (forget which) wasn't
> it?

That optimization works only in certain cases, when working with
uninterned strings with a reference count of 1, and then only when the
strings are in stored local variables, rather than in global vars or
in slots.  And then, it only works in CPython, not in other
implementations.  The optimization works by "cheating" -- breaking the
immutable string abstraction in the specific cases in which it is
provably safe to do so.
http://utcc.utoronto.ca/~cks/space/blog/python/ExaminingStringConcatOpt
examines it in some detail.

Guido was reluctant to accept the patch that implements the
optimization because he thought it would "change the way people write
code", a sentiment expressed in
http://mail.python.org/pipermail/python-dev/2004-August/046702.html
This discussion shows that he was quite right in retrospect.  (I'm not
saying that the optimization is a bad thing, just that it is changing
the "recommended" way of writing Python in a way that other
implementations cannot follow.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: API's and hardware communication. Newbie

2008-04-28 Thread Grant Edwards
On 2008-04-26, Grayham <[EMAIL PROTECTED]> wrote:
> Hi all
>
> I am new to this group so 'Hello All'
>
> I have a PC which is running linux and in it have installed a digital
> satellite card. I would like to write some software to access the card,
> tune it and bring back video. Basically a home brew DVB-s application.
>
> Being a non/new programmer (apart from some basic too many years ago) I
> decided to teach my self Python as from what i have read it's an easy and
> powerfull language to learn. I have been at it a few weeks and am getting
> on OK and finding it reasonably OK to pick up.
>
> The problem is i can find little to no information on programming for DVB
> cards or on how to access the Linux tv API in Python but I can find lots of
> information in C. This is making me think should i bother with Python and
> just learn C even though this will probably take a lot longer.

There are a couple of ways you can handle the problem:

 * You can use the ctypes modules to make C library calls. At
   first it seems a bit complicated, but it's really quite easy
   to use.  http://docs.python.org/lib/module-ctypes.html

 * You can write a C wrapper for the library so that it can be
   accessed as a Python module.  That's going to require a bit
   more C knowlege than the ctypes approach , but it's not as
   difficult as it looks.  http://www.python.org/doc/ext/intro.html

> Can some one help me or point me at a resource somewhere or
> would it be best to just learn C instead.  
>
> I am aware this is a complicated little project for someone
> just starting out but it will be a multifaceted program with
> loads of interesting classes, functions and loops and i don't
> have to start with the really difficult stuff first. I just
> want to know if it's possible under python to access the DVB
> card and if so how?


Freevo is a DVR system written in Python, so that might be a
good place to look: http://doc.freevo.org/

-- 
Grant Edwards   grante Yow! I guess you guys got
  at   BIG MUSCLES from doing too
   visi.commuch STUDYING!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Receive data from socket stream

2008-04-28 Thread s0suk3
On Apr 28, 4:30 am, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> >  I wanted to ask for standard ways to receive data from a socket stream
> >  (with socket.socket.recv()). It's simple when you know the amount of
> >  data that you're going to receive, or when you'll receive data until
> >  the remote peer closes the connection. But I'm not sure which is the
> >  best way to receive a message with undetermined length from a stream
> >  in a connection that you expect to remain open. Until now, I've been
> >  doing this little trick:
>
> >  data = client.recv(256)
> >  new = data
> >  while len(new) == 256:
> >  new = client.recv(256)
> >  data += new
>
> >  That works well in most cases. But it's obviously error-prone. What if
> >  the client sent *exactly* two hundred and fifty six bytes? It would
> >  keep waiting for data inside the loop. Is there really a better and
> >  standard way, or is this as best as it gets?
>
> What you are missing is that if the recv ever returns no bytes at all
> then the other end has closed the connection.  So something like this
> is the correct thing to write :-
>
>   data = ""
>   while True:
>   new = client.recv(256)
>   if not new:
>   break
>   data += new
>
> From the man page for recv
>
>   RETURN VALUE
>
>These calls return the number of bytes received, or -1 if an
>error occurred.  The return value will be 0 when the peer has
>performed an orderly shutdown.
>
> In the -1 case python will raise a socket.error.
>
> --
> Nick Craig-Wood <[EMAIL PROTECTED]> --http://www.craig-wood.com/nick

But as I said in my first post, it's simple when you know the amount
of data that you're going to receive, or when you'll receive data
until the remote peer closes the connection. But what about receiving
a message with undetermined length in a connection that you don't want
to close? I already figured it out: in the case of an HTTP server/
client (which is what I'm doing), you have to look for an empty line
in the message, which signals the end of the message headers. As for
the body, you have to look at the Content-Length header, or, if the
message body contains the "chunked" transfer-coding, you have to
dynamically decode the encoding. There are other cases but those are
the most influent.

BTW, has anybody used sockets as file-like objects
(client.makefile())? Is it more secure? More efficient?

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


Chapter on real-time signal processing using numerical Python

2008-04-28 Thread Johannes Nix
Hi,

this might be of interest for people who are look for practical
information on
doing real-time signal processing, possibly using multiple CPUs, and
wonder
whether it's possible to use Python for audio-type worst case
latencies (around 25 ms).
I've done that in my PhD work, both with real-time requirements on
dual-CPU
64 bit platforms, and with very complex algorithms running on
multicomputers.

What I found is that numerical Python is a great environment for such
tasks. I've used it as well for massively parallel algorithms
(particle filters) for simulations of auditory scene analysis. What is
a very
special advantage is that if you get faster hardware, you can simply
copy your algorithms to a new system and compile - even if
it has a different CPU!

I've documented the approach in my PhD thesis, in Appendix A,
starting with some thoughts on developments in signal processing
in the last years. This piece is available online. Title and abstract
of that
chapter read as follows:

--
A real-time, script-based, multiprocessing Solution for experimental
Development of Signal Processing Algorithms

Evaluation of audio signal processing algorithms on real-time
platforms has
unique advantages. However, such environments also used to have the
disadvantage
of requiring expensive hardware, and tedious work to set them up,
while providing only a short useful life. This report proposes to
exploit advances
in hardware and software development by integrating real-time
processing
with script-based explorative development and use of multiprocessing
hardware.
The concept was implemented based on standard hardware and open
source software, and its realization and characteristics are presented
here. Applications
of the system for algorithm development and evaluation are described
briefly.

--


Here is the download link for several paper formats:

http://medi.uni-oldenburg.de/members/jnix/index.html#thesisdownload

Alternatively, for ISO A4 paper, use one of these two URLs:

http://medi.uni-oldenburg.de/download/paper/Nix,Johannes-PhDthesis-2005-ISO-A4-format.pdf
http://docserver.bis.uni-oldenburg.de/publikationen/dissertation/2006/nixloc05/nixloc05.html
(for that paper size, this are the PDF pages 155 - 163)



If you want to cite the chapter, e.g. when doing advocacy for
scientific
computing using SciPy, please do this as follows:

Nix, Johannes (2005), "A real-time, script-based, multiprocessing
Solution for experimental
Development of Signal Processing Algorithms", in: Localization and
Separation of Concurrent Talkers Based on Principles of Auditory Scene
Analysis and Multi-Dimensional Statistical Methods, Appendix A, Ph.D.
thesis, Universität Oldenburg, Germany.


Also, I am currently looking for interesting further work
opportunities
or contracts in the domain of scientific computing and statistical
estimation.
If you know some interesting position, don't hesistate to contact me.

Kind regards,

Johannes


--
Dr. Johannes Nix

Energy & Meteo Systems GmbH
Research & Development of windpower forecasts
Bremen, Germany
Phone: + 49 421 8963914



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


Re: ANN: pyspread 0.0.4

2008-04-28 Thread Martin Manns
On Sun, 27 Apr 2008 05:21:56 +0200
Martin Manns <[EMAIL PROTECTED]> wrote:

> The newest version pyspread 0.0.4 now runs on 
> + GTK
> + Windows
> + Mac (not tested myself but got positive reports)
> 
> New features in 0.0.4:
> + Column, line and table insertion and deletion
> + Themeable toolbar

I forgot to post the short description and the link:

pyspread is a spreadsheet that accepts a pure python expression in
each cell.

Highlights:
+ No non-python syntax add-ons
+ Access to python modules from cells
+ 3D grid
+ Numpy object array for representation of string entry into grid cell
+ Numpy object array for representation of eval function array
+ Cell access via slicing of numpy function array
+ X, Y, and Z yield current cell location for relative reference

Requires: Python >=2.4, Numpy 1.0.4, and wxPython 2.8.7.1.
License: GPL

Project page: http://pyspread.sourceforge.net

Best Regards

Martin

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


Re: Receive data from socket stream

2008-04-28 Thread Jean-Paul Calderone

On Mon, 28 Apr 2008 08:30:03 -0500, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:

Hrvoje Niksic <[EMAIL PROTECTED]> wrote:

 Nick Craig-Wood <[EMAIL PROTECTED]> writes:

> What you are missing is that if the recv ever returns no bytes at all
> then the other end has closed the connection.  So something like this
> is the correct thing to write :-
>
>   data = ""
>   while True:
>   new = client.recv(256)
>   if not new:
>   break
>   data += new

 This is a good case for the iter() function:

 buf = cStringIO.StringIO()
 for new in iter(partial(client.recv, 256), ''):
 buf.write(new)
 data = buf.getvalue()

 Note that appending to a string is almost never a good idea, since it
 can result in quadratic allocation.


My aim was clear exposition rather than the ultimate performance!

Anyway str += was optimised in python 2.4 or 2.5 (forget which) wasn't
it?  I'm not convinced it will be any worse performing than
cStringIO.StringIO.write() which effectively appends to a string in
exactly the same way.

This test agrees with me!

$ python -m timeit -s 's = ""' 'for i in xrange(10): s+="x"'
10 loops, best of 3: 23.8 msec per loop

$ python -m timeit -s 'from cStringIO import StringIO; s=StringIO()' 'for i in 
xrange(10): s.write("x")'
10 loops, best of 3: 56 msec per loop



It's a bit nice that using cStringIO doesn't rely on a very esoteric
optimization in the CPython eval loop, as well as on what references
happen to exist to what objects.  For example, one might want to use a
debugger without falling back to the quadratic behavior of repeated
string concatenation.  cStringIO wins out in this case.

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


Cookie Confusion - How to Set a Cookie

2008-04-28 Thread cbhoem
Hi -

I am trying my hand at python cookies.  I'm confused about a few
things though.  Do the python cookies get written to a cookies text
file?  I have simple code below -- I see the cookie in my HTTP header
but do not get anything in the cookie text file.  I'm working on
linux.

print "Content-type: text/html"
cookie = Cookie.SimpleCookie()
cookie['Test'] = 'abc'
print cookie
print

Are there rules about where in the header the set cookie line should
be?

Thanks in advance!
Christian
--
http://mail.python.org/mailman/listinfo/python-list


is there a threadsafe cookie library?

2008-04-28 Thread fritz
I'm working with a script written in python2.4 that has to handle multiple http connections but I'm having concurrency issues with cookielib. Does anyone know of a threadsafe library that handles cookies?
--
http://mail.python.org/mailman/listinfo/python-list

Re: Receive data from socket stream

2008-04-28 Thread Nick Craig-Wood
Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
>  Nick Craig-Wood <[EMAIL PROTECTED]> writes:
> 
> > What you are missing is that if the recv ever returns no bytes at all
> > then the other end has closed the connection.  So something like this
> > is the correct thing to write :-
> >
> >   data = ""
> >   while True:
> >   new = client.recv(256)
> >   if not new:
> >   break
> >   data += new
> 
>  This is a good case for the iter() function:
> 
>  buf = cStringIO.StringIO()
>  for new in iter(partial(client.recv, 256), ''):
>  buf.write(new)
>  data = buf.getvalue()
> 
>  Note that appending to a string is almost never a good idea, since it
>  can result in quadratic allocation.

My aim was clear exposition rather than the ultimate performance!

Anyway str += was optimised in python 2.4 or 2.5 (forget which) wasn't
it?  I'm not convinced it will be any worse performing than
cStringIO.StringIO.write() which effectively appends to a string in
exactly the same way.

This test agrees with me!

$ python -m timeit -s 's = ""' 'for i in xrange(10): s+="x"'
10 loops, best of 3: 23.8 msec per loop

$ python -m timeit -s 'from cStringIO import StringIO; s=StringIO()' 'for i in 
xrange(10): s.write("x")'
10 loops, best of 3: 56 msec per loop

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


Re: function that accepts any amount of arguments?

2008-04-28 Thread Bruno Desthuilliers

Lie a écrit :

On Apr 25, 2:12 am, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:


(...)


FWIW, I'd personnaly write avg as taking a sequence - ie,
not using varargs - in which case calling it without arguments would a
TypeError (so BTW please s/Value/Type/ in my previous post).


The problem with passing it as a sequence is, if you want to call it,
you may have to wrestle with this odd looking code:
avg((3, 4, 6, 7))

rather than this, more natural code:
avg(3, 4, 6, 7)


Possibly. Yet my experience is that, most of the time, such a function 
will be called with an already existing sequence, so the most common 
call scheme is


  res = avg(some_sequence)

which is more natural than

  res = avg(*some_sequence)

!-)



And FWIW, the OP asked if it is possible to pass variable amount of
arguments,  avg is just a mere example of one where it could be used
not where it could be best used.


Indeed - but that's not what I was commenting on.
--
http://mail.python.org/mailman/listinfo/python-list


Checking for existance of feature / tools / solutions -- Something like Java webstart

2008-04-28 Thread Banibrata Dutta
Hi,

I've tried searching this list & googling around a bit -- trying to
see if there is a Java-Webstart like alternative for Python, the
closest approximate I've found is something suggested in this post:

http://mail.python.org/pipermail/python-list/2004-September/282837.html

Is this still pretty much the state-of-art ? Or, is there some other,
better, simpler, snappier alternative.

My requirements fundamentally are to use the web-mechanism
("something" embedded in a webpage, that is able to detect whether
particular (minimal) version of Python is installed on the client
system, and whether my client-software (Python app) is installed or
not, will possibly, first install Python (latest) if not installed,
and then my client-software (Python app). If both are installed, it'd
allow me to upgrade the python app (and/or Python itself prior to it).

This seems to be a something that should be fairly common thing that
folks might have to do!

thanks & regards,
Banibrata
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expression - Matching Multiples of 3 Characters exactly.

2008-04-28 Thread Jeff
Regular expressions for that sort of thing can get *really* big.  The
most efficient way would be to programmatically compose the regular
expression to be as exact as possible.

import re

def permutation(lst):

From http://labix.org/snippets/permutations/. Computes permutations
of a
list iteratively.
"""
queue = [-1]
lenlst = len(lst)
while queue:
i = queue[-1]+1
if i == lenlst:
queue.pop()
elif i not in queue:
queue[-1] = i
if len(queue) == lenlst:
yield [lst[j] for j in queue]
queue.append(-1)
else:
queue[-1] = i

def segment_re(a, b):
"""
Creates grouped regular expression pattern to match text between all
possibilies of three-letter sets a and b.
"""
def pattern(n):
return "(%s)" % '|'.join( [''.join(grp) for grp in 
permutation(n)] )

return re.compile( r'%s(\w+?)%s' % (pattern(a), pattern(b)) )

print segment_re(["a", "b", "c"], ["d", "e", "f"])

You could extend segment_re to accept an integer to limit the (\w+?)
to a definite quantifier.  This will grow the compiled expression in
memory but make matching faster (such as \w{3,n} to match from 3 to n
characters).

See http://artfulcode.net/articles/optimizing-regular-expressions/ for
specifics on optimizing regexes.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help on left padding

2008-04-28 Thread Albert Leibbrandt

Marc 'BlackJack' Rintsch wrote:

On Mon, 28 Apr 2008 04:37:02 -0700, rajesh kataraki wrote:

  

 My requirement is I am using one variable ex. var = 5 which is
integer.
And this variable, I m using in some string. But I want this var
to be used as 005 again integer in this string.



In [22]: '%03d' % 5
Out[22]: '005'

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

  

   that or use *str(5).zfill(3)*
--
http://mail.python.org/mailman/listinfo/python-list

Re: Retrieving int from hex in a file.

2008-04-28 Thread Filipe Teixeira
>
> Use ord(q)
>
> py> help(ord)
> Help on built-in function ord in module __builtin__:
>
> ord(...)
>  ord(c) -> integer
>
>  Return the integer ordinal of a one-character string.
>
> py>
>
> --
> Gabriel Genellina

Thank you Gabriel. It fit's my purpose.

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


Re: Retrieving int from hex in a file.

2008-04-28 Thread bgeddy

Filipe Teixeira wrote:

Hi.

I have to open a binary file from an old computer and recover the
information stored (or at least try to). I use:

f=open('file.bin','rb')
a=f.read()
f.close()

a in now a string full of hex representations in the form:

a[6]='\x14'
a[7]='\x20'

I would like to convert these hex representations to int, but this
(the most obvious way) doesn't seem to be working


q=a[6]
q

'\x14'

int(q,16)

Traceback (most recent call last):
  File "", line 1, in ?
ValueError: invalid literal for int():

How can I do this?

Thanks


As you say you are trying to recover information from the old computer 
are you sure you want to convert the data to it's integer representation   ?
What I mean is in this case the string will contain the actual data read 
from the file, not a hex representation. It's just the python displays 
this data as '\x14'. BTW - are you sure it's displaying '\x20' from your 
data as this should be a space character i.e. " ".


In the python interpreter try this:

mydata=""
for i in range(256):
mydata+=chr(i)
>> mydata

This will show you the hex representation of the values in mydata that 
it can't display however the string is not a string of "hex values" as 
such, it contains the binary values 0-255.

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


Re: apache module: python and web programming, easy way...?

2008-04-28 Thread Graham Dumpleton
On Apr 28, 7:42 pm, bvidinli <[EMAIL PROTECTED]> wrote:
> is there any apache module, you know, that i can just install with apt-get,
> then put my .py file, and run it ?

http://www.modwsgi.org
http://www.modpython.org

The mod_wsgi module supports WSGI (http://www.wsgi.org) specification
which is where Python web framework hosting is heading whereas
mod_python has its own specific API which results in your application
only being able to be hosted with it and nothing else.

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


Re: Need help on left padding

2008-04-28 Thread Marc 'BlackJack' Rintsch
On Mon, 28 Apr 2008 04:37:02 -0700, rajesh kataraki wrote:

>  My requirement is I am using one variable ex. var = 5 which is
> integer.
> And this variable, I m using in some string. But I want this var
> to be used as 005 again integer in this string.

In [22]: '%03d' % 5
Out[22]: '005'

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


  1   2   >