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

2009-04-08 Thread Gabriel Genellina
QOTW:  Those who show promise can advance to our Winter Improve Python to
Expert program, for an additional fee, and, be given expert tutoring to help
you gain our exemplary A.R.S.E./W.I.P.E certification which is guaranteed to
attract certain types of employers by its name alone. - Paddy3118
http://groups.google.com/group/comp.lang.python/msg/f86e314251d94d96


Two new releases this week: 
* Python 3.1 alpha 2:
http://mail.python.org/pipermail/python-list/2009-April/707817.html
* and Python 2.6.2 candidate 1:
http://mail.python.org/pipermail/python-list/2009-April/708214.html

Dynamically adding new methods to a class hierarchy:
http://groups.google.com/group/comp.lang.python/t/a6805cc39de3746a/

How to handle infinite generators (in the example, generating *all*
prime numbers):
http://groups.google.com/group/comp.lang.python/t/77cc9764f9d5a072/

Refactoring a giant class into smaller parts:
http://groups.google.com/group/comp.lang.python/t/581d6b8dac0360d6/

People coming from static languages fear that Python code requires
stronger unit tests - is that true?
http://groups.google.com/group/comp.lang.python/t/8a3be7bb5ee1d1b4/

Synchronizing concurrent access to a dictionary:
http://groups.google.com/group/comp.lang.python/t/d2156aa4aaf95bd5/

Can an object know whose attribute it is called upon?
http://groups.google.com/group/comp.lang.python/t/1b43c60954e0a7a3/

Usually, returning different types based on input parameters is a bad idea:
http://groups.google.com/group/comp.lang.python/t/b9fbef4368cf9981/



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

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/group/comp.lang.python.announce/topics

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

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/donations/

The Summary of Python Tracker Issues is an automatically generated
report summarizing new bugs, closed ones, and patch submissions. 

http://search.gmane.org/?author=status%40bugs.python.orggroup=gmane.comp.python.develsort=date

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://code.activestate.com/recipes/langs/python/

Many Python conferences around the world are in preparation.
Watch this space for links to them.

Among several Python-oriented RSS/RDF feeds available, see:
http://www.python.org/channews.rdf
For more, see:
http://www.syndic8.com/feedlist.php?ShowMatch=pythonShowStatus=all
The old Python To-Do List now lives principally in a
SourceForge reincarnation.
http://sourceforge.net/tracker/?atid=355470group_id=5470func=browse

Re: Anyone mannaged to access parallel port on windows xp?

2009-04-08 Thread prakash jp
Hi all,

just would like to say that most of the parallel port preexistant code is
usually blinking leds,
which is the not the true reprsentation of the paralle port  behaviour. Here
one needs to
think that data is coming out byte after byte. Now plz look out for the
sequence to
push data byte after byte. One pin to pulse(programatically) for a byte
of data to come
out is the Pin 0, strobe pin, then reset the same to push the next byte of
data.
Latare u r expected to send these data byte in the sequnce that the target
board
requirement. I have done this in c - dos based

regards
Prakash



On Tue, Apr 7, 2009 at 12:09 PM, alejandro aleksanda...@brisiovonet.hrwrote:

 I have a switch  that I should connect to the parallel port, but had no
 luck
 with it. Tha guy that made it for me told me that it would be easyer to
 connect via parallel instead the USB
 So did anyone have success? I only get suckess!! :-))
 tryed giveio.sys but it doesn't wort (can't figure out what is it)


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

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


Re: Incomplete exception tracebacks when importing from zipped modules

2009-04-08 Thread Gabriel Genellina
En Thu, 02 Apr 2009 09:35:53 -0300, arve.knud...@gmail.com  
arve.knud...@gmail.com escribió:



I can't seem to get complete tracebacks when modules imported from zip
archives raise exceptions. [...]
As you can see, the code for each stack entry is omitted. Is this
normal??


A known problem, at least...
You should be able to find it reported somewhere at http://bugs.python.org

--
Gabriel Genellina

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


Re: Injecting python function in an embedded python engine

2009-04-08 Thread Gabriel Genellina
En Mon, 06 Apr 2009 13:58:12 -0300, Roberto Fichera ker...@tekno-soft.it  
escribió:


I've embedded python v2.6.x engine into my application without any  
problem.

Now I would like to inject some additional functions after importing a
python module.
So, basically I'm importing a python module via PyImport_ImportModule()
function.
The python module is a simple set of functions and I would check if some
functions
does exist or not, than if doesn't I would add it from my C application.
Checking if
a function does exist or not isn't an issue, it works without any
problem, my problem
is only how to inject a new function in an already imported module.


Easy (so I wonder whether I misunderstood your question):

some_module.function_name = new_function_object
or
setattr(some_module, function_name, new_function_object)
or
use PyObject_SetAttr/PyObject_SetAttrString in C code.

--
Gabriel Genellina

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


RE: Scraping a web page

2009-04-08 Thread Lawrence D'Oliveiro
In message mailman.3480.1239112765.11746.python-l...@python.org, Support 
Desk wrote:

 You could do something like below to get the rendered page.
 
 Import os
 site = 'website.com'
 X = os.popen('lynx --dump %s' % site).readlines()

I wonder how easy it would be to get the page image in SVG format? I believe 
the Gecko HTML engine in Firefox already uses Cairo for its rendering, and 
Cairo supports SVG as one of its surface types.

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


Re: Injecting python function in an embedded python engine

2009-04-08 Thread prakash jp
import os
ch = os.system(import -window root temp.png)
print ch
 after that no way to store the screen shot

regards
Prakash

On Mon, Apr 6, 2009 at 10:28 PM, Roberto Fichera ker...@tekno-soft.itwrote:

 Hi All in the list,

 I've embedded python v2.6.x engine into my application without any problem.
 Now I would like to inject some additional functions after importing a
 python module.
 So, basically I'm importing a python module via PyImport_ImportModule()
 function.
 The python module is a simple set of functions and I would check if some
 functions
 does exist or not, than if doesn't I would add it from my C application.
 Checking if
 a function does exist or not isn't an issue, it works without any
 problem, my problem
 is only how to inject a new function in an already imported module.

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

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


TypeError: object cannot be interpreted as an index

2009-04-08 Thread tleeuwenb...@gmail.com
It started with this error message... TypeError: object cannot be
used as an index

foo = {}
someObject = someClass()
foo[someObject] = hello

Obviously, there are some known reasons why objects may not be
indexes, such as if they are not hashable (as in the case of lists).
However, I'm not getting that error message. I tested this out with
some minimal Python code, and the error did not occur. It only occurs
in my big codebase, not in a neat minimal example using a very small
class.

The type of this object is listed as 'instance'. My interpreter is
2.5.1

So I tried looking for more information inside types, and found
types.InstanceType.

Running help(types.InstanceType) gave me:
 help(types.InstanceType)
hello
Traceback (most recent call last):
  File stdin, line 1, in module
  File /usr/local/python-2.5.1/lib/python2.5/site.py, line 345, in
__call__
import pydoc
  File /usr/local/python-2.5.1/lib/python2.5/pydoc.py, line 56, in
module
from repr import Repr
ImportError: cannot import name Repr

There is a good chance that this object is build from C code,
instantiated through Swig. I'll have to do a bit more work to trace
back where the problem object is being created...

What, exactly, needs to be in place for an object to be a valid
dictionary key?
--
--
Tennessee Leeuwenburg
http://myownhat.blogspot.com/
Don't believe everything you think
--
http://mail.python.org/mailman/listinfo/python-list


Re: Q: Best book for teaching

2009-04-08 Thread John Yeung
On Apr 6, 10:37 am, grkunt...@gmail.com wrote:
 I am considering teaching an introduction to programming
 course for continuing education adults at a local community
 college. These would people with no programming experience,
 but I will require a reasonable facility with computers.

 What would be a good book to use as the text for the course?

For an extremely gentle introduction, perhaps take a look at _Python
Programming for the Absolute Beginner_ by Michael Dawson:

  
http://www.amazon.com/Python-Programming-Absolute-Beginner-Michael/dp/1592000738

A coworker of mine recently bought this book, which is how I found out
about it.  Besides assuming no programming experience, it tries to
stay interesting through the use of simple games for its examples
(eventually building up to the use of the popular pygame library).
The writing style is definitely more fun than academic.

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


Help with setting up Tkinter

2009-04-08 Thread Eclipse




 import _tkinter
 import Tkinter
 Tkinter._test
function _test at 0x0265D430

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


Help with setting up Tkinter

2009-04-08 Thread Eclipse
G'day All

I was following the instructions (listed at bottom of post) from the
PythonInfo Wiki which says to run three tests.

I ran the tests and test 1 and 2 worked

Test 3 gave me an error - function _test at 0x0265D430

can anyone help ???

Tks in advance

Pete

 import _tkinter
 import Tkinter
 Tkinter._test
function _test at 0x0265D430

_

Checking your Tkinter support

A good way to systematically check whether your Tkinter support is
working is the following.

Enter an interactive Python interpreter in a shell on an X console.

Step 1 - can _tkinter be imported?

Try the following command at the Python prompt:

 import _tkinter # with underscore, and lowercase 't'

* If it works, go to step 2.
* If it fails with No module named _tkinter, your Python
configuration needs to be modified to include this module (which is an
extension module implemented in C). Do **not** edit Modules/Setup (it
is out of date). You may have to install Tcl and Tk (when using RPM,
install the -devel RPMs as well) and/or edit the setup.py script to
point to the right locations where Tcl/Tk is installed. If you install
Tcl/Tk in the default locations, simply rerunning make should build
the _tkinter extension.
* If it fails with an error from the dynamic linker, see above
(for Unix, check for a header/library file mismatch; for Windows,
check that the TCL/TK DLLs can be found).

Step 2 - can Tkinter be imported?

Try the following command at the Python prompt:

 import Tkinter # no underscore, uppercase 'T'

* If it works, go to step 3.
* If it fails with No module named Tkinter, your Python
configuration need to be changed to include the directory that
contains Tkinter.py in its default module search path. You have
probably forgotten to define TKPATH in the Modules/Setup file. A
temporary workaround would be to find that directory and add it to
your PYTHONPATH environment variable. It is the subdirectory named
lib-tk of the Python library directory (when using Python 1.4 or
before, it is named tkinter).

Step 3 - does Tkinter work?

Try the following command at the Python prompt:

 Tkinter._test( ) # note underscore in _test( )

* This should pop up a small window with two buttons. Clicking the
Quit button makes it go away and the command return. If this works,
you're all set. (When running this test on Windows, from Python run in
a MS-DOS console, the new window somehow often pops up *under* the
console window. Move it aside or locate the Tk window in the Taskbar.)
*

  If this doesn't work, study the error message you get; if you
can't see how to fix the problem, ask for help.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help with setting up Tkinter

2009-04-08 Thread Chris Rebert
On Wed, Apr 8, 2009 at 1:15 AM, Eclipse pnsm...@gmail.com wrote:

 import _tkinter
 import Tkinter
 Tkinter._test
 function _test at 0x0265D430

That last input line should be:
Tkinter._test()

Note the parens, which do matter (Python != Ruby/Smalltalk). Try again
and see if you get an actual error.

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help with setting up Tkinter

2009-04-08 Thread koranthala
On Apr 8, 1:20 pm, Eclipse pnsm...@gmail.com wrote:
 G'day All

 I was following the instructions (listed at bottom of post) from the
 PythonInfo Wiki which says to run three tests.

 I ran the tests and test 1 and 2 worked

 Test 3 gave me an error - function _test at 0x0265D430

 can anyone help ???

 Tks in advance

 Pete

  import _tkinter
  import Tkinter
  Tkinter._test

 function _test at 0x0265D430

 _

 Checking your Tkinter support

 A good way to systematically check whether your Tkinter support is
 working is the following.

 Enter an interactive Python interpreter in a shell on an X console.

 Step 1 - can _tkinter be imported?

 Try the following command at the Python prompt:

  import _tkinter # with underscore, and lowercase 't'

     * If it works, go to step 2.
     * If it fails with No module named _tkinter, your Python
 configuration needs to be modified to include this module (which is an
 extension module implemented in C). Do **not** edit Modules/Setup (it
 is out of date). You may have to install Tcl and Tk (when using RPM,
 install the -devel RPMs as well) and/or edit the setup.py script to
 point to the right locations where Tcl/Tk is installed. If you install
 Tcl/Tk in the default locations, simply rerunning make should build
 the _tkinter extension.
     * If it fails with an error from the dynamic linker, see above
 (for Unix, check for a header/library file mismatch; for Windows,
 check that the TCL/TK DLLs can be found).

 Step 2 - can Tkinter be imported?

 Try the following command at the Python prompt:

  import Tkinter # no underscore, uppercase 'T'

     * If it works, go to step 3.
     * If it fails with No module named Tkinter, your Python
 configuration need to be changed to include the directory that
 contains Tkinter.py in its default module search path. You have
 probably forgotten to define TKPATH in the Modules/Setup file. A
 temporary workaround would be to find that directory and add it to
 your PYTHONPATH environment variable. It is the subdirectory named
 lib-tk of the Python library directory (when using Python 1.4 or
 before, it is named tkinter).

 Step 3 - does Tkinter work?

 Try the following command at the Python prompt:

  Tkinter._test( ) # note underscore in _test( )

     * This should pop up a small window with two buttons. Clicking the
 Quit button makes it go away and the command return. If this works,
 you're all set. (When running this test on Windows, from Python run in
 a MS-DOS console, the new window somehow often pops up *under* the
 console window. Move it aside or locate the Tk window in the Taskbar.)
     *

       If this doesn't work, study the error message you get; if you
 can't see how to fix the problem, ask for help.

Can you try Tkinter._test() instead of Tkinter._test
Just Tkinter._test  will go and hit its __repr__ code - i.e.
representation I guess - which displays the function data instead of
running actual function.
--
http://mail.python.org/mailman/listinfo/python-list


Re: more fun with iterators (mux, demux)

2009-04-08 Thread pataphor
On 07 Apr 2009 02:05:59 GMT
Steven D'Aprano ste...@remove.this.cybersource.com.au wrote:

 The demuxer can't be an iterator, since it needs to run through the 
 entire collection.

Then your demuxer obviously cannot handle infinite sequences.
 
 def demux(it, n):
 collectors = [[] for i in xrange(n)]
 i = 0
 for item in it:
 collectors[i].append(item)
 i = (i+1) % n
 return tuple([iter(x) for x in collectors])

But this one can:

from collections import deque
from itertools import cycle, izip, count, islice

def mux(*iterables):
for it in izip(*iterables):
for item in it:
yield item

def demux(seq,n):
it = iter(seq)
Q = [deque() for i in xrange(n)]
CQ = cycle(Q)
def gen(D):
for x,C in izip(it,CQ):
C.appendleft(x)
while D:  
yield D.pop()
while D:  
yield D.pop()
return map(gen,Q)

def test():
a = count(10)
b = count(20)
c = count (30)
x = demux(mux(a,b,c),3)
for e in x:
print list(islice(e,0,10))

if __name__=='__main__':
test()

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


Re: TypeError: object cannot be interpreted as an index

2009-04-08 Thread Peter Otten
tleeuwenb...@gmail.com wrote:

 It started with this error message... TypeError: object cannot be
 used as an index
 
 foo = {}
 someObject = someClass()
 foo[someObject] = hello

interpreted or used? 

If the former, 'foo' may be a list rather than a dict, and someClass a
classic class:

 class A: pass
...
 {A(): 42}
{__main__.A instance at 0x2ac2a6d35bd8: 42}
 [][A()]
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: object cannot be interpreted as an index

To find out the actual the actual type of a classic class look into the
__class__ attribute:

 type(A())
type 'instance'
 A().__class__
class __main__.A at 0x2ac2a6d1e830

Peter

PS: Please cut and paste in the future.

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


Why does Python show the whole array?

2009-04-08 Thread Gilles Ganault
Hello

I'd like to go through a list of e-mail addresses, and extract those
that belong to well-known ISP's. For some reason I can't figure out,
Python shows the whole list instead of just e-mails that match:

=== script
test = t...@gmail.com
isp = [gmail.com, yahoo.com]
for item in isp:
if test.find(item):
print item
=== output
gmail.com
yahoo.com
=== 

Any idea why I'm also getting yahoo.com?

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


Re: Why does Python show the whole array?

2009-04-08 Thread Ulrich Eckhardt
Gilles Ganault wrote:
 test = t...@gmail.com
 isp = [gmail.com, yahoo.com]
 for item in isp:
 if test.find(item):
 print item
 === output
 gmail.com
 yahoo.com
 ===
 
 Any idea why I'm also getting yahoo.com?

find() returns the index where it is found or -1 if it is not found. Both an
index0 or a -1 evaluate to True when used as conditional expression.

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Re: Why does Python show the whole array?

2009-04-08 Thread Albert Hopkins
On Wed, 2009-04-08 at 12:01 +0200, Peter Otten wrote:
 Gilles Ganault wrote:
 
  I'd like to go through a list of e-mail addresses, and extract those
  that belong to well-known ISP's. For some reason I can't figure out,
  Python shows the whole list instead of just e-mails that match:
  
  === script
  test = t...@gmail.com
  isp = [gmail.com, yahoo.com]
  for item in isp:
  if test.find(item):
  print item
  === output
  gmail.com
  yahoo.com
  === 
  
  Any idea why I'm also getting yahoo.com?
 
 Because str.find() returns the position of the search string if found and -1
 if it is not found:
 
  abc.find(bc)
 1
  abc.find(ab)
 0
  abc.find(x)
 -1
 
 Use
 
 if test.find(item) != -1: ...
 
 or
 
 if item in test: ...
 
 to make your example work.

Or you could also use the .endswith() method

if test[test.find('@')+1:].endswith(item):


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


Re: Why does Python show the whole array?

2009-04-08 Thread Ben Finney
Gilles Ganault nos...@nospam.com writes:

 I'd like to go through a list of e-mail addresses, and extract those
 that belong to well-known ISP's. For some reason I can't figure out,
 Python shows the whole list instead of just e-mails that match:
 
 === script
 test = t...@gmail.com
 isp = [gmail.com, yahoo.com]
 for item in isp:
   if test.find(item):
   print item
 === output
 gmail.com
 yahoo.com
 === 
 
 Any idea why I'm also getting yahoo.com?

You've had answers on the “why” question.

Here's a suggestion for a better way that doesn't involve ‘find’:

 known_domains = [example.com, example.org]
 test_address = t...@example.com
 for domain in known_domains:
... if test_address.endswith(@ + domain):
... print domain
... 
example.com
 

If all you want is a boolean “do any of these domains match the
address”, it's quicker and simpler to feed an iterator to ‘any’
(first introduced in Python 2.5), which short-cuts by exiting on the
first item that produces a True result:

 known_domains = [example.com, example.org]
 test_address = t...@example.com
 any(test_address.endswith(@ + domain) for domain in known_domains)
True
 test_address = tin...@example.net
 any(test_address.endswith(@ + domain) for domain in known_domains)
False

-- 
 \  “For my birthday I got a humidifier and a de-humidifier. I put |
  `\  them in the same room and let them fight it out.” —Steven Wright |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to go about. On read/write locks

2009-04-08 Thread Piet van Oostrum
 Carl Banks pavlovevide...@gmail.com (CB) wrote:

CB On Apr 6, 2:23 pm, Diez B. Roggisch de...@nospam.web.de wrote:
  This is a classical synchronization problem with a classical solution:
  You treat the readers as a group, and the writers individually. So you
  have a write lock that each writer has to acquire and release, but it is
  acquired only by the first reader and released by the last one.
  Therefore you need a counter of the number of readers, and manipulations
  of this counter must be protected by another lock.
 
 I was going to suggest a similar approach but refused to because of a
 problem I see with your code as well - if the readers are reading very
 fast (the OP didn't state what his actual application is, so it might
 not be a consumer-producer scheme which I don't think a dict would be
 the natural choice anyway) they can block the writer from writing
 alltogether.

CB You could implement some kind of fair ordering where whoever requests
CB a lock first is guaranteed to get it first, but I can't think of a way
CB to do that without requiring all readers to acquire two locks.

The original implementation (with writers starvation) comes from [1].
They also describe a solution where witers have priority, but it needs 5
semaphores and 2 counters (one for writers and one for readers). It can
cause starvation for readers, however. For the OP this wouldn't be a
problem because writers are rare in his situation.

However, I found a solution [2] with just one additional counter for the
number of writers and no additional semaphores. The manipulations of the
writers counter are also protected by the same mutex. This solution is
fair for both readers and writers. Translated in Python this would be:

#
from threading import Lock

mutex = Lock()
writelock = Lock()
numreaders = 0
numwriters = 0
#
# Reader code:

mutex.acquire()
if numwriters  0 or numreaders == 0:
   mutex.release()
   writelock.acquire()
   mutex.acquire()
numreaders += 1
mutex.release()

## critical section for reader

mutex.acquire()
numreaders -= 1
if numreaders == 0:
writelock.release()
mutex.release()
#
# Writer code:

mutex.acquire()
numwriters += 1
mutex.release()
writelock.acquire()

## critical section for writer

mutex.acquire()
numwriters -= 1
mutex.release()
writelock.release()
#

I am going to put this in a class, with a context manager so that it can
be use with the 'with' statement like the normal locks.

I also found a solution with no additional counters but an additional
semaphore, but I found it only in lecture notes [3,4]; I couldn't find any
scientific publications about it. So I don't know for sure if it is
correct, fair etc.

[1] P. J. Courtois , F. Heymans , D. L. Parnas, Concurrent control with
“readers” and “writers”, Communications of the ACM, v.14 n.10,
p.667-668, Oct. 1971
[2] Jalal Kawash, Process Synchronization with Readers and Writers
Revisited Journal of Computing and Information Technology - CIT 13,
2005, 1, 43–51
[3] http://pages.cs.wisc.edu/~haryadi/537/slides/lec18-semaphores.ppt
[4] http://vorlon.case.edu/~jrh23/338/HW3.pdf
-- 
Piet van Oostrum p...@cs.uu.nl
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why does Python show the whole array?

2009-04-08 Thread Dave Angel



Gilles Ganault wrote:

Hello

I'd like to go through a list of e-mail addresses, and extract those
that belong to well-known ISP's. For some reason I can't figure out,
Python shows the whole list instead of just e-mails that match:

=== script
test = t...@gmail.com
isp = [gmail.com, yahoo.com]
for item in isp:
if test.find(item):
print item
=== output
gmail.com
yahoo.com
=== 


Any idea why I'm also getting yahoo.com?

Thank you.

  
Look up the definition of string.find().  It returns a -1 for failure, 
not 0.  So your test should presumably be

  if test.find(item) != -1:


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


Re: Why does Python show the whole array?

2009-04-08 Thread Qilong Ren




Remeber the return value of find function of a string is -1 when it  
fails, which is True.


Try:
  for item in isp:
 if item in test:
   print item




From: Gilles Ganault nos...@nospam.com
Date: April 8, 2009 5:56:34 PM CST
To: python-list@python.org
Subject: Why does Python show the whole array?


Hello

I'd like to go through a list of e-mail addresses, and extract those
that belong to well-known ISP's. For some reason I can't figure out,
Python shows the whole list instead of just e-mails that match:

=== script
test = t...@gmail.com
isp = [gmail.com, yahoo.com]
for item in isp:
if test.find(item):
print item
=== output
gmail.com
yahoo.com
===

Any idea why I'm also getting yahoo.com?

Thank you.



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


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


Re: Q: Best book for teaching

2009-04-08 Thread Lawrence D'Oliveiro
In message 
8e3d0032-5e9f-44c2-9380-1d2383552...@u5g2000vbc.googlegroups.com, 
grkunt...@gmail.com wrote:

 I am considering teaching an introduction to programming course for
 continuing education adults at a local  community college. These would
 people with no programming experience, but I will require a reasonable
 facility with computers.

I thought that a good introduction might be to show them how HTML works, and 
progress from there to embedding little bits of JavaScript.

Nothing to do with Python I know, but might be a possibility.

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


Re: Why does Python show the whole array?

2009-04-08 Thread Peter Otten
Gilles Ganault wrote:

 I'd like to go through a list of e-mail addresses, and extract those
 that belong to well-known ISP's. For some reason I can't figure out,
 Python shows the whole list instead of just e-mails that match:
 
 === script
 test = t...@gmail.com
 isp = [gmail.com, yahoo.com]
 for item in isp:
 if test.find(item):
 print item
 === output
 gmail.com
 yahoo.com
 === 
 
 Any idea why I'm also getting yahoo.com?

Because str.find() returns the position of the search string if found and -1
if it is not found:

 abc.find(bc)
1
 abc.find(ab)
0
 abc.find(x)
-1

Use

if test.find(item) != -1: ...

or

if item in test: ...

to make your example work.

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


Re: TypeError: object cannot be interpreted as an index

2009-04-08 Thread Piet van Oostrum
 tleeuwenb...@gmail.com tleeuwenb...@gmail.com (tc) wrote:

tc What, exactly, needs to be in place for an object to be a valid
tc dictionary key?

It must have __hash__ and __cmp__ or __eq__ methods. Newstyle classes
inherit these from object.
-- 
Piet van Oostrum p...@cs.uu.nl
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: List of paths

2009-04-08 Thread Nico Grubert


 Here's a tricky case that doesn't show up in your example:
 In each case above, the directory names are distinct.
 how about:
['/desk', '/desk/ethanallen', '/desk/ikea',
  '/desktop', /desktop/pc', '/desktop/mac']
Should the answer be ['/desk'] or ['/desk', '/desktop'] ?

Hi Scott

good point.
It should be:

  ['/desk', '/desktop']
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why does Python show the whole array?

2009-04-08 Thread Gilles Ganault
On Wed, 08 Apr 2009 12:11:55 +0200, Ulrich Eckhardt
eckha...@satorlaser.com wrote:
find() returns the index where it is found or -1 if it is not found. Both an
index0 or a -1 evaluate to True when used as conditional expression.

Thanks everyone. I shouldn't have assumed that if test.find(item):
was necessarily enough to mean True.

for item in isp:
#GOOD if item in test:
if test.find(item)  0:
print test
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-04-08 Thread Gabriel Genellina
QOTW:  Those who show promise can advance to our Winter Improve Python to
Expert program, for an additional fee, and, be given expert tutoring to help
you gain our exemplary A.R.S.E./W.I.P.E certification which is guaranteed to
attract certain types of employers by its name alone. - Paddy3118
http://groups.google.com/group/comp.lang.python/msg/f86e314251d94d96


Two new releases this week: 
* Python 3.1 alpha 2:
http://mail.python.org/pipermail/python-list/2009-April/707817.html
* and Python 2.6.2 candidate 1:
http://mail.python.org/pipermail/python-list/2009-April/708214.html

Dynamically adding new methods to a class hierarchy:
http://groups.google.com/group/comp.lang.python/t/a6805cc39de3746a/

How to handle infinite generators (in the example, generating *all*
prime numbers):
http://groups.google.com/group/comp.lang.python/t/77cc9764f9d5a072/

Refactoring a giant class into smaller parts:
http://groups.google.com/group/comp.lang.python/t/581d6b8dac0360d6/

People coming from static languages fear that Python code requires
stronger unit tests - is that true?
http://groups.google.com/group/comp.lang.python/t/8a3be7bb5ee1d1b4/

Synchronizing concurrent access to a dictionary:
http://groups.google.com/group/comp.lang.python/t/d2156aa4aaf95bd5/

Can an object know whose attribute it is called upon?
http://groups.google.com/group/comp.lang.python/t/1b43c60954e0a7a3/

Usually, returning different types based on input parameters is a bad idea:
http://groups.google.com/group/comp.lang.python/t/b9fbef4368cf9981/



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

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/group/comp.lang.python.announce/topics

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

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/donations/

The Summary of Python Tracker Issues is an automatically generated
report summarizing new bugs, closed ones, and patch submissions. 

http://search.gmane.org/?author=status%40bugs.python.orggroup=gmane.comp.python.develsort=date

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://code.activestate.com/recipes/langs/python/

Many Python conferences around the world are in preparation.
Watch this space for links to them.

Among several Python-oriented RSS/RDF feeds available, see:
http://www.python.org/channews.rdf
For more, see:
http://www.syndic8.com/feedlist.php?ShowMatch=pythonShowStatus=all
The old Python To-Do List now lives principally in a
SourceForge reincarnation.
http://sourceforge.net/tracker/?atid=355470group_id=5470func=browse

Re: Why does Python show the whole array?

2009-04-08 Thread andrew cooke
Gilles Ganault wrote:
 On Wed, 08 Apr 2009 12:11:55 +0200, Ulrich Eckhardt
 eckha...@satorlaser.com wrote:
find() returns the index where it is found or -1 if it is not found. Both
 an
index0 or a -1 evaluate to True when used as conditional expression.

 Thanks everyone. I shouldn't have assumed that if test.find(item):
 was necessarily enough to mean True.

 for item in isp:
   #GOOD if item in test:
   if test.find(item)  0:

the post you quote has an error.  you probably want  -1 there.  0 is
returned if the two strings match at the start.  the problem is that the
method return isn't consistent with implicit conversion to boolean; python
does convert non-zero to True.

andrew

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




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


Re: named pipe and Linux

2009-04-08 Thread bobicanprogram
On Apr 7, 1:08 pm, akineko akin...@gmail.com wrote:
 Hello everyone,

 I'm trying to use named pipes to fuse a Python program and a C
 program.
 One side creates pipes using os.mkfifo() and both sides use the same
 named pipes (one side reads, another side writes). The read side uses
 select.select() to wait for incoming messages and read the message
 when select.select() says it is ready.

 The length of the message is unknown to the read side.
 I cannot use file.read() because it will block waiting for an EOF.
 I cannot use file.readline() because how many lines have arrived is
 unknown.
 So, I needed to use os.read() with the exact number of characters to
 read.

 Under Solaris environment, os.fstat() provides the exact size of the
 message that has arrived.
 Thus, two processes can communicate each other through the named pipes
 without blocking.

 However, the above scheme didn't work under Linux.
 Linux os.fstat() returns size=0 even the message is pending.
 (I think Linux buffers the message in memory while Solaris buffers the
 message in a file system)

 My question is, how can I make the named pipe scheme work under Linux?
 Is there any way to read the message without getting blocked?

 I know this is more Linux question than Python question but I believe
 many Python programmers are strong Linux programmers.

 Any suggestions will be appreciated.

 Best regards,
 Aki Niimura


The SIMPL open source project (http://www.icanprogram.com/simpl)
provides an ultra lightweight toolkit useful for joining Python
programs to C programs using a Send/Receive/Reply mechanism first
pioneered by QNX.SIMPL uses a fifo synchronized shared memory
scheme for the local message pass.Through the use of generic
surrogate pairs SIMPL processes can be distributed across TCP/IP or
RS232 (think radio modem) networks often times without any changes or
recompiles.   Through the use of another type of generic surrogate a
Python module running on a nonLinux OS can communicate transparently
with a module running on a Linux box.

A SIMPL application consists of two or more SIMPL modules
collaborating in this way.   SIMPL modules can be written in any
number of languages including Python, C, C++,  Tcl/Tk or JAVA.   More
importantly SIMPL modules written in different languages can be mixed
in a given SIMPL application.

There is a Sudoku puzzle solver example here:

http://www.icanprogram.com/simplBook/simplBook.self.html

bob
SIMPL project facilitator
--
http://mail.python.org/mailman/listinfo/python-list


Re: Some test fail on my new Python 2.6

2009-04-08 Thread R. David Murray
Sorin Schwimmer sx...@yahoo.com wrote:
 
 I wanted to replace my old Python 2.4 and tcl/tk 8.4 with tcl/tk 8.5.6 and 
 Python 2.6, mainly so that I can enjoy ttk. tcl/tk was installed from sources 
 without any problem, I started a wish and worked.
 
 Now, for the Python, here are all the issues signaled by make test:

 running build
 running build_ext
 building 'dbm' extension
 gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall 
 -Wstrict-prototypes -DHAVE_GDBM_NDBM_H -I. -I/install/Python-2.6.1/./Include 
 -I. -IInclude -I./Include -I/usr/local/include 
 -I/install/Python-2.6.1/Include -I/install/Python-2.6.1 -c 
 /install/Python-2.6.1/Modules/dbmmodule.c -o 
 build/temp.linux-i686-2.6/install/Python-2.6.1/Modules/dbmmodule.o
 gcc -pthread -shared 
 build/temp.linux-i686-2.6/install/Python-2.6.1/Modules/dbmmodule.o 
 -L/usr/local/lib -lgdbm -o build/lib.linux-i686-2.6/dbm.so
 *** WARNING: renaming dbm since importing it failed: 
 build/lib.linux-i686-2.6/dbm.so: undefined symbol: dbm_firstkey

Ok, so DBM wasn't built because it couldn't find the external symbol
'dbm_firstkey'.  I have no idea off the top of my head why that would
happen, but I don't think you really care at the moment since you are
trying to get tkinter working.  If you do care we can come back to that.

 building '_tkinter' extension
 gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall 
 -Wstrict-prototypes -DWITH_APPINIT=1 -DWITH_BLT=1 -I/usr/X11R6/include -I. 
 -I/install/Python-2.6.1/./Include -I. -IInclude -I./Include 
 -I/usr/local/include -I/install/Python-2.6.1/Include -I/install/Python-2.6.1 
 -c /install/Python-2.6.1/Modules/_tkinter.c -o 
 build/temp.linux-i686-2.6/install/Python-2.6.1/Modules/_tkinter.o
 gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall 
 -Wstrict-prototypes -DWITH_APPINIT=1 -DWITH_BLT=1 -I/usr/X11R6/include -I. 
 -I/install/Python-2.6.1/./Include -I. -IInclude -I./Include 
 -I/usr/local/include -I/install/Python-2.6.1/Include -I/install/Python-2.6.1 
 -c /install/Python-2.6.1/Modules/tkappinit.c -o 
 build/temp.linux-i686-2.6/install/Python-2.6.1/Modules/tkappinit.o
 gcc -pthread -shared 
 build/temp.linux-i686-2.6/install/Python-2.6.1/Modules/_tkinter.o 
 build/temp.linux-i686-2.6/install/Python-2.6.1/Modules/tkappinit.o 
 -L/usr/X11R6/lib64 -L/usr/X11R6/lib -L/usr/local/lib -lBLT -ltk8.5 -ltcl8.5 
 -lX11 -o build/lib.linux-i686-2.6/_tkinter.so
 *** WARNING: renaming _tkinter since importing it failed: libtk8.5.so: 
 cannot open shared object file: No such file or directory

Now, this one is clear.  It couldn't find libtk8.5.so when it tried to
use _tkinter.so.  So either that symlink doesn't exist, or points to a
nonexistent library, or there's something wrong with your load library
path, so that python isn't finding it when it tries to do the load.
If you don't know what that last one means, check out 'man ldconfig'.

 Failed to find the necessary bits to build these modules:
 _sqlite3   bsddb185   sunaudiodev

Here you presumably don't have these libraries installed,
so no real problem.

 To find the necessary bits, look in setup.py in detect_modules() for the 
 module's name.
 
 
 Failed to build these modules:
 _tkinter   dbm

These we covered above.

Most of the stuff you show from the test run is expected output
for one reason or another.  The ones that aren't...

 test_multiprocessing
 test_multiprocessing skipped -- OSError raises on RLock creation, see issue 
 3111!

According to the referenced bug, this may be a result of your not having
/dev/shm mounted, but in any case it is more a bug in the tests than a
bug in your system or setup.

 test_socket
 test test_socket failed -- Traceback (most recent call last):
   File /install/Python-2.6.1/Lib/test/test_socket.py, line 474, in 
 testSockName
 my_ip_addr = socket.gethostbyname(socket.gethostname())
 gaierror: [Errno -2] Name or service not known

This probably means that you haven't properly defined 'localhost'
in your /etc/hosts file.

 test_sys
 test test_sys failed -- Traceback (most recent call last):
   File /install/Python-2.6.1/Lib/test/test_sys.py, line 354, in test_43581
 self.assert_(sys.__stdout__.encoding == sys.__stderr__.encoding)
 AssertionError

This one is puzzling.  Did you modify 'site.py'?  Or perhaps you
redirected stdout and stderr to different places and they
wound up with different encodings for some reason.  In which
case that one would be a bug in the tests as well.

 test_tcl
 test_tcl skipped -- No module named _tkinter

This is a result of the build failure.

 320 tests OK.
 3 tests failed:
 test_httpservers test_socket test_sys

So we understand test_socket and maybe test_sys.  You'll have to show
me the output of test_httpsservers run in verbose mode again to see
if I can make sense of that one, if you care.

 38 tests skipped:
 test_aepack test_al test_applesingle test_bsddb185 test_bsddb3
 test_cd test_cl test_codecmaps_cn 

genetic algorithms in Python?

2009-04-08 Thread Esmail

Hello,

Anyone using Python for coding up genetic algorithms? If
so, would you share your favorite modules/libraries/tools?

Thanks,
Esmail

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


Re: Adding method to class at run-time: bad style?

2009-04-08 Thread Grant Edwards
On 2009-04-08, Gabriel Genellina gagsl-...@yahoo.com.ar wrote:

  ClientForm.Control = FancyControl
  ClientForm.CheckboxControl = FancyCheckboxControl

 That would work -- but there are probably 8 or 10 different
 Control subclasses. It's a bit tedious mixing them all one at a
 time, and you need more inside information (the names of all
 the different subclasses).

 New style classes have a __subclasses__() method that could be
 used to find all of them (*at a certain moment*) -- but
 considering all the issues, I think that monkey-patching the
 base class is the less bad option in this case...

Of course I could just 


-- 
Grant Edwards   grante Yow! Th' MIND is the Pizza
  at   Palace of th' SOUL
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Adding method to class at run-time: bad style?

2009-04-08 Thread Grant Edwards
On 2009-04-08, Gabriel Genellina gagsl-...@yahoo.com.ar wrote:

  class Mixin:  # or class Mixin(object) if new-style:
  def __eq__(self, other):
  return (self.type == other.type ...
  def __ne__(self, other):
  return not self.__eq__(other)
  class FancyControl(MixIn, ClientForm.Control): pass
  class FancyCheckboxControl(MixIn, ClientForm.CheckboxControl): pass
  ..
  ClientForm.Control = FancyControl
  ClientForm.CheckboxControl = FancyCheckboxControl

 That would work -- but there are probably 8 or 10 different
 Control subclasses. It's a bit tedious mixing them all one at a
 time, and you need more inside information (the names of all
 the different subclasses).

 New style classes have a __subclasses__() method that could be used to  
 find all of them (*at a certain moment*) -- but considering all the  
 issues, I think that monkey-patching the base class is the less bad  
 option in this case...

I agree.  Inserting methods into the base class seems to be
working fine, and it's the least messy of the alternatives. I'd
submit a patch for ClientForm, but I don't know if my
definition of equal for a form/control is generally useful
enough to warrant being added to the package.

FWIW, I'm using it for automated regression-testing on a
product containing a web server.  Basically, I perform an
operation on the product, and then check to make sure that only
certain web pages/form/controls changed in the manner they
should have.

-- 
Grant Edwards   grante Yow! ... the HIGHWAY is
  at   made out of LIME JELLO and
   visi.commy HONDA is a barbequeued
   OYSTER!  Yum!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Returning different types based on input parameters

2009-04-08 Thread George Sakkis
On Apr 7, 3:18 pm, Adam Olsen rha...@gmail.com wrote:

 On Apr 6, 3:02 pm, George Sakkis george.sak...@gmail.com wrote:

  For example, it is common for a function f(x) to expect x to be simply
  iterable, without caring of its exact type. Is it ok though for f to
  return a list for some types/values of x, a tuple for others and a
  generator for everything else (assuming it's documented), or it should
  always return the most general (iterator in this example) ?

 For list/tuple/iterable the correlation with the argument's type is
 purely superficial, *because* they're so compatible.  Why should only
 tuples and lists get special behaviour?  Why shouldn't every other
 argument type return a list as well?

That's easy; because the result might be infinite. In which case you
may ask why shouldn't every argument type return an iterator then,
and the reason is usually performance; if you already need to store
the whole result sequence (e.g. sorted()), why return just an iterator
to it and force the client to copy it to another list if he needs
anything more than iterating once over it ?

 A counter example is python 3.0's str/bytes functions.  They're
 mutually incompatible and there's no default.

As already mentioned, another example is filter() that tries to match
the input sequence type and falls back to list if it fails.

  To take it further, what if f wants to return different types,
  differing even in a duck-type sense? That's easier to illustrate in a
  API-extension scenario. Say that there is an existing function `solve
  (x)` that returns `Result` instances.  Later someone wants to extend f
  by allowing an extra optional parameter `foo`, making the signature
  `solve(x, foo=None)`. As long as the return value remains backward
  compatible, everything's fine. However, what if in the extended case,
  solve() has to return some *additional* information apart from
  `Result`, say the confidence that the result is correct ? In short,
  the extended API would be:

      def solve(x, foo=None):
          '''
          @rtype: `Result` if foo is None; (`Result`, confidence)
  otherwise.
          '''

  Strictly speaking, the extension is backwards compatible; previous
  code that used `solve(x)` will still get back `Result`s. The problem
  is that in new code you can't tell what `solve(x,y)` returns unless
  you know something about `y`. My question is, is this totally
  unacceptable and should better be replaced by a new function `solve2
  (x, foo=None)` that always returns (`Result`, confidence) tuples, or
  it might be a justifiable cost ? Any other API extension approaches
  that are applicable to such situations ?

 At a minimum it's highly undesirable.  You lose a lot of readability/
 maintainability.  solve2/solve_ex is a little ugly, but that's less
 overall, so it's the better option.

That's my feeling too, at least in a dynamic language. For a static
language that allows overloading, that should be a smaller (or perhaps
no) issue.

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


Re: SoHo Book Problem

2009-04-08 Thread David C. Ullrich
Never mind (at least tentatively).

Later in the day I got an email from the publisher,
saying they're going to send me a corrected copy
free.

Evidently if you get a bad copy you don't have to complain
to the publisher or the retailer, you just have to post
a complaint somewhere where Google can see it...

DU.

In article dullrich-5ea218.10405607042...@text.giganews.com,
 David C. Ullrich dullr...@sprynet.com wrote:

 Just curious - has anyone else bought the printed
 Python 3 Reference Manual published by SoHo Books?
 
 Talking about what they call Part 2 of their Python
 Documentation. I haven't looked in detail - Part 1
 seems fine, but the typesetting in Part 2 is totally
 screwed up.
 
 I mean totally - on more or less every page there are lines
 that are unreadable because there are words printed on top
 of each other instead of next to each other!
 
 On the one hand I don't see how the problem could be with
 just my copy. On the other hand I don't see how they could
 _all_ be like mine - that would mean nobody even _glanced_
 at what was coming out of the press. So I'm curious whether
 anyone else has a copy.
 
 (I know it's all online. Some people like _books_...)
 
 DU.

-- 
David C. Ullrich
--
http://mail.python.org/mailman/listinfo/python-list


Re: more fun with iterators (mux, demux)

2009-04-08 Thread Neal Becker
pataphor wrote:

 On 07 Apr 2009 02:05:59 GMT
 Steven D'Aprano ste...@remove.this.cybersource.com.au wrote:
 
 The demuxer can't be an iterator, since it needs to run through the
 entire collection.
 
 Then your demuxer obviously cannot handle infinite sequences.
  
 def demux(it, n):
 collectors = [[] for i in xrange(n)]
 i = 0
 for item in it:
 collectors[i].append(item)
 i = (i+1) % n
 return tuple([iter(x) for x in collectors])
 
 But this one can:
 
 from collections import deque
 from itertools import cycle, izip, count, islice
 
 def mux(*iterables):
 for it in izip(*iterables):
 for item in it:
 yield item
 
 def demux(seq,n):
 it = iter(seq)
 Q = [deque() for i in xrange(n)]
 CQ = cycle(Q)
 def gen(D):
 for x,C in izip(it,CQ):
 C.appendleft(x)
 while D:
 yield D.pop()
 while D:
 yield D.pop()
 return map(gen,Q)
 
 def test():
 a = count(10)
 b = count(20)
 c = count (30)
 x = demux(mux(a,b,c),3)
 for e in x:
 print list(islice(e,0,10))
 
 if __name__=='__main__':
 test()
 
 P.
 --
 http://mail.python.org/mailman/listinfo/python-list

What was wrong with this one?

def demux(iterable, n):
return tuple(islice(it, i, None, n) for (i, it) in 
enumerate(tee(iterable, n)))





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


Simple CGI request and Python reply

2009-04-08 Thread Greg Corradini

Hello,
I'm trying to implement something very simple without using a Python
WebFramework and I need some advice. I want to send a comma delimited string
from the client to a server-side Python script. My initial plan was to use a
JavaScript function (see below) called makerequest that creates a
XMLHttpRequest object and GETs the output from a Python script. I've used
this function before to field requests  (in those cases the parameter data
passed in the XMLHttpRequest.send() method is null). So I thought I could
just pass some data in and be able to retrieve it with Python. I'm not sure
how to do this. I've used forms with cgi/Python before. However, I don't
want to use a form here. I want Python to handle the data variable being
passed without looking for field names using .FieldStorage(). Can that be
done?

Maybe making a request is not the quickest route to do what I want.  Ideas?

function makerequest(serverPage,objID,data)
{
var obj = document.getElementById(objID);
xmlhttp.open(GET,serverPage);
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4  xmlhttp.status == 200)
{
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(data);
}


-- 
View this message in context: 
http://www.nabble.com/Simple-CGI-request-and-Python-reply-tp22952274p22952274.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: CGIXMLRPCRequestHandler example

2009-04-08 Thread O.R.Senthil Kumaran
On Apr 5, 12:24 pm, a...@pythoncraft.com (Aahz) wrote:
 [posted  e-mailed, please respond on-group]

There was some problem with the CGIXMLRPCRequestHandler code in the
SimpleXMLRPC Server.
It was not getting the length to read from the CONTENT_LENGTH
environement variable ( as it the CGI server was doing).

It was fixed during PyCon sprints:
http://svn.python.org/view?view=revrevision=70940
--
http://mail.python.org/mailman/listinfo/python-list


Re: genetic algorithms in Python?

2009-04-08 Thread Mohammed Mediani
I have done something in this direction. I will be happy to share my
experience. However, my code is not generic and needs many things to be
manually introduced. My GA is standard (selection by roulette wheel or
tournament, single point cross). Let me know if you are interested!

On Wed, Apr 8, 2009 at 3:25 PM, Esmail ebo...@hotmail.com wrote:

 Hello,

 Anyone using Python for coding up genetic algorithms? If
 so, would you share your favorite modules/libraries/tools?

 Thanks,
 Esmail

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

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


Re: Some test fail on my new Python 2.6

2009-04-08 Thread Sorin Schwimmer

Thanks for the pointers.

Here are some answers:

 Ok, so DBM wasn't built because it couldn't find the external symbol
 'dbm_firstkey'.  I have no idea off the top of my head why that would
 happen, but I don't think you really care at the moment since you are
 trying to get tkinter working.  If you do care we can come back to that.
Although I can live without it, I do use sometime dbm. And then, again,
there are other ways to accomplish the same, so it's not critical.

 building '_tkinter' extension
 gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall 
 -Wstrict-prototypes -DWITH_APPINIT=1 -DWITH_BLT=1 -I/usr/X11R6/include -I. 
 -I/install/Python-2.6.1/./Include -I. -IInclude -I./Include 
 -I/usr/local/include -I/install/Python-2.6.1/Include -I/install/Python-2.6.1 
 -c /install/Python-2.6.1/Modules/_tkinter.c -o 
 build/temp.linux-i686-2.6/install/Python-2.6.1/Modules/_tkinter.o
 gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall 
 -Wstrict-prototypes -DWITH_APPINIT=1 -DWITH_BLT=1 -I/usr/X11R6/include -I. 
 -I/install/Python-2.6.1/./Include -I. -IInclude -I./Include 
 -I/usr/local/include -I/install/Python-2.6.1/Include -I/install/Python-2.6.1 
 -c /install/Python-2.6.1/Modules/tkappinit.c -o 
 build/temp.linux-i686-2.6/install/Python-2.6.1/Modules/tkappinit.o
 gcc -pthread -shared 
 build/temp.linux-i686-2.6/install/Python-2.6.1/Modules/_tkinter.o 
 build/temp.linux-i686-2.6/install/Python-2.6.1/Modules/tkappinit.o 
 -L/usr/X11R6/lib64 -L/usr/X11R6/lib -L/usr/local/lib -lBLT -ltk8.5 -ltcl8.5 
 -lX11 -o build/lib.linux-i686-2.6/_tkinter.so
 *** WARNING: renaming _tkinter since importing it failed: libtk8.5.so: 
 cannot open shared object file: No such file or directory
 Now, this one is clear.  It couldn't find libtk8.5.so when it tried to
 use _tkinter.so.  So either that symlink doesn't exist, or points to a
 nonexistent library, or there's something wrong with your load library
 path, so that python isn't finding it when it tries to do the load.
 If you don't know what that last one means, check out 'man ldconfig'.

# pwd
/usr/local/lib
# ls
libpq.so.4libtcl8.4.so  libtclstub8.4.a  libtk8.4.so  libtkstub8.4.a  
python2.4  tcl8.4  tclConfig.sh  tk8.5
libpq.so.4.0  libtcl8.5.so  libtclstub8.5.a  libtk8.5.so  libtkstub8.5.a  tcl8  
 tcl8.5  tk8.4 tkConfig.sh

It's there!

 test_multiprocessing
 test_multiprocessing skipped -- OSError raises on RLock creation, see issue 
 3111!
 According to the referenced bug, this may be a result of your not having
 /dev/shm mounted, but in any case it is more a bug in the tests than a
 bug in your system or setup.

# mount
/dev/hda3 on / type reiserfs (rw,noatime)
proc on /proc type proc (rw)
sysfs on /sys type sysfs (rw)
udev on /dev type tmpfs (rw,nosuid)
devpts on /dev/pts type devpts (rw)
shm on /dev/shm type tmpfs (rw,noexec,nosuid,nodev)
usbfs on /proc/bus/usb type usbfs (rw,devmode=0664,devgid=85)

It's there, but if it is about a known bug in the test, maybe we should just 
ignore it?

 test_socket
 test test_socket failed -- Traceback (most recent call last):
   File /install/Python-2.6.1/Lib/test/test_socket.py, line 474, in 
 testSockName
 my_ip_addr = socket.gethostbyname(socket.gethostname())
 gaierror: [Errno -2] Name or service not known
 This probably means that you haven't properly defined 'localhost'
 in your /etc/hosts file.

# cat /etc/hosts
# /etc/hosts
#
# This file describes a number of hostname-to-address
# mappings for the TCP/IP subsystem.  It is mostly
# used at boot time, when no name servers are running.
# On small systems, this file can be used instead of a
# named name server.  Just add the names, addresses
# and any aliases to this file...
#

127.0.0.1   localhost
# IPV6 versions of localhost and co
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts


There is a localhost definition. Is it not correct?

 test_sys
 test test_sys failed -- Traceback (most recent call last):
   File /install/Python-2.6.1/Lib/test/test_sys.py, line 354, in test_43581
 self.assert_(sys.__stdout__.encoding == sys.__stderr__.encoding)
 AssertionError
 This one is puzzling.  Did you modify 'site.py'?  Or perhaps you
 redirected stdout and stderr to different places and they
 wound up with different encodings for some reason.  In which
 case that one would be a bug in the tests as well.

No, I didn't, nor have I done anything with stdout, stderror. When I ran the 
test, I did a make test | tee test.rez, which in my mind should have been 
harmless.

The output for individual test_httpservers was posted here:
http://mail.python.org/pipermail/python-list/2009-April/708041.html

Thanks again
SxN


  __
Yahoo! Canada Toolbar: Search from anywhere on the web, and bookmark your 
favourite sites. Download it now
http://ca.toolbar.yahoo.com.
--

Re: Scraping a web page

2009-04-08 Thread Iain King
On Apr 7, 1:44 pm, Tim Chase python.l...@tim.thechases.com wrote:
  f = urllib.urlopen(http://www.google.com;)
  s = f.read()

  It is working, but it's returning the source of the page. Is there anyway I
  can get almost a screen capture of the page?

 This is the job of a browser -- to render the source HTML.  As
 such, you'd want to look into any of the browser-automation
 libraries to hook into IE, FireFox, Opera, or maybe using the
 WebKit/KHTML control.  You may then be able to direct it to
 render the HTML into a canvas you can then treat as an image.

 Another alternative might be provided by some web-services that
 will render a page as HTML with various browsers and then send
 you the result.  However, these are usually either (1)
 asynchronous or (2) paid services (or both).

 -tkc

WX can render html.
--
http://mail.python.org/mailman/listinfo/python-list


Python 3.0 online docs broken

2009-04-08 Thread Jim Garrison

Jim Garrison wrote:

Ye Liu wrote:

On Apr 6, 6:33 pm, Jim Garrison j...@acm.org wrote:

I notice the online docs (at docs.python.org/3.0/index.html) were
updated today.  It seems some of the top-level pages, like
Tutorial, Using Python, Language Reference are truncated
after the first few paragraphs.


Yea, same here. Hope it's going to be fixed soon.


Still broken.  I've emailed webmaster(at)python.org


I'm still seeing only stubs for many of the doc pages at
docs.python.org. For example

http://docs.python.org/3.0/tutorial/index.html

This page stops at the sentence The Glossary is also worth going 
through. whereas it used to be followed by a hyperlinked table of

contents for all the tutorial pages.

I emailed the webmaster but have received no response.

Am I the only one seeing this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: genetic algorithms in Python??

2009-04-08 Thread Esmail

Hello Mohammed,

Yes, that would great. While I am comfortable with GAs,
I'm still rather inexperienced with Python so seeing some
implementation examples would be very useful.

Thanks,
Esmail

--

Date: Wed, 8 Apr 2009 17:08:48 +0200
Subject: Re: genetic algorithms in Python?
From: medmedi...@gmail.com
To: ebo...@hotmail.com
CC: python-list@python.org

I have done something in this direction. I will be happy to share my 
experience. However, my code is not generic and needs many things to be 
manually introduced. My GA is standard (selection by roulette wheel or 
tournament, single point cross). Let me know if you are interested!



On Wed, Apr 8, 2009 at 3:25 PM, Esmail ebo...@hotmail.com wrote:

Hello,

Anyone using Python for coding up genetic algorithms? If
so, would you share your favorite modules/libraries/tools?


Thanks,
Esmail


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


how to get back an object from its id() value

2009-04-08 Thread TP
Hi everybody,

I have a data structure (a tree) that has one constraint: I can only store
strings in this data structure.

To know if an object foo already exists in memory, I store str(id(foo)) in
the data structure.
OK.

But how do I get a usable reference from the id value?
For example, if foo has a method bar(), how can I call foo.bar()
from str(id(foo)) (say, 149466208).

Thanks in advance,

Julien

-- 
python -c print ''.join([chr(154 - ord(c)) for c in '*9(9(18%.\
91+,\'Z4(55l4('])

When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong. (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


How to ignore white space changes using difflib?

2009-04-08 Thread Grant Edwards
I'm trying to use difflib to compare strings ignoring changes
to white-space (space/tab).  According to the doc page, you can
do this by specifying a charjunk parameter to filter out
characters:

   charjunk: A function that accepts a character (a string of
   length 1), and returns if the character is junk, or false if
   not. The default is module-level function
   IS_CHARACTER_JUNK(), which filters out whitespace characters
   (a blank or tab; note: bad idea to include newline in
   this!).

But, I simply can't get it to work.  I get exactly the same
results with or without white-space filtering:

Here's my test program:

   #!/usr/bin/python
   import difflib
   
   d1 = [this is string one,this is string   two,this is string three]
   d2 = [this is string one,this  is  string two,this is string three]
   
   def iswhite(c):
   return c in  \t
   
   print no filtering
   delta = difflib.ndiff(d1,d2)
   
   for line in delta:
   print line
   print 
   print
   print IS_CHARACTER_JUNK
   delta = difflib.ndiff(d1,d2,charjunk=difflib.IS_CHARACTER_JUNK)
   
   for line in delta:
   print line
   print 
   print
   print iswhite
   delta = difflib.ndiff(d1,d2,charjunk=iswhite)
   
   for line in delta:
   print line
   print 
   

And here's the output:

   no filtering
 this is string one
   - this is string   two
   ?--
   
   + this  is  string two
   ?  +  +
   
 this is string three
   
   
   IS_CHARACTER_JUNK
 this is string one
   - this is string   two
   ?--
   
   + this  is  string two
   ?  +  +
   
 this is string three
   
   
   iswhite
 this is string one
   - this is string   two
   ?--
   
   + this  is  string two
   ?  +  +
   
 this is string three
   

What am I doing wrong?   

-- 
Grant Edwards   grante Yow! I'll show you MY
  at   telex number if you show me
   visi.comYOURS ...
--
http://mail.python.org/mailman/listinfo/python-list


Floor value in math operators

2009-04-08 Thread Avi
Hi,

This will be a very simple question to ask all the awesome programmers
here:

How can I get answer in in decimals for such a math operator:

3/2

I get 1. I want to get 1.5

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


Re: Floor value in math operators

2009-04-08 Thread Chris Rebert
On Wed, Apr 8, 2009 at 9:03 AM, Avi avinashr...@gmail.com wrote:
 Hi,

 This will be a very simple question to ask all the awesome programmers
 here:

 How can I get answer in in decimals for such a math operator:

 3/2

 I get 1. I want to get 1.5

Add the following line to the top of your program (or use Python 3.0+):
from __future__ import division

To get integer division when this is enabled, use the integer division
operator, //
e.g. x = 3//2 #x=1

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get back an object from its id() value

2009-04-08 Thread CTO
 But how do I get a usable reference from the id value?
 For example, if foo has a method bar(), how can I call foo.bar()
 from str(id(foo)) (say, 149466208).

can you just use a weakref instead? It is certainly cleaner than
trying to store id's,
since an id is only guaranteed to be unique for the lifetime of the
object in question,
and the only way I know of correlating id's to objects involves some C-
level trickery.

for completeness- the trickery: http://www.friday.com/bbum/2007/08/24/python-di/
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get back an object from its id() value

2009-04-08 Thread MRAB

TP wrote:

Hi everybody,

I have a data structure (a tree) that has one constraint: I can only store
strings in this data structure.

To know if an object foo already exists in memory, I store str(id(foo)) in
the data structure.
OK.

But how do I get a usable reference from the id value?
For example, if foo has a method bar(), how can I call foo.bar()
from str(id(foo)) (say, 149466208).


You could create a dict with the string as the key and the object as the
value.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get back an object from its id() value

2009-04-08 Thread Gary Herron

TP wrote:

Hi everybody,

I have a data structure (a tree) that has one constraint: I can only store
strings in this data structure.

To know if an object foo already exists in memory, I store str(id(foo)) in
the data structure.
OK.

But how do I get a usable reference from the id value?
For example, if foo has a method bar(), how can I call foo.bar()
from str(id(foo)) (say, 149466208).
  



Short answer:  You can't!

Longer answer:  You still can't, but you may be able to work around it:

(1)  Build up a dictionary in parallel to the structure:
   idMapper[id(foo)] = foo
 and later, index with
   idMapper[int(idString)] to get foo back

(2)  Get a different data structure.  This one is clearly not satisfying 
your needs.


(3)  Pickle (or marshal or serialize as it's also called) your object 
into a (perhaps) long string to store.  When the string is retrieved, 
unpickle to reconstruct an equivalent object.  This new version of the 
original foo may or may not be adequate for your use.




Gary Herron




Thanks in advance,

Julien

  


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


Re: How to ignore white space changes using difflib?

2009-04-08 Thread Grant Edwards
On 2009-04-08, Grant Edwards inva...@invalid wrote:

 I'm trying to use difflib to compare strings ignoring changes
 to white-space (space/tab).  According to the doc page, you
 can do this by specifying a charjunk parameter to filter out
 characters:

charjunk: A function that accepts a character (a string of
length 1), and returns if the character is junk, or false if
not. The default is module-level function
IS_CHARACTER_JUNK(), which filters out whitespace characters
(a blank or tab; note: bad idea to include newline in
this!).

Apparently that filtering out characters doesn't mean that
they're ignored when doing the comparison.  (A bit of a WTF?
if you ask me).  After some more googling, it appears that I'm
far from the first person who interpreted filtered out as
ignored when comparing lines. I'd submit a fix for the doc
page, but you apparently have to be a lot smarter than me to
figure out what filters out means in this context.

I guess I can collapse all whitespace sequences, do the diff on
the collapsed lines, and them map the results back to the
original lines. :/

 What am I doing wrong?

Reading the doc page, apparently. ;)

-- 
Grant Edwards   grante Yow! Not SENSUOUS ... only
  at   FROLICSOME ... and in
   visi.comneed of DENTAL WORK ... in
   PAIN!!!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Floor value in math operators

2009-04-08 Thread Diez B. Roggisch
Avi wrote:

 Hi,
 
 This will be a very simple question to ask all the awesome programmers
 here:
 
 How can I get answer in in decimals for such a math operator:
 
 3/2
 
 I get 1. I want to get 1.5

You don't say which python-version you have. Depending on that, the answer
is different.

In python2.5 and before, dividing two integers will always return an
integer.

So for your problem, you need to do

3.0 / 2.0 

At least one of the involved numbers must be a float.

However, from python2.5 the division operator behavior changed if desired -
if you do

 from __future__ import division
 3 / 2
1.5
 3 // 2
1


you get what you expect. The old division operator is still available, as //

In python2.6 and 3.x, the new behavior is standard.

Diez

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


Re: how to get back an object from its id() value

2009-04-08 Thread CTO
snip
 You could create a dict with the string as the key and the object as the
 value.
/snip

This will create a strong reference to the object, which is (I'm
assuming) undesired behavior.
--
http://mail.python.org/mailman/listinfo/python-list


Re: genetic algorithms in Python??

2009-04-08 Thread R. David Murray
Esmail esmail...@gmail.com wrote:
 Hello Mohammed,
 
 Yes, that would great. While I am comfortable with GAs,
 I'm still rather inexperienced with Python so seeing some
 implementation examples would be very useful.

A google for 'python genetic algorithms' turns up a number
of interesting hits.

I also remember seeing at least one package announced on
python-announce that referred to genetic algorithms,
so you might check the archives of that mailing list
as well.

--
R. David Murray http://www.bitdance.com

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


Re: Python 3.0 online docs broken

2009-04-08 Thread Hendrik van Rooyen
Jim Garrison j...@acm.org

 Jim Garrison wrote:
  Ye Liu wrote:
  On Apr 6, 6:33 pm, Jim Garrison j...@acm.org wrote:
  I notice the online docs (at docs.python.org/3.0/index.html) were
  updated today.  It seems some of the top-level pages, like
  Tutorial, Using Python, Language Reference are truncated
  after the first few paragraphs.
 
  Yea, same here. Hope it's going to be fixed soon.
  
  Still broken.  I've emailed webmaster(at)python.org
 
 I'm still seeing only stubs for many of the doc pages at
 docs.python.org. For example
 
 http://docs.python.org/3.0/tutorial/index.html
 
 This page stops at the sentence The Glossary is also worth going 
 through. whereas it used to be followed by a hyperlinked table of
 contents for all the tutorial pages.
 

When I looked now (6:30 pm in South Africa) the links were back.
The last one is representation error and it was all right when I
clicked on it.

- Hendrik

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


Re: how to get back an object from its id() value

2009-04-08 Thread TP
MRAB wrote:

 You could create a dict with the string as the key and the object as the
 value.

Thanks. But it implies an additional data structure: a dictionnary.
I don't know what is the best:
* using an additional dict and maintaining it
* or using the di module proposed by CTO

If di is reliable, it seems a good solution for my initial constraint
which is the impossibility to store anything but strings in my data
structure.

-- 
python -c print ''.join([chr(154 - ord(c)) for c in '*9(9(18%.\
91+,\'Z4(55l4('])

When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong. (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Floor value in math operators

2009-04-08 Thread Diez B. Roggisch
 
 In python2.6 and 3.x, the new behavior is standard.

Apparently that is nonsense - it seems to be not standard for 2.6. Which
Makes sense I guess.

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


Re: how to get back an object from its id() value

2009-04-08 Thread CTO
 I don't know what is the best:
 * using an additional dict and maintaining it

It works, but as you say, is somewhat inelegant.

 * or using the di module proposed by CTO

Let me be clear: I am not proposing that you use it. It *does* do what
you
ask- but what you are asking is, all by itself, not a good idea. The
dict
is a vastly superior- and standard- solution to the problem of mapping
one object onto another.

 If di is reliable, it seems a good solution for my initial constraint
 which is the impossibility to store anything but strings in my data
 structure.

di is not reliable. Its author says so, and took a lot of heat for not
saying so in Hollywood-sign letters, lit on fire and a thousand feet
tall.

If all you are worried about is storing a string, how about
UserString?

Notice the difference:

 from collections import UserString
 import weakref
 weakref.ref(ABC)
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: cannot create weak reference to 'str' object
 weakref.ref(UserString(ABC))
weakref at 0xb7baef2c; to 'UserString' at 0xb7a330ec


This way you don't have to maintain a dictionary, only store
your string once, and don't have to hack and kludge your way
around id mappings.
--
http://mail.python.org/mailman/listinfo/python-list


asynchronous python call

2009-04-08 Thread joeygartin
Complete newbie, so forgive my improper use of Python terminology.

I am working with Django and I have to send off a number of emails
after a person has filled out a form.  What I want is to make a call
that goes off to form and send the emails and redirect the user to
another view.  I have this working now, but I noticed it is a bit
slow.  So I was hoping there was a way to spin off the process and
redirect the user to the page while the emails are being formed and
sent vs. making the page hang while it is done.

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


Re: Python syntax

2009-04-08 Thread Mensanator
On Apr 7, 11:39 pm, Lawrence D'Oliveiro l...@geek-
central.gen.new_zealand wrote:
 In message mailman.3514.1239161591.11746.python-l...@python.org, Steve

 Holden wrote:
  Lawrence D'Oliveiro wrote:

  In message 7dd228af-
  e549-444d-8623-11e951851...@y9g2000yqg.googlegroups.com, janus99 wrote:

  I messed around with my own comp (windos xp) command prompt ...

  Try a Linux command prompt. You'll learn a bit more that way.

  Great advice when Linux is available, but somewhat fatuous for a Windows
  user.

 How hard is it to install Cygwin

It's actually quite difficult. Even if you think ahead and
ask that the various compilers are to be installed, that won't
include various utilities like make (which are part of a
different install component).

It takes a lot of trial and error trying to get, say, GMP
to compile.

 or download a live CD?

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


Re: how to get back an object from its id() value

2009-04-08 Thread CTO
Correction: the UserString will be dead on the final line. When I
typed
it in I had a strong reference still hanging around.
--
http://mail.python.org/mailman/listinfo/python-list


Re: 3D plotting in a GUI

2009-04-08 Thread Baris Demir

Stef Mientki wrote:

Baris Demir wrote:

Hi all,

I need to develop a GUI for some scientific data processing 
operations and this GUI should work well with a 3D plotting module, 
also with NumPy and SciPy for sure. I made a search about packages 
but, there are plenty of these modules available. What kind of a 
package or a package of packages might be the best way  for this  
work. BTW I do not want to use MayaVi. It is too much actually.

What do you mean by too much actually ?
What's the GUI you had in mind ?
What kind of scientific data processing do you've in mind ?

cheers,
Stef


I am quite experienced about python programming but this is going to be 
my first GUI design. I need to draw some 2D graphs (also capability for 
3D graphs might be very delicious) and do some mathematical operations 
on them like adding, substracting, smoothing, integration, detecting 
peak points and marking them, fourier transformations and etc. on 
WindowsXP.  And then I want to convert this python code into a .exe by 
using py2exe. I said Mayavi is too much for me because I thought that it 
would be more likeyl to have problems while using a big package like 
MayaVi with py2exe.


Thanks in advance.
BD

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


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



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


Re: Floor value in math operators

2009-04-08 Thread David Smith
Avi wrote:
 Hi,
 
 This will be a very simple question to ask all the awesome programmers
 here:
 
 How can I get answer in in decimals for such a math operator:
 
 3/2
 
 I get 1. I want to get 1.5
 
 Thanks in advance,
 Avi

I'm going to assume your operands are variables instead of numeric
literals.  Why not consider doing a type conversion to float or Decimal
and then perform the division?

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


Re: Some test fail on my new Python 2.6

2009-04-08 Thread R. David Murray
Sorin Schwimmer sx...@yahoo.com wrote:
 
 Thanks for the pointers.
 
 Here are some answers:
 
  Ok, so DBM wasn't built because it couldn't find the external symbol
  'dbm_firstkey'.  I have no idea off the top of my head why that would
  happen, but I don't think you really care at the moment since you are
  trying to get tkinter working.  If you do care we can come back to that.

 Although I can live without it, I do use sometime dbm. And then, again,
 there are other ways to accomplish the same, so it's not critical.

OK, so we'll come back to it later.

  *** WARNING: renaming _tkinter since importing it failed: libtk8.5.so: 
  cannot open shared object file: No such file or directory

  Now, this one is clear.  It couldn't find libtk8.5.so when it tried to
  use _tkinter.so.  So either that symlink doesn't exist, or points to a
  nonexistent library, or there's something wrong with your load library
  path, so that python isn't finding it when it tries to do the load.
  If you don't know what that last one means, check out 'man ldconfig'.
 
 # pwd
 /usr/local/lib
 # ls
 libpq.so.4libtcl8.4.so  libtclstub8.4.a  libtk8.4.so  libtkstub8.4.a  
 python2.4  tcl8.4  tclConfig.sh  tk8.5
 libpq.so.4.0  libtcl8.5.so  libtclstub8.5.a  libtk8.5.so  libtkstub8.5.a  
 tcl8   tcl8.5  tk8.4 tkConfig.sh
 
 It's there!

Well, there is _something_ there.  Maybe it's a symbolic link that
doesn't point anywhere?  Do ls -l, and/or 'file' on it just to check.
The above message is what you would get if it were a symbolic link
that didn't point anywhere valid.

Oh, and make sure /usr/local/lib is in your /etc/ld.so.conf file.  If
it isn't, then that's your problem.  If you need to update that
file I'm pretty sure you need to run ldconfig afterwards.

  test_multiprocessing
  test_multiprocessing skipped -- OSError raises on RLock creation, see 
  issue 3111!
  According to the referenced bug, this may be a result of your not having
  /dev/shm mounted, but in any case it is more a bug in the tests than a
  bug in your system or setup.
 
 # mount
 /dev/hda3 on / type reiserfs (rw,noatime)
 proc on /proc type proc (rw)
 sysfs on /sys type sysfs (rw)
 udev on /dev type tmpfs (rw,nosuid)
 devpts on /dev/pts type devpts (rw)
 shm on /dev/shm type tmpfs (rw,noexec,nosuid,nodev)
 usbfs on /proc/bus/usb type usbfs (rw,devmode=0664,devgid=85)
 
 It's there, but if it is about a known bug in the test, maybe we should just 
 ignore it?

Yeah.  Or download 2.6.2c1 and see if that has the same problem.  The bug
doesn't say that it was fixed in 2.6.2, and the conditional skip is
still there in the test, but I know Jesse was doing work in that area,
so it might get past it on 2.6.2.

On the other hand, if you aren't using multiprocessing you don't need
to worry about it.

  test_socket
  test test_socket failed -- Traceback (most recent call last):
File /install/Python-2.6.1/Lib/test/test_socket.py, line 474, in 
  testSockName
  my_ip_addr = socket.gethostbyname(socket.gethostname())
  gaierror: [Errno -2] Name or service not known
  This probably means that you haven't properly defined 'localhost'
  in your /etc/hosts file.
 
 # cat /etc/hosts
 # /etc/hosts
 #
 # This file describes a number of hostname-to-address
 # mappings for the TCP/IP subsystem.  It is mostly
 # used at boot time, when no name servers are running.
 # On small systems, this file can be used instead of a
 # named name server.  Just add the names, addresses
 # and any aliases to this file...
 #
 
 127.0.0.1   localhost
 # IPV6 versions of localhost and co
 ::1 ip6-localhost ip6-loopback
 fe00::0 ip6-localnet
 ff00::0 ip6-mcastprefix
 ff02::1 ip6-allnodes
 ff02::2 ip6-allrouters
 ff02::3 ip6-allhosts
 
 
 There is a localhost definition. Is it not correct?

Yes, but...I just did the functions on my own machine and got this:

Python 2.6.1 (r261:67515, Mar 26 2009, 08:03:17) 
[GCC 4.1.2 (Gentoo 4.1.2)] on linux2
Type help, copyright, credits or license for more information.
 import socket
 socket.gethostname()
'partner'
 socket.gethostbyname('partner')
'127.0.0.1'
 
So I suspect that you need to add your hostname to the 'localhost' line in
order to get that test to pass.  Mine looks like this:

127.0.0.1   partner.bitdance.com partner localhost

I'm inclined to call that a bug in the tests.  You could file a bug
report if you feel so moved :)

  test_sys
  test test_sys failed -- Traceback (most recent call last):
File /install/Python-2.6.1/Lib/test/test_sys.py, line 354, in 
  test_43581
  self.assert_(sys.__stdout__.encoding == sys.__stderr__.encoding)
  AssertionError
  This one is puzzling.  Did you modify 'site.py'?  Or perhaps you
  redirected stdout and stderr to different places and they
  wound up with different encodings for some reason.  In which
  case that one would be a bug in the tests as well.
 
 No, I didn't, nor have I done anything with stdout, stderror. When I ran the 
 

Re: How to ignore white space changes using difflib?

2009-04-08 Thread Duncan Booth
Grant Edwards inva...@invalid wrote:

 Apparently that filtering out characters doesn't mean that
 they're ignored when doing the comparison.  (A bit of a WTF?
 if you ask me).  After some more googling, it appears that I'm
 far from the first person who interpreted filtered out as
 ignored when comparing lines. I'd submit a fix for the doc
 page, but you apparently have to be a lot smarter than me to
 figure out what filters out means in this context.

So far as I can see from looking at the code:

Once if you have identified one block of lines as having been replaced by 
another the matcher can then give you additional information by marking up 
the changes within each line. However it only makes sense to do that if the 
lines are still somewhat similar.

'charjunk' is used to remove junk characters before scanning the lines 
within a replacement block and the most similar lines (if they are 
sufficiently similar) are then chosen for this extra step of comparing the 
character changes within the line.

Here's an example. If I do this:

 print ''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1),
   'one\nwot\ntoo\nthree\n'.splitlines(1)))
  one
- two
? -
+ wot
?   +
+ too
  three

The comparison detected that two was replaced by 2 lines wot and too. 
It decided the first of these was the best match for the original line so 
it shows character level difference between the original and the first 
replacement line.


 print ''.join(Differ(charjunk=lambda c:c=='w')
  .compare('one\ntwo\nthree\n'.splitlines(1),
   'one\nwot\ntoo\nthree\n'.splitlines(1)))
  one
+ wot
- two
?  ^
+ too
?  ^
  three

This time we told the system that we don't care about 'w' in either the 
original or replacement text. That means instead of seeing which of wot 
and too is closest to two it looks to see which of ot and too is 
closest to to. ot has two changes but too only has one, so this time 
it does the detailed comparison between the original line and the second 
line of the output. N.B. The junk function is only used to decide which 
lines to use for the detailed comparison: the original lines are still used 
for the comparison itself.
--
http://mail.python.org/mailman/listinfo/python-list


Re: more fun with iterators (mux, demux)

2009-04-08 Thread pataphor
On Wed, 08 Apr 2009 10:51:19 -0400
Neal Becker ndbeck...@gmail.com wrote:

 What was wrong with this one?
 
 def demux(iterable, n):
 return tuple(islice(it, i, None, n) for (i, it) in 
 enumerate(tee(iterable, n)))

Nothing much, I only noticed after posting that this one handles
infinite sequences too. For smallish values of n it is acceptable. 

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


Re: 3D plotting in a GUI

2009-04-08 Thread Stef Mientki

Baris Demir wrote:

Stef Mientki wrote:

Baris Demir wrote:

Hi all,

I need to develop a GUI for some scientific data processing 
operations and this GUI should work well with a 3D plotting module, 
also with NumPy and SciPy for sure. I made a search about packages 
but, there are plenty of these modules available. What kind of a 
package or a package of packages might be the best way  for this  
work. BTW I do not want to use MayaVi. It is too much actually.

What do you mean by too much actually ?
What's the GUI you had in mind ?
What kind of scientific data processing do you've in mind ?

cheers,
Stef


I am quite experienced about python programming but this is going to 
be my first GUI design. I need to draw some 2D graphs (also capability 
for 3D graphs might be very delicious) and do some mathematical 
operations on them like adding, substracting, smoothing, integration, 
detecting peak points and marking them, fourier transformations and 
etc. on WindowsXP.  And then I want to convert this python code into a 
.exe by using py2exe. I said Mayavi is too much for me because I 
thought that it would be more likeyl to have problems while using a 
big package like MayaVi with py2exe.
Two obvious choices are wxPython + MatPlotLib and/or VPython or PyQt, 
depends on what license you're after.
Maybe interesting to know that a number of guys are creating MatLab-like 
environements, search the scipy newsgroup.
You can also find some m-file to numpy converters (in case you might 
have m-files already).
And I can assure you, there are 2 packages which will give you trouble 
with py2exe: numpy and matplotlib.


btw if you choose wxPython, download the demo first, and you might even 
be interested in a simpler way to create GUIs,

http://mientki.ruhosting.nl/data_www/pylab_works/pw_gui_support.html

good luck,
Stef

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


Re: how to get back an object from its id() value

2009-04-08 Thread Christian Heimes
TP wrote:
 If di is reliable, it seems a good solution for my initial constraint
 which is the impossibility to store anything but strings in my data
 structure.

'di' is dangerous and not reliable. When the original object is freed,
then the memory address may be used by another Python object, point to
an invalid Python object or some random bytes. You can easily mess up or
seg fault the Python interpreter. 'di' is an evil debugging hack that
may proof useful as last resort.

Do *not* use anything like 'di' in production code.

Christian


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


Re: asynchronous python call

2009-04-08 Thread Tino Wildenhain

Hi,

joeygartin wrote:

Complete newbie, so forgive my improper use of Python terminology.

I am working with Django and I have to send off a number of emails
after a person has filled out a form.  What I want is to make a call
that goes off to form and send the emails and redirect the user to
another view.  I have this working now, but I noticed it is a bit
slow.  So I was hoping there was a way to spin off the process and
redirect the user to the page while the emails are being formed and
sent vs. making the page hang while it is done.


You best bet would be something like Zope's asynchronous mail handler
which is simply a queue Folder where you write the mail to be send
and having an outside process completely independend to scan for new
mail to be send out from time to time. If you want to speed up the
pickup time you could have the mail sender process open a socket (UDP
for example) where you can ping once you wrote out the mails to be send.

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


Re: Module caching

2009-04-08 Thread Aaron Scott
 Anyway, this person also posted on mod_python list. One of the things
 I highlighted there was that mod_python for some configurations is
 multithreaded and as such they may not be properly protecting
 variables if they are storing them at global scope. They haven't
 responded to any comments about it on mod_python list. They were also
 told to read:

  http://www.dscpl.com.au/wiki/ModPython/Articles/TheProcessInterpreter...

 Graham

Thanks, Graham. Sorry I didn't respond -- it's crunch time here, so I
was pulled off the project for a couple days to help with something
else. I just didn't have time to catch up.

In the end, we decided to convert everything from mod_python to CGI,
which ended up getting us the functionality we were looking for. For
development, MaxRequestsPerChild was already set to 1, but this didn't
solve any of the variable caching issues.

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


Re: Q: Best book for teaching

2009-04-08 Thread Joel Koltner
Lawrence D'Oliveiro l...@geek-central.gen.new_zealand wrote in message 
news:grhq75$eb...@lust.ihug.co.nz...
 I thought that a good introduction might be to show them how HTML works, and
 progress from there to embedding little bits of JavaScript.

 Nothing to do with Python I know, but might be a possibility.

If you want to emphasize web usage, I'd be tempted to show them a bit of HTML 
and then introduce them to CGI-bin scripts... written in Python.

Something like Django might be fun to show as well, although such full 
featured content management systems are really a course unto themselves. 
(And if you're used Python scripts on the server and played with, e.g., MySQL 
a little, it'll be clear that things like Django are just greatly expanded 
versions of what they're doing themselves.)

---Joel


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


Computed attribute names

2009-04-08 Thread Dale Amon
There are a number of things which I have been used
to doing in other OO languages which I have not yet
figured out how to do in Python, the most important
of which is passing method names as args and inserting
them into method calls. Here are two cases I have been
trying to figure out for a current project. 

The first is passing methods to dispatcher methods. In
pseudocode, something like this:

def dispatcher(self,methodname):
self.obj1.methodname()
self.obj2.methodname()

and another case is selecting behavior of an object by
setting a type string, with pseudo code like this:

self.IBM029 = re.compile([^acharset]
self.IBM026 = re.compile([^anothercharset]
self.type = IBM029
errs  = self.(self.type).findall(aCardImage)

I have yet to find any way to do either, although it appears
I could do some of it using a long and roundabout call string
using __dict__.

What is the Python dialect for this sort of runtime OO? 





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


Re: Computed attribute names

2009-04-08 Thread Albert Hopkins
On Wed, 2009-04-08 at 19:47 +0100, Dale Amon wrote:
 There are a number of things which I have been used
 to doing in other OO languages which I have not yet
 figured out how to do in Python, the most important
 of which is passing method names as args and inserting
 them into method calls. Here are two cases I have been
 trying to figure out for a current project. 
 
 The first is passing methods to dispatcher methods. In
 pseudocode, something like this:
 
 def dispatcher(self,methodname):
 self.obj1.methodname()
 self.obj2.methodname()

The built-in getattr() function:

def dispatcher(self, methodname):
getattr(self.obj1, methodname)()
getattr(self.obj2, methodname)()


 and another case is selecting behavior of an object by
 setting a type string, with pseudo code like this:
 
 self.IBM029 = re.compile([^acharset]
 self.IBM026 = re.compile([^anothercharset]
 self.type = IBM029
 errs  = self.(self.type).findall(aCardImage)

Same:

errs = getattr(self, self.type).findall(aCardImage)



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


Re: Computed attribute names

2009-04-08 Thread paul

Dale Amon schrieb:

There are a number of things which I have been used
to doing in other OO languages which I have not yet
figured out how to do in Python, the most important
of which is passing method names as args and inserting
them into method calls. Here are two cases I have been
trying to figure out for a current project. 


The first is passing methods to dispatcher methods. In
pseudocode, something like this:

def dispatcher(self,methodname):
self.obj1.methodname()
self.obj2.methodname()


I'd say you can use:

method = getattr(self.obj1, 'methodname')
method()

It will raise AttributeError if 'methodname' is not found or the 
(optional) third argument to getattr()



and another case is selecting behavior of an object by
setting a type string, with pseudo code like this:

self.IBM029 = re.compile([^acharset]
self.IBM026 = re.compile([^anothercharset]
self.type = IBM029
errs  = self.(self.type).findall(aCardImage)

same here, or use a class/module-level dict like

symbol_table = {
  'IBM029': re.compile([^...]),
  'IBM026': re.compile([^...])
}

and symbol_table[self.type].findall(something)

cheers
 Paul



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


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


Re: Computed attribute names

2009-04-08 Thread Dale Amon
On Wed, Apr 08, 2009 at 09:03:00PM +0200, paul wrote:
 I'd say you can use:

Thanks. I could hardly ask for a faster response on a
HowTo than this!



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


Re: Q: Best book for teaching

2009-04-08 Thread tkp...@hotmail.com
I taught myself Python from Python Programming for the Absolute
Beginner by Michael Dawson (which has been mentioned above) and with
lots of help from the friendly members of this group, but there's now
a free e-book titled Snake Wrangling for Kids by Jason Briggs. You can
view it at http://www.briggs.net.nz/log/writing/snake-wrangling-for-kids/.
There are versions for Windows, Mac and Linux, though it is focused on
Python 2.x.

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


Re: Painful?: Using the ast module for metaprogramming

2009-04-08 Thread Martin v. Löwis
 I see how it avoids needing to look at the parent node in general, but
 if we were compiling by recursively descending through the AST, then
 we would know whether Name's would be loads or stores by the time we
 got to them (we would already had to have visited an encompassing
 assignment or expression)

Python's compiler does recursively descend. However, it is still
more convenient to allow uniform processing of expressions, rather
than having parameters passed down into the visitor functions.

 except in the case of your a = b = c
 expression, which I'm curious how Python handles. The natural answer
 is for assignment to be an expression (so b = c returns the new value
 of b). But Python doesn't do that, so then I'd expect we'd have some
 third ast.LoadAndStore() option for b, but examining ast.parse's
 behavior it looks like it chooses Store...

No, the value of b is never read in this assignment. I'm not quite
sure whether you are aware what the *actual* semantics of this
assignment is; it is equivalent to

 tmp = c
 a = tmp
 b = tmp

(so the assignment to a happens first), and neither a nor b is
being read. So it's simple stores into both a and b.

 -Why can't orelse for ast.If and ast.While default to empty []?
 You want to store None? That would be a type error; orelse is
 specified as stmt*. So it must be a list.
 
 A list is actually what I want, an empty one. The problem is that
 ast.While and ast.If's constructors default to the opposite,
 orelse=None. Same with keywords and args for ast.Call. Admittedly,
 adding orelse=[] to the constructor calls isn't terribly burdensome,
 but it does make already obfuscated looking AST mangling code even
 worse.

Ah, that could be fixed. Please contribute a patch.

 -Why can't I eval a functiondef to get back a function object?
 Because a definition is not an expression. You can only eval
 expressions.
 
 I understand that if function definitions were expressions, because of
 the whitespace syntax there wouldn't be a way to express an assignment
 to such an expression. But, why would it be problematic to let them be
 expressions anyway?

This would be a significant change to the compiler, which would have
to learn what bytecodes to compile it to. Feel free to discuss this
on python-ideas.

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


Testing the new version of Psyco

2009-04-08 Thread Baz Walter

hello

i recently tried out this new version of psyco...

http://www.voidspace.org.uk/python/weblog/arch_d7_2009_03_14.shtml#e1063

...because of the new support for generators. the above link says To 
use and test generators, create preferences.py, following the 
instructions in setup.py - except there's nothing obvious in setup.py 
that refers to generators.


anyway, i created a preferences.py file (with PSYCO_DEBUG = 1) and ran 
psycobench against python-2.5/psyco-1.6 and python-2.6/psyco-2.0 with 
the following results (output has been cropped slightly):


# start output

[benchmark]$ python2.5 psycobench.py -m time_generators time_anyall
Running new timings with original psyco

send call loop 1000 plain: 3.30  psyco: 3.29  ratio: 1.00
send and loop 1000  plain: 3.28  psyco: 3.27  ratio: 1.00
send just many timesplain: 1.28  psyco: 0.56  ratio: 2.29 *
iterate just many times plain: 0.67  psyco: 0.57  ratio: 1.19 *
call next just many times   plain: 0.85  psyco: 0.63  ratio: 1.35 *
all_bool_genexp plain: 2.03  psyco: 2.31  ratio: 0.88
all_bool_listcomp   plain: 2.94  psyco: 1.01  ratio: 2.91
all_genexp  plain: 1.71  psyco: 1.97  ratio: 0.87
all_listcompplain: 2.70  psyco: 0.73  ratio: 3.71
all_loopplain: 1.09  psyco: 0.08  ratio: 13.15
any_bool_genexp plain: 2.03  psyco: 2.45  ratio: 0.83
any_bool_listcomp   plain: 2.89  psyco: 0.97  ratio: 2.99
any_genexp  plain: 1.74  psyco: 1.84  ratio: 0.95
any_listcompplain: 2.65  psyco: 0.72  ratio: 3.69
any_loopplain: 1.08  psyco: 0.08  ratio: 13.10

[benchmark]$ python2.6 psycobench.py -m time_generators time_anyall
Running new timings with python2.6/site-packages/psyco/_psyco.so

send call loop 1000 plain: 2.85  psyco: 0.04  ratio: 67.90
send and loop 1000  plain: 2.85  psyco: 0.04  ratio: 65.00
send just many timesplain: 1.17  psyco: 0.87  ratio: 1.35
iterate just many times plain: 0.64  psyco: 0.86  ratio: 0.74
call next just many times   plain: 0.77  psyco: 0.87  ratio: 0.89
all_bool_genexp plain: 1.87  psyco: 1.98  ratio: 0.95
all_bool_listcomp   plain: 2.54  psyco: 0.66  ratio: 3.84
all_genexp  plain: 1.69  psyco: 1.77  ratio: 0.95
all_listcompplain: 2.38  psyco: 0.52  ratio: 4.55
all_loopplain: 1.07  psyco: 0.08  ratio: 14.24
any_bool_genexp plain: 1.87  psyco: 1.99  ratio: 0.94
any_bool_listcomp   plain: 2.57  psyco: 0.68  ratio: 3.76
any_genexp  plain: 1.74  psyco: 1.82  ratio: 0.95
any_listcompplain: 2.47  psyco: 0.53  ratio: 4.66
any_loopplain: 1.07  psyco: 0.07  ratio: 14.65

# end output

with the obvious exception of the the first two tests for psyco v2, the 
results (for generators) seem a little underwhelming. in fact, psyco v1 
does significantly better on three of the tests (marked with an 
asterisk) and for the others there's not much difference.


this makes me wonder whether i enabled generators properly in psyco v2 
when i compiled it. has anybody else tried out this new version of psyco 
and got better overall results for generators? also, those first two 
results for v2 look really odd - what could explain the huge difference 
relative to the other generator tests for v2?


(p.s. i re-ran the tests and got very similar results)

--
Baz Walter

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


Re: asynchronous python call

2009-04-08 Thread Aahz
In article 637028a0-58b9-4912-896d-2b17e1341...@q16g2000yqg.googlegroups.com,
joeygartin  joeygar...@gmail.com wrote:

I am working with Django and I have to send off a number of emails
after a person has filled out a form.  What I want is to make a call
that goes off to form and send the emails and redirect the user to
another view.  I have this working now, but I noticed it is a bit
slow.  So I was hoping there was a way to spin off the process and
redirect the user to the page while the emails are being formed and
sent vs. making the page hang while it is done.

The simplest solution is to create an external program and use the
subprocess module to call it.  You could also use fork() directly, but
that's more complicated.
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons.  --Aahz
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 online docs broken

2009-04-08 Thread Benjamin Kaplan
On Wed, Apr 8, 2009 at 11:28 AM, Jim Garrison j...@acm.org wrote:

 Jim Garrison wrote:

 Ye Liu wrote:

 On Apr 6, 6:33 pm, Jim Garrison j...@acm.org wrote:

 I notice the online docs (at docs.python.org/3.0/index.html) were
 updated today.  It seems some of the top-level pages, like
 Tutorial, Using Python, Language Reference are truncated
 after the first few paragraphs.


 Yea, same here. Hope it's going to be fixed soon.


 Still broken.  I've emailed webmaster(at)python.org


 I'm still seeing only stubs for many of the doc pages at
 docs.python.org. For example

 http://docs.python.org/3.0/tutorial/index.html

 This page stops at the sentence The Glossary is also worth going through.
 whereas it used to be followed by a hyperlinked table of
 contents for all the tutorial pages.

 I emailed the webmaster but have received no response.

 Am I the only one seeing this?


Nope. I have the same problem.


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

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


Re: named pipe and Linux

2009-04-08 Thread Thomas Bellman
Cameron Simpson c...@zip.com.au wrote:

 On 07Apr2009 10:08, akineko akin...@gmail.com wrote:
| I'm trying to use named pipes to fuse a Python program and a C
| program.
| One side creates pipes using os.mkfifo() and both sides use the same
| named pipes (one side reads, another side writes). The read side uses
| select.select() to wait for incoming messages and read the message
| when select.select() says it is ready.
| The length of the message is unknown to the read side.

 That's a serious flaw in the message protocol.

| I cannot use file.read() because it will block waiting for an EOF.
| I cannot use file.readline() because how many lines have arrived is
| unknown.
| So, I needed to use os.read() with the exact number of characters to
| read.

 No!

 You should use os.read() with the maximum size of a message.
 It _should_ return with the number of bytes in the message, provided the
 C program writes messages with a single OS-level write() call.

No!

That's still broken.  You can't know if the writer has managed to
write one or several messages onto the pipe.  And if the messages
are large, you aren't guaranteed that the OS won't split up the
data into multiple segments that only become available to the
reader one or a few at a time.

You *need* to use a protocol where it is possible to determine
the message boundaries.  You can do that by:

- Using messages of a fixed size.

- Terminate each message with an octet sequence that cannot occur
  within a message.  For example, a linefeed without a backslash
  before it (and you would probably want a way to escape the
  backslash, in case you want to end a message with a backslash).

- Have small header of a fixed size at the start of each message,
  that includes the length of the message in octets.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
Life IS pain, highness.  Anyone who tells   !  bellman @ lysator.liu.se
 differently is selling something.  !  Make Love -- Nicht Wahr!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Some test fail on my new Python 2.6

2009-04-08 Thread Sorin Schwimmer

Hello again,

/usr/local/lib is in /etc/ld.so.conf. The files are real. However,
creating symlinks in /usr/lib targeting the libraries in /usr/local/lib,
then recompiling, solved the tkinter problem. So, the conclusion is that
only /usr/lib is consulted for the tcl/tk libraries.

multiprocessing - do I need it? Probably not. I can fork() a new process,
so I can manage. I don't know what am I loosing without multiprocessing.

socket was solved as suggested, by adding the host name in /etc/hosts, like 
this:
127.0.0.1  localhost dsr-1

sys doesn't fail anymore after recompilation (have no clue why).

htttpservers is still failing the same.

Everything is done as root.

I'll move on with make install.

Thanks for your help; I'm progressing :-)

SxN


  __
Instant Messaging, free SMS, sharing photos and more... Try the new Yahoo! 
Canada Messenger at http://ca.beta.messenger.yahoo.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Q: Best book for teaching

2009-04-08 Thread JBW
On Mon, 06 Apr 2009 07:37:19 -0700, grkuntzmd wrote:

 What would be a good book to use as the text for the course?

Python Programming: An Introduction to Computer Science
Franklin, Beedle  Associates, by little Johny Zelle.

Accept no substitues!

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


Re: extract Infobox contents

2009-04-08 Thread J. Cliff Dyer
On Wed, 2009-04-08 at 01:57 +0100, Rhodri James wrote:
 On Tue, 07 Apr 2009 12:46:18 +0100, J. Clifford Dyer  
 j...@sdf.lonestar.org wrote:
 
  On Mon, 2009-04-06 at 23:41 +0100, Rhodri James wrote:
  On Mon, 06 Apr 2009 23:12:14 +0100, Anish Chapagain
  anishchapag...@gmail.com wrote:
 
   Hi,
   I was trying to extract wikipedia Infobox contents which is in format
   like given below, from the opened URL page in Python.
  
   {{ Infobox Software
   | name   = Bash
 [snip]
   | latest release date= {{release date|mf=yes|2009|02|20}}
   | programming language   = [[C (programming language)|C]]
   | operating system   = [[Cross-platform]]
   | platform   = [[GNU]]
   | language   = English, multilingual ([[gettext]])
   | status = Active
 [snip some more]
   }} //upto this line
  
   I need to extract all data between {{ Infobox ...to }}
 
 [snip still more]
 
  You end up with 'infoboxes' containing a list of all the infoboxes
  on the page, each held as a list of the lines of their content.
  For safety's sake you really should be using regular expressions
  rather than 'startswith', but I leave that as an exercise for the
  reader :-)
 
 
  I agree that startswith isn't the right option, but for matching two
  constant characters, I don't think re is necessary.  I'd just do:
 
  if '}}' in line:
  pass
 
  Then, as the saying goes, you only have one problem.
 
 That would be the problem of matching lines like:
 
   | latest release date= {{release date|mf=yes|2009|02|20}}
 
 would it? :-)
 

That's the one.

 A quick bit of timing suggests that:
 
if line.lstrip().startswith(}}):
  pass
 
 is what we actually want.
 

Indeed.  Thanks.

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


str object is not callable error

2009-04-08 Thread venkat sanaka
HIi everyone.
i was using python/c api to call a python function from c and I know the
name of the function which i want to call.Is there any way to do that??
This is the method i tried...

for eg:This is the python function i wants to call.
 def add(x):
...   return x+10


This is my code in C:
PyObject *result = NULL;
int arg;
PyObject *arglist;
arg = 123;
my_callback = add;
arglist = Py_BuildValue((i), arg);
result = PyObject_CallObject(my_callback, arglist);
Py_DECREF(arglist);
return result;

I was getting a error like str object is not callable.From the error i
came to know that i was assigning add as a string which caused this
error.Then how to make it a callable object??

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


Re: more fun with iterators (mux, demux)

2009-04-08 Thread Miles
On Wed, Apr 8, 2009 at 1:21 PM, pataphor wrote:
 On Wed, 08 Apr 2009 10:51:19 -0400 Neal Becker wrote:

 What was wrong with this one?

 def demux(iterable, n):
     return tuple(islice(it, i, None, n) for (i, it) in
 enumerate(tee(iterable, n)))

 Nothing much, I only noticed after posting that this one handles
 infinite sequences too. For smallish values of n it is acceptable.

I assume that smallish values of n refers to the fact that
itertools.tee places items into every generator's internal deque,
which islice then skips over, whereas your version places items only
into the deque of the generator that needs it.  However, for small n,
the tee-based solution has the advantage of having most of the work
done in C instead of in Python generator functions; in my limited
benchmarking, the point where your version becomes faster is somewhere
around n=65.

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


nested looping

2009-04-08 Thread PK
So I'm trying to see whats the cleanest way to do this:

I have a

checklist = [ax, bx, by, cy  ..] (a combination of a,b,c with x and y,
either both on one)

allist = [a,b,c,]
xlist = [x, y, ..]

now I wanna loop through alist and xlist and see if the combination
exists in checklist

so something like,

for alpha in alist:
for xy in xlist:
if alpha+xy not in checklist:
missing.append(alpha)

now the problem is I want to include alpha in missing list only if
none of the combinations from xlist with alpha are in checklist.

The above will exclude the possibility where ax doesn't exist but ay
or az does exist.

Hope There is a cleaner way to accomplish this.

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


Character strings / Python 3.0 C API

2009-04-08 Thread rch . astra
Hi everybody,

I'm doing some experiments with the python 3.0 C API, and I'm having
some problems for obtaining character strings. In python 2.X APIs, a
function called PyString_AsString was available. This function
provided a C string (char*) given a PyObject. But, in python 3.0 API
there is no such a function, and they mention that it has been
substituted by PyUnicode* functions. The issue is that I still don't
get how to use these functions to obtain char strings in C!

This is one of the things I try to do:

PyThreadState* state = PyThreadState_GET();
PyInterpreterState* interp = state-interp;
int numModules = PyDict_Size(interp-modules);

PyObject* moduleKeys = PyDict_Keys(interp-modules);
int idx=0;
for(idx=0; idxnumModules; idx++)
{
PyObject* key = PyList_GetItem(moduleKeys,idx);
PyObject* module = PyDict_GetItem( interp-modules, key );
char* theKeyName = 
PySys_WriteStdout(Module '%s'\n, theKeyName);
}

I was not able to obtain theKeyName, knowing that the key PyObject
is in fact a unicode string containing the character string I want...

Could anybody help me? How can I, in general, obtain char* strings
from a corresponding PyObject? What should I use for ?

Thank you very much in advance,

Cheers

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


Re: genetic algorithms in Python?

2009-04-08 Thread Terry Reedy

Esmail wrote:

Hello,

Anyone using Python for coding up genetic algorithms? If
so, would you share your favorite modules/libraries/tools?


Search 'Python genetic algorithm' on Google or elsewhere.

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


Re: genetic algorithms in Python??

2009-04-08 Thread Esmail

R. David Murray wrote:

Esmail esmail...@gmail.com wrote:

Hello Mohammed,

Yes, that would great. While I am comfortable with GAs,
I'm still rather inexperienced with Python so seeing some
implementation examples would be very useful.


A google for 'python genetic algorithms' turns up a number
of interesting hits.


Agreed .. I did that and came up with a number of hits, but the
problem :-) with Python is a plethora of choices, so I wasn't
quite sure which of the finds might be the most promising/useful.

Nothing like a testimony from someone who uses or has used a tool.


I also remember seeing at least one package announced on
python-announce that referred to genetic algorithms,
so you might check the archives of that mailing list
as well.


Yes, that's a good idea, thanks,
Esmail

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


Re: genetic algorithms in Python?

2009-04-08 Thread Esmail

Terry Reedy wrote:

Esmail wrote:

Hello,

Anyone using Python for coding up genetic algorithms? If
so, would you share your favorite modules/libraries/tools?


Search 'Python genetic algorithm' on Google or elsewhere.


Hi Terry,

I did that first, and I came up with a number of hits. The problem
with Python is that there's so much available and it's sometimes hard
to decide what to select, so I was looking for some folks who had
use some of the tools and could share their experiences.

Esmail

ps: the problem is a good thing to have all things considered :-)

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


Re: Character strings / Python 3.0 C API

2009-04-08 Thread Martin v. Löwis
 PyObject* key = PyList_GetItem(moduleKeys,idx);
 PyObject* module = PyDict_GetItem( interp-modules, key );
 char* theKeyName = 
 PySys_WriteStdout(Module '%s'\n, theKeyName);
 }
 I was not able to obtain theKeyName, knowing that the key PyObject
 is in fact a unicode string containing the character string I want...

Use PyUnicode_AsUTF8String.

 Could anybody help me? How can I, in general, obtain char* strings
 from a corresponding PyObject? What should I use for ?

In general, this is much more difficult. If the object is an integer
(say), or a file object - what is the char* that you want to get?
You would need to call PyObject_Str first, getting str() (or repr())
of the object, and then use PyUnicode_AsUTF8String (releasing
the _Str result afterwards).

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


Re: nested looping

2009-04-08 Thread Terry Reedy

PK wrote:

So I'm trying to see whats the cleanest way to do this:

I have a

checklist = [ax, bx, by, cy  ..] (a combination of a,b,c with x and y,
either both on one)


Since you will be repeatedly looking for items in checklist, I suggest 
making it a set instead.



allist = [a,b,c,]
xlist = [x, y, ..]

now I wanna loop through alist and xlist and see if the combination
exists in checklist

so something like,

for alpha in alist:
for xy in xlist:
if alpha+xy not in checklist:
missing.append(alpha)


This will append alpha multiple times.  Not what you want.


now the problem is I want to include alpha in missing list only if
none of the combinations from xlist with alpha are in checklist.


for xy in xlist:
  if alpha+xy in checklist: break
else:
  missing.append(alpha) # or missing.add(alpha) if missing a set

tjr

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


Re: more fun with iterators (mux, demux)

2009-04-08 Thread Raymond Hettinger
[Miles]
 I assume that smallish values of n refers to the fact that
 itertools.tee places items into every generator's internal deque,
 which islice then skips over, whereas your version places items only
 into the deque of the generator that needs it.

The pure python equivalent listed in the docs uses separate
deques for each subiterator, but the actual C implementation
of itertools.tee() only has one internal deque that is shared
by all of the sub-iterators.


Raymond

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


Re: Character strings / Python 3.0 C API

2009-04-08 Thread rch . astra
Sorry but it did not help... I tried this:

PyObject* key = PyList_GetItem(moduleKeys,idx);
char* theKeyName = PyUnicode_AsUTF8String( key );

And this, just in case:

PyObject* key = PyList_GetItem(moduleKeys,idx);
char* theKeyName = PyUnicode_AsUTF8String( PyObject_Str
(key) );

(Although it should work in the first case since key is suposed to be
a string already, the module name). In all the cases, I obtained an
empty string when using theKeyName:

PySys_WriteStdout(Module '%s'\n, theKeyName);

The issue is that all PyUnicode* functions are returning PyObjects.
PyString_AsString return value was char*. Is there any real equivalent
of this function?

Thanks again. Best regards,

RC

On 8 abr, 23:35, Martin v. Löwis mar...@v.loewis.de wrote:
          PyObject* key = PyList_GetItem(moduleKeys,idx);
          PyObject* module = PyDict_GetItem( interp-modules, key );
          char* theKeyName = 
          PySys_WriteStdout(Module '%s'\n, theKeyName);
      }
  I was not able to obtain theKeyName, knowing that the key PyObject
  is in fact a unicode string containing the character string I want...

 Use PyUnicode_AsUTF8String.

  Could anybody help me? How can I, in general, obtain char* strings
  from a corresponding PyObject? What should I use for ?

 In general, this is much more difficult. If the object is an integer
 (say), or a file object - what is the char* that you want to get?
 You would need to call PyObject_Str first, getting str() (or repr())
 of the object, and then use PyUnicode_AsUTF8String (releasing
 the _Str result afterwards).

 Regards,
 Martin

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


Re: Character strings / Python 3.0 C API

2009-04-08 Thread Martin v. Löwis
 The issue is that all PyUnicode* functions are returning PyObjects.
 PyString_AsString return value was char*. Is there any real equivalent
 of this function?

Ah, right. PyString_AsUTF8String returns a bytes object, to which you
need to apply PyBytes_AsString to. At the end, you need to decref the
bytes object.

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


Re: nested looping

2009-04-08 Thread Matimus
On Apr 8, 2:15 pm, PK superp...@gmail.com wrote:
 So I'm trying to see whats the cleanest way to do this:

 I have a

 checklist = [ax, bx, by, cy  ..] (a combination of a,b,c with x and y,
 either both on one)

 allist = [a,b,c,]
 xlist = [x, y, ..]

 now I wanna loop through alist and xlist and see if the combination
 exists in checklist

 so something like,

 for alpha in alist:
     for xy in xlist:
         if alpha+xy not in checklist:
             missing.append(alpha)

 now the problem is I want to include alpha in missing list only if
 none of the combinations from xlist with alpha are in checklist.

 The above will exclude the possibility where ax doesn't exist but ay
 or az does exist.

 Hope There is a cleaner way to accomplish this.

 Thanks in advance,
 PK

That code doesn't look too bad. It is fairly readable. There are
several ways to accomplish this though. If you aren't interested in
duplicate values or order then sets would be a good option.

something like this:

missing = set(alpha + xy for alpha in alist for xy in xlist).difference
(checklist)

if you are using 2.6 you could also make use of the product generator
in itertools:

from itertools import product
missing = set(''.join(p) for p in product(alist, xlist)).difference
(checklist)

If you could adapt your code to use tuples instead of strings you
could do it like this:

missing = set(product(alist, xlist)).difference(checklist)




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


Re: Character strings / Python 3.0 C API

2009-04-08 Thread rch . astra
Thank you very much for your help Martin, now I got it.

Cheers,

RC

On 9 abr, 00:05, Martin v. Löwis mar...@v.loewis.de wrote:
  The issue is that all PyUnicode* functions are returning PyObjects.
  PyString_AsString return value was char*. Is there any real equivalent
  of this function?

 Ah, right. PyString_AsUTF8String returns a bytes object, to which you
 need to apply PyBytes_AsString to. At the end, you need to decref the
 bytes object.

 Regards,
 Martin

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


Decompression with zlib

2009-04-08 Thread Emma Li

Hello,

I'm trying to do compression/decompression of stuff with zlib, and I  
just don't get it...
Here is an example. I assume that dec should be a, but it isn't. dec  
turns out to be an empty string, and I don't understand why...


===
import zlib
compressor = zlib.compressobj(6) # level
decompressor = zlib.decompressobj() # wbits

cmpr = compressor.compress(a)
print compressed, len(cmpr)
dec = decompressor.decompress(cmpr)
print decompressed, len(dec)

# unconsumed tail and unused data
print decompressor.unconsumed_tail, decompressor.unconsumed_tail
##print decompressor.unused_data, decompressor.unused_data

dec += decompressor.flush()
print after flushing, len(dec)
===

Any help is appreciated.
Emma
--
http://mail.python.org/mailman/listinfo/python-list


Re: nested looping

2009-04-08 Thread Luis Alberto Zarrabeitia Gomez

Quoting PK superp...@gmail.com:

 So I'm trying to see whats the cleanest way to do this:
 
 I have a
 
 checklist = [ax, bx, by, cy  ..] (a combination of a,b,c with x and y,
 either both on one)
 
 allist = [a,b,c,]
 xlist = [x, y, ..]
 
[...]
 now the problem is I want to include alpha in missing list only if
 none of the combinations from xlist with alpha are in checklist.

This is untested:

for alpha in alist:
for xy in xlist:
if alpha+xy in checklist:
break
else:
missing.append(alpha)

(note that the else is for the for, not the if)

You could also try the any/all functions from python2.5:

for alpha in alist:
if not any(alpha + xy in checklist for xy in xlist):
missing.append(alpha)


Or the really not recommended one-liner:

missing = [alpha for alpha in alist if not any(alpha + xy in checklist for xy in
xlist)]

(remember, all of this is untested)

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie


-- 
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba 
http://www.universidad2010.cu

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


  1   2   >