Socket Troubles

2005-08-28 Thread Chris Spencer
I've written a simple class to manage P2P socket connections. However, 
whenever I try to receive data, the socket raises an exception with the 
error message  (11, 'Resource temporarily unavailable').

My code's fairly straight-forward, with much of it right out of the 
Python docs, so I'm not sure what I'm doing wrong. You can see it all at 
http://deadbeefbabe.org/paste/1525/0

Any help is immensely appreciated.

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


Re: Socket Troubles

2005-08-28 Thread Chris Spencer
Chris Spencer wrote:
> I've written a simple class to manage P2P socket connections. However, 
> whenever I try to receive data, the socket raises an exception with the 
> error message  (11, 'Resource temporarily unavailable').
> 
> My code's fairly straight-forward, with much of it right out of the 
> Python docs, so I'm not sure what I'm doing wrong. You can see it all at 
> http://deadbeefbabe.org/paste/1525/0
> 
> Any help is immensely appreciated.
> 
> Thanks,
> Chris

One more thing. The code I posted is also a complete demo of my problem. 
Run the script in two different terminals simultaneously, like
script.py 8000 8001
and
script.py 8001 8000

They should then try talking to each other, reproducing the problem.

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


Re: Windows/win32all, unicode and long filenames

2005-08-28 Thread Do Re Mi chel La Si Do
Hi !


You are true.
But, more, don't believe : for use with CD-Rom/DVD, a path cannot to have 
more than 64 caracteres.


@-salutations

Michel Claveau 


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


Re: problems with tarfile.open and tar.bz2

2005-08-28 Thread Lars Gustäbel
On Fri, 26 Aug 2005 09:05:29 -0700, justin.vanwinkle wrote:

> Hello everyone,
> 
> I need some tar functionality for my program.  Currently the following
> code properly displays tar archives, and tar.gz archives.  However, it
> chokes on tar.bz2 archives with the following error:
> 
>   File "mail_filter.py", line 262, in extract_archive
> tar_archive = tarfile.open('', 'r', fileobj)
>   File "/usr/lib/python2.3/tarfile.py", line 900, in open
> return func(name, "r", fileobj)
>   File "/usr/lib/python2.3/tarfile.py", line 980, in bz2open
> raise ValueError, "no support for external file objects"
> ValueError: no support for external file objects

The problem here is that the bz2.BZ2File class that tarfile.py uses to
access tar.bz2 files has no support for an external file-object argument.
In contrast to gzip.GzipFile, it works solely on real files.
This limitation is somewhat annoying, but so far no one took the trouble
changing the bz2 module.

If your program does not rely on random access to the tar.bz2 file, you
can still use the "r|bz2" stream mode:

tar_archive = tarfile.open(mode="r|bz2", fileobj=StringIO.StringIO(attach))
for tarinfo in tar_archive:
print tarinfo.name
print tar_archive.extractfile(tarinfo).read()
tar_archive.close()

-- 
Lars Gustäbel
[EMAIL PROTECTED]

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


py to exe: suggestions?

2005-08-28 Thread chris patton
I need to convert a python file to an '.exe'. I've tried py2exe, and I
don't like it because you have to include that huge dll and libraries.

Thanks for the Help!!

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


Re: py to exe: suggestions?

2005-08-28 Thread Sybren Stuvel
chris patton enlightened us with:
> I need to convert a python file to an '.exe'. I've tried py2exe, and
> I don't like it because you have to include that huge dll and
> libraries.

Then what would you expect? The whole Python interpreter is needed if
you want to run Python programs. It's more a smart packaging process
than a compilation of Python code into an executable.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


What are new-style classes?

2005-08-28 Thread Vaibhav
I recently heard about 'new-style classes'. I am very sorry if this
sounds like a newbie question, but what are they? I checked the Python
Manual but did not find anything conclusive. Could someone please
enlighten me? Thanks!

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


Re: py to exe: suggestions?

2005-08-28 Thread Ben Finney
chris patton <[EMAIL PROTECTED]> wrote:
> I need to convert a python file to an '.exe'.

A Python program is executable only in the context of a Python
interpreter. Python is a dynamic language; it can't be compiled to
native machine code.

> I've tried py2exe, and I don't like it because you have to include
> that huge dll and libraries.

That's the Python interpreter environment, and the standard Python
library that is made available in the Python environment. Without
them, your program isn't executable.

What were you hoping for?

-- 
 \   "If trees could scream, would we be so cavalier about cutting |
  `\   them down? We might, if they screamed all the time, for no good |
_o__) reason."  -- Jack Handey |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What are new-style classes?

2005-08-28 Thread Robert Kern
Vaibhav wrote:
> I recently heard about 'new-style classes'. I am very sorry if this
> sounds like a newbie question, but what are they? I checked the Python
> Manual but did not find anything conclusive. Could someone please
> enlighten me? Thanks!

There's a link on the left sidebar of http://docs.python.org

http://www.python.org/doc/newstyle.html

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Dynamic image creation for the web...

2005-08-28 Thread Tompa
Hi,

I would like to create images on the fly as a response to an http request.
I can do this with PIL like this (file create_gif.py):
from PIL import Image, ImageDraw

print 'Status: 200 OK'
print 'Content-type: text/html'
print
print 'Python Dynamic Image Creation Test'
print ''
im = Image.new("P", (600, 400))
draw = ImageDraw.Draw(im)
draw.rectangle((0, 0) + im.size, fill="blue")
im.save("images/tmp.gif");
print ''
print ''


However, I would like to 1) avoid saving the image in a file on disk and 
2) separate the HTLM code from the python image creation code. 

Something like this is what I have in mind:
(file index.html):


 Python Dynamic Image Creation




and in file create_image.py:
from PIL import Image, ImageDraw, ImageFont
im = Image.new("P", (600, 400))
draw = ImageDraw.Draw(im)
draw.rectangle((0, 0) + im.size, fill="blue")


Unfortunately this does not work :-(
What is missing?

Thanks in advance!
/Tompa


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


Re: Dynamic image creation for the web...

2005-08-28 Thread Richard Lewis

On Sun, 28 Aug 2005 09:50:17 + (UTC), "Tompa" <[EMAIL PROTECTED]>
said:
> Hi,
> 
> I would like to create images on the fly as a response to an http
> request.
> I can do this with PIL like this (file create_gif.py):
> from PIL import Image, ImageDraw
> 
> print 'Status: 200 OK'
> print 'Content-type: text/html'
> print
> print 'Python Dynamic Image Creation
> Test'
> print ''
> im = Image.new("P", (600, 400))
> draw = ImageDraw.Draw(im)
> draw.rectangle((0, 0) + im.size, fill="blue")
> im.save("images/tmp.gif");
> print ''
> print ''
> 
> 
> However, I would like to 1) avoid saving the image in a file on disk and 
> 2) separate the HTLM code from the python image creation code. 
> 
> Something like this is what I have in mind:
> (file index.html):
> 
> 
>  Python Dynamic Image Creation
> 
> 
> 
> 
> and in file create_image.py:
> from PIL import Image, ImageDraw, ImageFont
> im = Image.new("P", (600, 400))
> draw = ImageDraw.Draw(im)
> draw.rectangle((0, 0) + im.size, fill="blue")
> 
> 
> Unfortunately this does not work :-(
> What is missing?
> 
It would be useful to know what web server software you're using. With
Apache you should be able to force it to tell clients that your scripts
are returning images by using the AddType directive form mod_mime
(http://httpd.apache.org/docs/2.0/mod/mod_mime.html.en#addtype).

The other thing you may need to check is the HTTP header of the
generated image. It should be possible to create an HTTP response from
your create_image.py script (as opposed to just an image) with a MIME
type of image/jpeg and manually insert the binary image data in the
response body...

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


Re: Can I send files through xmlrpc connections?

2005-08-28 Thread ookoi
hi,

You can try this recipe, it should provides what you need.

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

The key is: xmlrpclib.Binary(my_file_object.read())

-- 
sébastien
http://yadp.sourceforge.net

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


Re: Socket Troubles

2005-08-28 Thread Peter Hansen
Chris Spencer wrote:
> I've written a simple class to manage P2P socket connections. However, 
> whenever I try to receive data, the socket raises an exception with the 
> error message  (11, 'Resource temporarily unavailable').

I would assume (without looking at your code) that this is equivalent to 
the Windows error "WSAEWOULDBLOCK" (10035) for which Microsoft's docs 
say this:

Resource temporarily unavailable.
 This error is returned from operations on nonblocking sockets that 
cannot be completed immediately, for example recv when no data is queued 
to be read from the socket. It is a nonfatal error, and the operation 
should be retried later. It is normal for WSAEWOULDBLOCK to be reported 
as the result from calling connect on a nonblocking SOCK_STREAM socket, 
since some time must elapse for the connection to be established.


Does that help?  If not, at least provide information about what 
platform you're running on, and preferably post the code, if you can 
reduce it to only a few lines which still reproduces the problem.  Many 
people don't like to spend time downloading code from who knows where 
and attempting to run it on their own machine, but could find the 
problem with a quick inspection of your code if posted here (but not if 
it's hundreds of lines!).

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


Re: py to exe: suggestions?

2005-08-28 Thread gene tani
There's movpy, w/option to exclude Unicode/win98 capabilities:

http://www.voidspace.org.uk/python/movpy/

Also:

http://www.effbot.org/zone/exemaker.htm
http://www.python.org/doc/current/dist/postinstallation-script.html
http://www.jython.org/docs/differences.html

Ben Finney wrote:
> chris patton <[EMAIL PROTECTED]> wrote:
> > I need to convert a python file to an '.exe'.
>
> A Python program is executable only in the context of a Python
> interpreter. Python is a dynamic language; it can't be compiled to
> native machine code.
>
> > I've tried py2exe, and I don't like it because you have to include
> > that huge dll and libraries.
>
> That's the Python interpreter environment, and the standard Python
> library that is made available in the Python environment. Without
> them, your program isn't executable.
>
> What were you hoping for?
>
> --
>  \   "If trees could scream, would we be so cavalier about cutting |
>   `\   them down? We might, if they screamed all the time, for no good |
> _o__) reason."  -- Jack Handey |
> Ben Finney

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


Re: Writing portable applications (Was: Jargons of Info Tech industry)

2005-08-28 Thread Ulrich Hobelmann
Mike Meyer wrote:
>> I'd rather develop a native client for the machine that people
>> actually WANT to use, instead of forcing them to use that
>> little-fiddly web browser on a teeny tiny display.
> 
> You missed the point: How are you going to provide native clients for
> platforms you've never heard of?

Who says I have to?  With open protocols, everybody can.  I know many 
platforms that STILL don't have a browser that would work with most 
websites out there.  They all have NNTP, SMTP and POP clients. 
Text-mode, GUI-mode, your choice.

>> And again: connections might be slow, a compact protocol is better
>> than loading the whole UI every time.  And while Ajax might work,
>> despite the UI being maybe too big for the little browser window, and
>> even if it works, it's still probably more work than a simple, native
>> UI.  First of all it needs to load all the JS on first load, secondly
>> sometimes for a flexible UI you'd have to replace huge parts of the
>> page with something else.  Native UIs are more up to the task.
> 
> I'm not arguing that native UI's aren't better. I'm arguing that web
> applications provide more portability - which is important for some
> applications and some developers.

Like Java provides more portability.  Unless you ran NetBSD in 2003 
(there was no Java back then that worked for me), hm, IRIX?, Plan9, BeOS 
the list goes on...  LOTS of platforms don't have the manpower to 
develop a client that renders all of the huge bloated wagonload of W3C 
tech that was only designed for *markup* from the beginning.

>>> I started writing web apps when I was doing internal tools development
>>> for a software development company that had 90+ different platform
>>> types installed inhouse. It was a *godsend*. By deploying one
>> If that's 90+ GUI platforms, then I agree.
> 
> Why do you care if they are GUI or not? If you need to provide the
> application for them, you need to provide the application for
> them. Them not being GUI just means you can't try and use a standard
> GUI library. It also means you have to know what you're doing when you
> write HTML so that it works properly in a CLUI. But your native app
> would have to have a CLUI anyway.

Ok, UI then ;)
I don't care what UIs people like and use.

>> I just wonder who wrote fully standards compliant web browsers for
>> those 90 platforms.
> 
> Nobody. I doubt there's a fully standards compliant web browser

Nobody, huh?  Then how could you run just ANY web application on those 
platforms?

> available for *any* platform, much less any non-trivial collection of
> them. You write portable web applications to the standards, and design
> them to degrade gracefully. Then you go back and work around any new

Oh right, they degrade gracefully.  So without Javascript or cookies 
(the former is often not implemented) you get a HTML page with an error 
notice -- if you're lucky.

A server AND client for a simple protocol designed for its task (i.e. 
not FTP for instance) can be implemented in much less work than even 
designing even part of a web application backend that does that kind of 
stuff.  Plus you're not bound by HTTP request structure, you can use 
publish/subscribe or whatever communication style you want for efficiency.

> bugs you've uncovered in the most popular browsers - which
> historically are among the *worst* at following standards.
> 
>> If you have one Windows GUI (maybe C#), one Mac GUI (Cocoa), one Gtk
>> GUI for X, you're done.
> 
> You think you're done. A lot of developers think you can stop with the
> first one or two. You're all right for some applications. For others,
> you're not.  Personally, I like applications that run on all the
> platforms I use - and your set doesn't cover all three of those
> systems.

Ok, I'd be interested to hear what those are.  VMS, RiscOS, Mac OS 9...?

>>> well-written app, I could make everyone happy, without having to do
>>> versions for the Mac, Windows, DOS (this was a while ago), getting it
>>> to compile on umpteen different Unix version, as well as making it
>>> work on proprietary workstation OS's.
>> Well, stick to POSIX and X APIs and your stuff should run fine on
>> pretty much all Unices.
> 
> You know, the same kind of advice applies to writing portable web
> apps. Except when you do it with HTML, "portability" means damn near
> any programmable device with a network interface, not some relatively
> small fraction of all deployed platforms.

Only that even years ago lots of even small platforms would run X, but 
even today MANY platforms don't run a browser with XHTML/HTML4+JS+CSS 
(well, okay, the CSS isn't that important).

>> I never understood those people who write all kinds of weird ifdefs
>> to on all Unices. Maybe that was before my time, during the
>> Unix wars, before POSIX.
> 
> There were standards before POSIX. They didn't cover everything people
> wanted to do, or didn't do them as fast as the OS vendor wanted. So
> Unix vendors added their own

Re: Modify a C++ instance from the embed python interpreter

2005-08-28 Thread Wezzy
Diez B. Roggisch <[EMAIL PROTECTED]> wrote:

> Wezzy wrote:
> > Hi, is there a tool that automatically expose an object to python? i
> > have an instance of a C++ (or ObjC) object and i want to pass it to the
> > embed interpreter that runs inside my program.
> > Python code have to call c++ method and register some callback.
> > 
> > I know that swig helps when python creates c++ instance but i've the
> > instance and i want to use it with python.
> 
> That is the same case, wrt SWIG - the objects methods get accessed by
> functions like
> 
> int Object_foo(Object *s) {
>  return s->foo();
> }

Can you post few line of code ?

> So passing a exiting object reference to such a function will work. You
> might also consider using SIP, it appears to me to be much more OO.
> 
> Diez

well i'll look to SIP but i prefer to use swig because it can interface
C++ with other language such as ruby

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


Re: Doubt C and Python

2005-08-28 Thread James Kim
Jeff Schwab wrote:
> 5. Scripting is easier in Python than in Java, particularly with 
> regard to environment variables and process control.
> 
> Of course, these are only my opinions.  I am particularly not an expert 
> on Python or Java.

Note that for Java experts, Jython can be used for interpreting works.
Jython has the same grammer to Python, or CPython, and is also able to 
call Java codes very simply.

See, for example: http://www.jython.org/docs/usejava.html

-James (^o^)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doubt C and Python

2005-08-28 Thread James Kim
Wouter van Ooijen (www.voti.nl) wrote:
> I use Python when my time is most valuable (in most cases it is), in
> the very few cases the computer's time is more valuable I write in
> C/C++.

In cases when the computer's time is more valuable, why not use CPython 
with C/C++ API? Only most time consuming parts can be replaced to C/C++ 
codes so as to increase the speed up to native C/C++ programs).

-James (^o^)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cygwin font problems

2005-08-28 Thread Jason Tishler
Steve,

On Sat, Aug 27, 2005 at 11:43:23PM -0400, Steve Holden wrote:
> Cygwin runs Python 2.4.1, Windows runs 2.4. Any light on this mystery
> gratefully received.

You may get better traction on the Cygwin mailing list.  I recommend
trying there.

Jason

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


Re: Dynamic image creation for the web...

2005-08-28 Thread Benjamin Niemann
Tompa wrote:

> Hi,
> 
> I would like to create images on the fly as a response to an http request.
> I can do this with PIL like this (file create_gif.py):
> from PIL import Image, ImageDraw
> 
> print 'Status: 200 OK'
> print 'Content-type: text/html'
> print
> print 'Python Dynamic Image Creation
> Test' print ''
> im = Image.new("P", (600, 400))
> draw = ImageDraw.Draw(im)
> draw.rectangle((0, 0) + im.size, fill="blue")
> im.save("images/tmp.gif");
> print ''
> print ''
> 
> 
> However, I would like to 1) avoid saving the image in a file on disk and
> 2) separate the HTLM code from the python image creation code.
> 
> Something like this is what I have in mind:
> (file index.html):
> 
> 
>  Python Dynamic Image Creation
> 
> 
> 
> 
> and in file create_image.py:
> from PIL import Image, ImageDraw, ImageFont
> im = Image.new("P", (600, 400))
> draw = ImageDraw.Draw(im)
> draw.rectangle((0, 0) + im.size, fill="blue")
> 
> 
> Unfortunately this does not work :-(
> What is missing?

You are almost there. Your create_image.py does not return anything to the
browser yet.

First return proper HTTP headers, e.g.

sys.stdout.write('Status: 200 OK\r\n')
sys.stdout.write('Content-type: image/gif\r\n')
sys.stdout.write('\r\n')

(Your prints above are mostly equivalent, but do not output the correct \r\n
as line terminator - at least on UNIX style systems. Most webservers
tolarate this, if it's coming from a CGI - but doing it right and not
relying on a certain server behaviour is not bad anyway ;)

Then check the PIL docs to find out, how to output the image to sys.stdout
(instead of writing to a file).

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting from Microsoft Binary Format floats to Python Float

2005-08-28 Thread geskerrett
Well, thank-you again.
It's a bit embarassing, but you are correct ...  It was a typo on in
the sample data.
A bit frustrated with myself as I checked, and double checked, but I
guess became a bit blinded to the problem.

Sorry to waste your time, and appreciate your assistance and patience.

Geoff.

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


Re: Dynamic image creation for the web...

2005-08-28 Thread Max Erickson
Tompa <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Hi,
> 
> I would like to create images on the fly as a response to an http
> request. I can do this with PIL like this (file create_gif.py):
> from PIL import Image, ImageDraw
> 

check out sparklines:

http://bitworking.org/projects/sparklines/

It is a script very similar to what you want to do.

The difference between your script and sparklines is mostly that it 
sends:

print "Content-type: image/png"

instead of:

print 'Content-type: text/html'


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


Re: What are new-style classes?

2005-08-28 Thread Steve Holden
Vaibhav wrote:
> I recently heard about 'new-style classes'. I am very sorry if this
> sounds like a newbie question, but what are they? I checked the Python
> Manual but did not find anything conclusive. Could someone please
> enlighten me? Thanks!
> 
Older Pythons have a dichotomy between programmer-declared object 
classes (from which subclasses can inherit) and the built-in object 
classes (which just existed as built-in, but which could not be used as 
the base of subclasses).

More recently the object hierarchy was redesigned, and now everything 
inherits from object, so (if you know what you are doing) you can 
implement subclasses of the built-in types such as dict, float and str.

Robert Kern has given you a link that explains the situation in detail.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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


NASFiC?

2005-08-28 Thread Aahz
Anyone gonna be at NASFiC next weekend?  Want a get-together?

(NASFiC is a science fiction convention that will be in Seattle this
time; for more info, see http://nasfic.org/)
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

The way to build large Python applications is to componentize and
loosely-couple the hell out of everything.
-- 
http://mail.python.org/mailman/listinfo/python-list


close failed: [Errno 0] No error goes to stdout

2005-08-28 Thread Yoav
I use the following code to the console output:

def get_console(cmd):
 try:
 p_in, p_out, p_err = os.popen3(cmd)
 except:
 pass
 out_str = ''
 for obj in p_out:
 out_str = out_str + obj
 for obj in p_err:
 out_str = out_str + obj
 return out_str


for some reason some exceptions (stderr outputs) are not captured by the 
try method, and slip to the screen. Any one has any idea on how can 
prevent from any output that I don't want to?
The output I get on these exceptions is:
close failed: [Errno 0] No error


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


Release of PyPy 0.7.0

2005-08-28 Thread Carl Friedrich Bolz
pypy-0.7.0: first PyPy-generated Python Implementations
==

What was once just an idea between a few people discussing
on some nested mailing list thread and in a pub became reality ...
the PyPy development team is happy to announce its first
public release of a fully translatable self contained Python
implementation.  The 0.7 release showcases the results of our
efforts in the last few months since the 0.6 preview release
which have been partially funded by the European Union:

- whole program type inference on our Python Interpreter
   implementation with full translation to two different
   machine-level targets: C and LLVM

- a translation choice of using a refcounting or Boehm
   garbage collectors

- the ability to translate with or without thread support

- very complete language-level compliancy with CPython 2.4.1


What is PyPy (about)?


PyPy is a MIT-licensed research-oriented reimplementation of
Python written in Python itself, flexible and easy to
experiment with.  It translates itself to lower level
languages.  Our goals are to target a large variety of
platforms, small and large, by providing a compilation toolsuite
that can produce custom Python versions.  Platform, Memory and
Threading models are to become aspects of the translation
process - as opposed to encoding low level details into a
language implementation itself.  Eventually, dynamic
optimization techniques - implemented as another translation
aspect - should become robust against language changes.

Note that PyPy is mainly a research and development project
and does not by itself focus on getting a production-ready
Python implementation although we do hope and expect it to
become a viable contender in that area sometime next year.


Where to start?
-

Getting started: 
http://codespeak.net/pypy/dist/pypy/doc/getting-started.html

PyPy Documentation: http://codespeak.net/pypy/dist/pypy/doc/

PyPy Homepage:  http://codespeak.net/pypy/

The interpreter and object model implementations shipped with
the 0.7 version can run on their own and implement the core
language features of Python as of CPython 2.4.  However, we still
do not recommend using PyPy for anything else than for education,
playing or research purposes.

Ongoing work and near term goals
-

PyPy has been developed during approximately 15 coding sprints
across Europe and the US.  It continues to be a very
dynamically and incrementally evolving project with many
one-week meetings to follow.  You are invited to consider coming to
the next such meeting in Paris mid October 2005 where we intend to
plan and head for an even more intense phase of the project
involving building a JIT-Compiler and enabling unique
features not found in other Python language implementations.

PyPy has been a community effort from the start and it would
not have got that far without the coding and feedback support
from numerous people.   Please feel free to give feedback and
raise questions.

 contact points: http://codespeak.net/pypy/dist/pypy/doc/contact.html

 contributor list: 
http://codespeak.net/pypy/dist/pypy/doc/contributor.html

have fun,

 the pypy team, of which here is a partial snapshot
 of mainly involved persons:

 Armin Rigo, Samuele Pedroni,
 Holger Krekel, Christian Tismer,
 Carl Friedrich Bolz, Michael Hudson,
 Eric van Riet Paap, Richard Emslie,
 Anders Chrigstroem, Anders Lehmann,
 Ludovic Aubry, Adrien Di Mascio,
 Niklaus Haldimann, Jacob Hallen,
 Bea During, Laura Creighton,
 and many contributors ...

PyPy development and activities happen as an open source project
and with the support of a consortium partially funded by a two
year European Union IST research grant. Here is a list of
the full partners of that consortium:

 Heinrich-Heine University (Germany), AB Strakt (Sweden)
 merlinux GmbH (Germany), tismerysoft GmbH(Germany)
 Logilab Paris (France), DFKI GmbH (Germany)
 ChangeMaker (Sweden), Impara (Germany)
-- 
http://mail.python.org/mailman/listinfo/python-list


NooB Question

2005-08-28 Thread APCass
How do you execute a .py in Linux with KDE?  If I double click on my
program it opens Kwrite, for editing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Socket Troubles

2005-08-28 Thread Michael Sparks
Chris Spencer wrote:
> My code's ... at http://deadbeefbabe.org/paste/1525/0
...
> I've written a simple class to manage P2P socket connections. However,
> whenever I try to receive data, the socket raises an exception with the
> error message  (11, 'Resource temporarily unavailable').

At one point in your code you do this: 
self._socket.setblocking(0)

This says "if we can't recieve or send data without blocking, fail rather 
than succeed". One of the failure modes is to return error 11. This is 
infact normally defined as:
#define EAGAIN  11  /* Try again */

What this means is "sorry, I couldn't do this without blocking right now, 
try again very shortly!".

Looking at your code it continually loops (in BaseConnectionHandler_recv) 
receiving data - whether or not there's any data to receive:
def _recv(self):
while self.running:
try:
data = self._socket.recv(4096)
if not len(data):
time.sleep(0.1)
continue
except Exception, e:
log('Recieve failed for handler',self.address,'because of',e)

break

Since you never actually check to see if the socket is ready to give you
data, and you've set it non-blocking, seeing lots of EAGAIN errors is
pretty much what you'd expect to see. (Simply sleeping is not sufficient!)

I suppose the short answer though really is this: you set the socket
non-blocking, you should therefore expect to see failures telling you
to try again, and follow their advice! :)

Regards,


Michael.

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


Re: Release of PyPy 0.7.0

2005-08-28 Thread Simon Percivall
That's great! Congratulations!

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


Re: py to exe: suggestions?

2005-08-28 Thread Bugs
If your users already have Python installed then you could just create a 
self-extracting, self-executing .exe that contains only your scripts and 
necessary files.  I belive many of the popular zip utilities have the 
ability to do this.  The free info-zip does this as well: 
http://www.info-zip.org (but you have to recompile it with the 
appropriate switch turned on).

If they don't have Python installed then you have no choice but to 
include the python DLLs, libraries, etc. as that's your runtime 
environment necessary to run your Python application.

HTH

chris patton wrote:
> I need to convert a python file to an '.exe'. I've tried py2exe, and I
> don't like it because you have to include that huge dll and libraries.
> 
> Thanks for the Help!!
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: close failed: [Errno 0] No error goes to stdout

2005-08-28 Thread Peter Hansen
Yoav wrote:
> I use the following code to the console output:
> 
> def get_console(cmd):
> try:
> p_in, p_out, p_err = os.popen3(cmd)
> except:
> pass
> out_str = ''
> for obj in p_out:
> out_str = out_str + obj
> for obj in p_err:
> out_str = out_str + obj
> return out_str
> 
> 
> for some reason some exceptions (stderr outputs) are not captured by the 
> try method, and slip to the screen. Any one has any idea on how can 
> prevent from any output that I don't want to?
> The output I get on these exceptions is:
> close failed: [Errno 0] No error

What makes you think the errors are getting past the try/except?  Could 
they be printed by the program you are invoking with popen3() instead? 
What does "cmd" equal when you get this failure?

Maybe you are expecting that popen3() will somehow raise exceptions when 
the called program fails, exceptions which the except statement would 
catch.  That's not the case.

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


Re: Release of PyPy 0.7.0

2005-08-28 Thread Michael Sparks
Carl Friedrich Bolz wrote:
[[... great news ...]]

Would it be useful for people to start trying out their modules/code to see
if they work with this release, and whether they can likewise be translated
using the C/LLVM backends, or would you say this is too early? (I'm more
thinking in terms of it providing real world usecases in the hope of
finding things that don't work - rather than anything else)

Either way, this looks like a great milestone - congratulations to the
entire team. (I remember PyPy being met with skepticism as to whether
it could even be done! :-)

Best Regards,


Michael

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


Re: formal math ?

2005-08-28 Thread William Park
[EMAIL PROTECTED] wrote:
> Hi,
> 
> I have just discovered python and it seems so easy ans so powerful to
> me that it remind me matlab or maple programming language (sorry free
> software purists ears).
> 
> So I was wondering if there a sort of formal math library, that can do
> a thing like:
> 
> lib.solve("x+1=0")
> -> x=-1
> 
> I have checked numarray and I think it can not do this.
> 
> Thanks in advance,

No, you need to type some more. :-)  You need to define function
def f(x):
return x + 1
and call root solver, either from a library or function imported from
module.

For simple cases, I use RPN calculator recently added to Bash shell,
like
rpn 'f(x)= 1 +' 0 1 secant =
rpn 'f(x)= 1 +' 'fd(x)= 1'  0 newton =

-- 
William Park <[EMAIL PROTECTED]>, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
   http://home.eol.ca/~parkw/thinflash.html
BashDiff: Super Bash shell
  http://freshmeat.net/projects/bashdiff/
-- 
http://mail.python.org/mailman/listinfo/python-list


RE:Returned mail: see transcript for details

2005-08-28 Thread MAILsweeper
Please be aware that a message to the following recipient(s) has been blocked 
because it was identified as containing a virus, and your address was specified 
as the sender:

[EMAIL PROTECTED]


This does not necessarily mean that you were the sender, as your address could 
have been chosen at random by the virus.  The chances are that if you do not 
recognise the above recipient's address(es), you can safely ignore this message.

However, you should still make sure you are taking all the usual precautions to 
guard against infection of your computer.

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

Yielding a chain of values

2005-08-28 Thread Talin
I'm finding that a lot of places within my code, I want to return the 
output of a generator from another generator. Currently the only method 
I know of to do this is to explicitly loop over the results from the 
inner generator, and yield each one:

for x in inner():
yield x

I was wondering if there was a more efficient and concise way to do 
this. And if there isn't, then what about extending the * syntax used 
for lists, i.e.:

yield *inner()

The * would indicate that you want to iterate through the given 
expression, and yield each value in turn. You could also use it on 
ordinary lists:

yield *[1, 2, 3 ]

Anyway, just an idle thought on a Sunday morning :)

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


Re: Embedding Python in other programs

2005-08-28 Thread Gregory Piñero
Thanks Ravi, I'll take a look


On 27 Aug 2005 22:55:40 -0700, Ravi Teja <[EMAIL PROTECTED]> wrote:
> http://www.python.org/windows/win32com/QuickStartServerCom.html
> 
> If you are using ActivePython, that tutorial is included (PyWin32
> documentation -> Python COM -> Overviews) along with the needed
> win32all module.
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 


-- 
Gregory Piñero
Chief Innovation Officer
Blended Technologies
(www.blendedtechnologies.com)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Release of PyPy 0.7.0

2005-08-28 Thread Valentino Volonghi aka Dialtone
Michael Sparks <[EMAIL PROTECTED]> wrote:

> Would it be useful for people to start trying out their modules/code to see
> if they work with this release, and whether they can likewise be translated
> using the C/LLVM backends, or would you say this is too early? (I'm more
> thinking in terms of it providing real world usecases in the hope of
> finding things that don't work - rather than anything else)

This is not how it works. Pypy doesn't translate your code to C/LLVM. 
Currently PyPy can only translate a pretty simple subset of python
called RPython which has a very C-like syntax (but without memory
management code). This is needed to allow type inference inside the
interpreter code.

The code in your application is application code and can be whatever you
want, you may try to translate it to C/LLVM but it won't be that good of
course because the annotator is not that intelligent.

Just In Time compilation a-la-psyco is planned before the 1.0 release of
pypy. 
Right now also the compiler/parser run in application level which means
it is rather slow because it is not translated like the rest of pypy
(which accounts for quite a bit of the slowness of the translated pypy)
[this is of course only true if they didn't manage to rewrite the
parser/compiler in RPython, which I admit I'm not sure]

More information is available on codespeak.net website :).

What's really cool in PyPy is how easily you can implement a new object
space and change semantics of operations done in python.
Writing a Python interpreter that can share data structures across many
computers will be hard but possible.
There are already 4 different object spaces implemented, the standard
one, the thunk one (which is a lazy evaluation object space), the
flowgraph object space and the trace object space that traces each
operation done.

> Either way, this looks like a great milestone - congratulations to the
> entire team. (I remember PyPy being met with skepticism as to whether
> it could even be done! :-)

Indeed.

-- 
Valentino Volonghi aka Dialtone
Now Running MacOSX 10.4
Blog: http://vvolonghi.blogspot.com
http://weever.berlios.de
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Socket Troubles

2005-08-28 Thread Chris Spencer
Michael Sparks wrote:
> Chris Spencer wrote:
> 
> At one point in your code you do this: 
> self._socket.setblocking(0)
> 
> This says "if we can't recieve or send data without blocking, fail rather 
> than succeed". One of the failure modes is to return error 11. This is 
> infact normally defined as:
> #define EAGAIN  11  /* Try again */
> 
> What this means is "sorry, I couldn't do this without blocking right now, 
> try again very shortly!".
> 
> Looking at your code it continually loops (in BaseConnectionHandler_recv) 
> receiving data - whether or not there's any data to receive:
> def _recv(self):
> while self.running:
> try:
> data = self._socket.recv(4096)
> if not len(data):
> time.sleep(0.1)
> continue
> except Exception, e:
> log('Recieve failed for handler',self.address,'because of',e)
> 
> break
> 
> Since you never actually check to see if the socket is ready to give you
> data, and you've set it non-blocking, seeing lots of EAGAIN errors is
> pretty much what you'd expect to see. (Simply sleeping is not sufficient!)
> 
> I suppose the short answer though really is this: you set the socket
> non-blocking, you should therefore expect to see failures telling you
> to try again, and follow their advice! :)

You're quite right. I fixed this by using select(). However, I was still 
having problems with open() blocking the main thread. Then I realized a 
slight problem:
 t = threading.Thread(target=self._connection_handler(h))

I changed this to:
 t = threading.Thread(target=self._connection_handler, args=(h,))
and now it appears to be working correctly.

Thanks for your help! I truly appreciate it.

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


Re: What are new-style classes?

2005-08-28 Thread Terry Hancock
On Sunday 28 August 2005 04:47 am, Vaibhav wrote:
> I recently heard about 'new-style classes'. I am very sorry if this
> sounds like a newbie question, but what are they? I checked the Python
> Manual but did not find anything conclusive. Could someone please
> enlighten me? Thanks!

"New style" classes are becoming the standard in Python, and must
always be declared as a subclass of a new style class, including built-in
classes. The simplest is "object", so the simplest newstyle class is:

class no_class(object):
pass

as opposed to the simplest "old style" object which didn't inherit at all:

class really_no_class:
pass

I would regard the latter as deprecated now, since it basically doesn't
buy you anything to use it. The only reason to hang on to old style
classes would seem to be to avoid breaking older code that relied on
details such as the order of multiple inheritence, which have changed.

So if you're just learning, just use new style classes exclusively, and
use the documentation that applies to them.  I think it's fairly non-
controversial that new style classes are an improved design.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: What are new-style classes?

2005-08-28 Thread Reinhold Birkenfeld
Terry Hancock wrote:
> On Sunday 28 August 2005 04:47 am, Vaibhav wrote:
>> I recently heard about 'new-style classes'. I am very sorry if this
>> sounds like a newbie question, but what are they? I checked the Python
>> Manual but did not find anything conclusive. Could someone please
>> enlighten me? Thanks!
> 
> "New style" classes are becoming the standard in Python, and must
> always be declared as a subclass of a new style class, including built-in
> classes.

[Warning, advanced stuff ahead!]

That's not entirely true. New-style classes need not be derived from a new-
style class, they need to use the metaclass "type" or a derived.

So you can also declare a new-style class as

class new_class:
__metaclass__ = type

Or, if you want to switch a whole module with many classes to new-style, just 
set a

__metaclass__ = type

globally.


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


Re: Release of PyPy 0.7.0

2005-08-28 Thread Erik Max Francis
Carl Friedrich Bolz wrote:

> pypy-0.7.0: first PyPy-generated Python Implementations
> ==
> 
> What was once just an idea between a few people discussing
> on some nested mailing list thread and in a pub became reality ...
> the PyPy development team is happy to announce its first
> public release of a fully translatable self contained Python
> implementation.  The 0.7 release showcases the results of our
> efforts in the last few months since the 0.6 preview release
> which have been partially funded by the European Union:

Cool.  I just tested EmPy's regression suite with PyPy 0.7.0, and it ran 
fine (though obviously it was very slow).  Nice job so far, guys!

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   It is fatal to enter any war without the will to win it.
   -- Douglas MacArthur
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Release of PyPy 0.7.0

2005-08-28 Thread Michael Sparks
Valentino Volonghi aka Dialtone wrote:

> Michael Sparks <[EMAIL PROTECTED]> wrote:
> 
>> Would it be useful for people to start trying out their modules/code to
>> see if they work with this release, and whether they can likewise be
>> translated using the C/LLVM backends, or would you say this is too early?
>> (I'm more thinking in terms of it providing real world usecases in the
>> hope of finding things that don't work - rather than anything else)
> 
> This is not how it works. 

I beg to differ - it is how it can work (just not the default or currently
recommended). Currently the biggest, most interesting example is this:
(from the getting started page, compiling pypy)

cd pypy/translator/goal
python translate_pypy.py

Which has just finished executing on my machine and took about 3 hours to
complete (partly because the cc1 process reached ~780MB in terms of memory
footprint and my machine has 512Mb). However it goes on to talk about
compiling other things:

"""You can also use the translate_pypy.py script to try out several smaller
programs, e.g. a slightly changed version of Pystone:
cd pypy/translator/goal
python translate_pypy.py targetrpystone
"""

Which is pretty cool of course. For those of interest running pystone with
the pypy compiled native binary has the following results for pystones on
my machine:

[EMAIL PROTECTED]:~/pypy-0.7.0/pypy/translator/goal> ./pypy-c
debug: entry point starting
debug:  argv -> ./pypy-c
debug: importing code
debug: calling code.interact()
Python 2.4.1 (pypy 0.7.0 build) on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
 from test import pystone
 pystone.main(1000)
Pystone(1.1) time for 1000 passes = 13.97
This machine benchmarks at 71.582 pystones/second


The same results for CPython:
[EMAIL PROTECTED]:~/pypy-0.7.0/pypy/translator/goal> python
Python 2.4 (#1, Mar 22 2005, 21:42:42)
[GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test import pystone
>>> pystone.main()
Pystone(1.1) time for 5 passes = 1.58
This machine benchmarks at 31645.6 pystones/second

Obviously therefore anyone seeking to translate their existing code from
python to an executable directly using pypy would not be doing it for
performance reasons (again, something I'm aware of watching the
updates come out and having run svn checkouts at previous times).

(Factor of ~450 though is pretty d*^%n cool though :)

I'm also well aware of the difference between python and rpython :-)

> Pypy doesn't translate your code to C/LLVM.

> Currently PyPy can only translate a pretty simple subset of python
> called RPython which has a very C-like syntax (but without memory
> management code). This is needed to allow type inference inside the
> interpreter code.
>
> The code in your application is application code and can be whatever you
> want, you may try to translate it to C/LLVM but it won't be that good of
> course because the annotator is not that intelligent.

*Shrug* Seemed pretty good at annotating and compiling a module longer than
many of mine at Europython, and then compiled using the LLVM backed.  :)

Anyway, whether it's sensible or not I'm going to play with translating some
of my modules :)

Regards,


Michael.

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


Re: ideas for university project ??

2005-08-28 Thread Ken Starks
Jon Hewer wrote:

> Hi
> 
> I'm about to start my third, and final, year in computer science at
> cambridge uni, and i need to come up with an idea for a software
> project, but i'm really struggling for ideas, and i was wondering
> whether anyone here had any suggestions.
> 
> I'd say i'm probably most experienced in Java, but I have started
> learning Python, and although i haven't got very far yet, I plan on
> doing some more in the next few weeks.
> 
> Areas of interested include AI, distributed systems.  Most of all i
> want something that is interesting, and actually useful (thats
> probably stating the obvious!)
> 
> Cheers
> Jon

I'd like you to write a Python-SOAP-based interface to data-loggers and
interface boxes used in the UK at school level. For example, those
produced by Phillip Harris, which are normally connected by way of a
serial cable.

The idea is to keep an old computer with the data-logger attached, and
the SOAP server installed, in the field or lab. Am I correct in saying
that Java is too security-bound for this role?

Personally, I would feed the resulting XML into Cocoon, which already has
SOAP input, and from there into dataframes in 'R' among other places. Once
it has entered a Cocoon pipeline, it is already in a very flexible form, and
Data analysis can be done anywhere that can reach the Cocoon server. 

You may wish to develop that end of the pipeline either using your Java
skills, or by using XSLT to create Prolog facts or whatever.





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


Re: Doubt C and Python

2005-08-28 Thread Wouter van Ooijen (www.voti.nl)
>> I use Python when my time is most valuable (in most cases it is), in
>> the very few cases the computer's time is more valuable I write in
>> C/C++.
>
>In cases when the computer's time is more valuable, why not use CPython 
>with C/C++ API? Only most time consuming parts can be replaced to C/C++ 
>codes so as to increase the speed up to native C/C++ programs).

That assumes that one knows which are the most time-consuming parts,
that they are few (which is typically, but not always, the case) and
that they are 'fit' to be transferred to the C/C++ domain. The one
application I have written the last few years that probably would not
be fit to this approach is a compiler (Jal). It spends most of its
time walking the annotated syntax tree, with a lot of code
contributing rather evenly to the CPU time.

Don't take me wrong, IIRC that is the *only* PC program I have written
the last few years for which I selected the language and the language
was not Python :)

But I mainly program PICs. Where is the 10F200 Python interpreter when
you need one?


Wouter van Ooijen

-- 
http://www.voti.nl
Webshop for PICs and other electronics
http://www.voti.nl/hvu
Teacher electronics and informatics
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python image thumbnail generator?

2005-08-28 Thread Wouter van Ooijen (www.voti.nl)
>I'm thinking it would be nice and easy, if we could just upload a jpg into
>a dir called "gallery/". When the client clicks the "gallery" link, a 
>cgi script could search the gallery/ dir, and create thumbnails of any
>jpeg images that don't already have a thumbnail associated with them. The
>script could then generate a page of clickable thumbnails.

I dunno about the scripting aspect, but I use Python to generate my
website, I already had the images (of the products I sell). I used PIL
to generate thumbnails of the images. I think it took 2 or 3 lines of
Python - that is: for me. PIL is of course a bit more.




Wouter van Ooijen

-- 
http://www.voti.nl
Webshop for PICs and other electronics
http://www.voti.nl/hvu
Teacher electronics and informatics
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic image creation for the web...

2005-08-28 Thread Tompa
Benjamin Niemann  odahoda.de> writes:
> You are almost there. 
I don't feel so...

> Your create_image.py does not return anything to the
> browser yet.
Yes, I am aware of that but I do not what to return.

> First return proper HTTP headers, e.g.
> 
> sys.stdout.write('Status: 200 OK\r\n')
> sys.stdout.write('Content-type: image/gif\r\n')
> sys.stdout.write('\r\n')

Ok, but if possible I'd rather not return anything HTTP/HTML-related from my 
create_image.py file.

> Then check the PIL docs to find out, how to output the image to sys.stdout
> (instead of writing to a file).
> 
Ok, then I get this:

from PIL import Image, ImageDraw
import sys

im = Image.new("P", (600, 400))
draw = ImageDraw.Draw(im)
draw.rectangle((0, 0) + im.size, fill="blue")

sys.stdout.write('Status: 200 OK\r\n')
sys.stdout.write('Content-type: image/gif\r\n')
sys.stdout.write('\r\n')

im.save(sys.stdout, "GIF")

But this does not work.
I also tested to skip the HTTP-header stuff and just write the gif to 
sys.stdout, believing that that would work. But not so...

Hmm, I'm a newbie to Python (as you already probably have noticed ;-) so I 
don't know what else I should try. Any hints are welcome!

/Tompa


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


Re: Yielding a chain of values

2005-08-28 Thread Peter Hansen
Talin wrote:
> I'm finding that a lot of places within my code, I want to return the 
> output of a generator from another generator. Currently the only method 
> I know of to do this is to explicitly loop over the results from the 
> inner generator, and yield each one:
> 
>for x in inner():
>yield x
> 
> I was wondering if there was a more efficient and concise way to do 
> this. And if there isn't, then what about extending the * syntax used 
> for lists, i.e.:
> 
>yield *inner()

It's not the first time it's been suggested.  You can check the archives 
perhaps for past discussions.

I think syntax like that could be a good idea too, for readability 
reasons perhaps, but I don't think it's really important for efficiency 
reasons.  If you think about it, this involves one stack frame being set 
up for the call to the generator, and then a series of quick context 
switches (or whatever they're called in this situation) between the 
current stack frame and the inner() one, as each yielded value is 
produced, yield, then re-yielded up to the calling frame (with another 
quick context switch).  No additional stack frames are generated, and 
very few byte codes are involved:

 >>> def f():
...   for x in inner():
... yield x
...
 >>> dis.dis(f)
   2   0 SETUP_LOOP  21 (to 24)
   3 LOAD_GLOBAL  0 (inner)
   6 CALL_FUNCTION0
   9 GET_ITER
 >>   10 FOR_ITER10 (to 23)
  13 STORE_FAST   0 (x)

   3  16 LOAD_FAST0 (x)
  19 YIELD_VALUE
  20 JUMP_ABSOLUTE   10
...

Yes, that is some overhead, but unless you are going many levels deep 
(and that's usually a design smell of some kind) this isn't likely to be 
noticed amongst the rest of the code which is presumably doing something 
non-trivial to produce the values in the first place, and to consume 
them ultimately.

The basic loop could be handled entirely from C with an appropriate 
syntax addition as you suggest, but executing those four byte code 
instructions is very quick, and there is no repeated (Python) function 
call overhead as you would expect if inner() were not a generator.

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


Re: Dynamic image creation for the web...

2005-08-28 Thread Tompa
Richard Lewis  fastmail.co.uk> writes:
> It would be useful to know what web server software you're using. 

I intended to add that info but forgot...
I run IIS on W2K, python 2.4.1 and PIL 1.1.5.

> The other thing you may need to check is the HTTP header of the
> generated image. 
If possible I'd rather separate the HTTP/HTML-stuff from image creation.
I'd like to have an HTML file that refers to a py-file that creates images 
which are returned somehow (sys.stdout or something else in memory) and 
incorporated within the HTTP-response.

> It should be possible to create an HTTP response from
> your create_image.py script (as opposed to just an image) with a MIME
> type of image/jpeg and manually insert the binary image data in the
> response body...
Yes, I believe so too. Something like this, as suggested by Benjamin:
sys.stdout.write('Status: 200 OK\r\n')
sys.stdout.write('Content-type: image/gif\r\n')
sys.stdout.write('\r\n')
im.save(sys.stdout, "GIF")

But it does not work for some reason!? Besides, I was hoping for a solution 
which could skip the HTTP-header related stuff...

Regards,
/Tompa


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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-28 Thread Bryan Olson
Steve Holden wrote:
 > Paul Rubin wrote:
 > We are arguing about trivialities here. Let's stop before it gets
 > interesting :-)

Some of us are looking beyond the trivia of what string.find()
should return, at an unfortunate interaction of Python features,
brought on by the special-casing of negative indexes. The wart
bites novice or imperfect Python programmers in simple cases
such as string.find(), or when their subscripts accidentally
fall off the low end. It bites programmers who want to fully
implement Python slicing, because of the double-and-
contradictory- interpretation of -1, as both an exclusive ending
bound and the index of the last element. It bites documentation
authors who naturally think of the non-negative subscript as
*the* index of a sequence item.


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


Re: Dynamic image creation for the web...

2005-08-28 Thread Tompa
Max Erickson  gmail.com> writes:
> 
> check out sparklines:
> 
> http://bitworking.org/projects/sparklines/
> 
> It is a script very similar to what you want to do.

This sure looks interesting! Strange that I couldn't find this when I googled 
for this kind of stuff...
I will check it out - thanks!

Regards,
/Tompa


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


Re: global interpreter lock

2005-08-28 Thread Bryan Olson
phil hunt wrote:
 > It's not the number of paths that's important.

Absolutely right. Non-trivial software always has too many paths
to consider them individually, so we have to reason generally.

 > What's important is *predictability*, e.g. which instruction will
 > the computer execute next?
 >
 > If you only have one thread, you can tell by looking at the code
 > what gets executed next. It's very simple.

Not really. Trivially, an 'if' statement that depends upon input
data is statically predictable. Use of async I/O means makes the
programs execution dependent upon external timing.


 > If you have 2 threads you can easily have a timing-based situation
 > that occurs rarely but which causes your program to behave wierdly.
 > This sort of bug is very hard to reproduce and therefore to fix.

So we need to learn to avoid it.


[...]
 > Yes, find solutions. Don't find dangerous dead-ends that look like
 > solutions but which will give you lots of trouble.

If concurrency is a dead end, why do the programs that provide
the most sophisticated services of any in the world rely on it
so heavily?


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


Re: py to exe: suggestions?

2005-08-28 Thread Ron Adam
chris patton wrote:
> I need to convert a python file to an '.exe'. I've tried py2exe, and I
> don't like it because you have to include that huge dll and libraries.
> 
> Thanks for the Help!!

Do you want to create an exe to give to others,  or so that you can use 
it in windows easier just like any other exe?

If the later you may be able to tell py2exe to exclude dll's that are in 
your search path.

If you want something you can send to other windows users, then it's far 
easier to include the dll's and extra files than it is to try and make 
sure all the files the programs needs are installed correctly on the 
recipients computer.

I use:

py2exe - to create the main exe and gather all the needed files together.

Inno Setup - to create a windows installer complete with license, docs, 
Internet support links, and an uninstaller.

And a few other programs such as an icon editor to create icons, and 
Resource Hacker to change the tk window icons to my own. Py2exe will 
insert the exe icon, but not change the little tk window icons which 
reside in the tk dll files.

When it's all done you have an installable application from a single exe 
file that's very professional.  Most users won't need to know or care 
what language you developed your application with as long as it works.

Hope that helps,
Cheers,
Ron











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


Re: python image thumbnail generator?

2005-08-28 Thread Terry Hancock
On Saturday 27 August 2005 09:06 pm, Chris Dewin wrote:
> I'm thinking it would be nice and easy, if we could just upload a jpg into
> a dir called "gallery/". When the client clicks the "gallery" link, a 
> cgi script could search the gallery/ dir, and create thumbnails of any
> jpeg images that don't already have a thumbnail associated with them. The
> script could then generate a page of clickable thumbnails.

This is trivial to do with Zope.  I wrote a "VarImage" product for it
that will do the image manipulation you want handily.  I never really
created a "gallery" product for it because it's so trivial to do with a
regular Zope folder and a couple of scripts, but I would be happy to
share my Gallery template with you  if your interested.

The current version of VarImage even implements things like HTTP_REFERER
blocking (or watermarking if you prefer), to discourage remote-linking
of your images, etc.

An online example can be seen here: http://narya.net/Gallery

Not sure about CGI methods of doing it, though.
--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: Bug in string.find

2005-08-28 Thread bearophileHUGS
I agree with Bryan Olson.
I think it's a kind of bug, and it has to be fixed, like few other
things.

But I understand that this change can give little problems to the
already written code...

Bye,
bearophile

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


Re: global interpreter lock

2005-08-28 Thread Bryan Olson
Piet van Oostrum wrote:
 >>Paul Rubin  (PR) wrote:
 >>PR> Really, the essence of programming is to find ways of organizing the
 >>PR> program to stay reliable and maintainable in the face of that
 >>PR> combinatorial explosion.  That means facing the problem and finding
 >>PR> solutions, not running away.  The principle is no different for
 >>PR> threads than it is for if statements.
 >
 > The principle is (more or less) similar, but for parallel programs it 
is an
 > order of magnitude more complicated. Compare the correctness proofs of
 > parallel programs with those of sequential programs.

That's an artifact of what the research community is trying to
accomplish with the proof. Proving non-trivial programs correct
is currently beyond the state of the art.


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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-28 Thread Steve Holden
Bryan Olson wrote:
> Steve Holden wrote:
>  > Paul Rubin wrote:
>  > We are arguing about trivialities here. Let's stop before it gets
>  > interesting :-)
> 
> Some of us are looking beyond the trivia of what string.find()
> should return, at an unfortunate interaction of Python features,
> brought on by the special-casing of negative indexes. The wart
> bites novice or imperfect Python programmers in simple cases
> such as string.find(), or when their subscripts accidentally
> fall off the low end. It bites programmers who want to fully
> implement Python slicing, because of the double-and-
> contradictory- interpretation of -1, as both an exclusive ending
> bound and the index of the last element. It bites documentation
> authors who naturally think of the non-negative subscript as
> *the* index of a sequence item.
> 
> 
Sure. I wrote two days ago:

> We might agree, before further discussion, that this isn't the most 
> elegant part of Python's design, and it's down to history that this tiny 
> little wart remains.

While I agree it's a trap for the unwary I still don't regard it as a 
major wart. But I'm all in favor of discussions to make 3.0 a better 
language.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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


aproximate a number

2005-08-28 Thread billiejoex
Hi all. I'd need to aproximate a given float number into the next (int) 
bigger one. Because of my bad english I try to explain it with some example:

5.7 --> 6
52.987 --> 53
3.34 --> 4
2.1 --> 3

Regards 


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


Re: aproximate a number

2005-08-28 Thread rafi
billiejoex wrote:
> Hi all. I'd need to aproximate a given float number into the next (int) 
> bigger one. Because of my bad english I try to explain it with some example:
> 
> 5.7 --> 6
> 52.987 --> 53
> 3.34 --> 4
> 2.1 --> 3
> 
> Regards 
> 
> 

math.ceil returns what you need but as a float, then create an int

 >>> import math
 >>> math.ceil (12.3)
13.0
 >>> int (math.ceil (12.3))
13

hth

-- 
rafi

"Imagination is more important than knowledge."
(Albert Einstein)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: aproximate a number

2005-08-28 Thread Will McGugan
billiejoex wrote:
> Hi all. I'd need to aproximate a given float number into the next (int) 
> bigger one. Because of my bad english I try to explain it with some example:
> 
> 5.7 --> 6
> 52.987 --> 53
> 3.34 --> 4
> 2.1 --> 3
> 

Have a look at math.ceil

 >>> import math
 >>> math.ceil(5.7)
6.0


Will McGugan
-- 
http://www.willmcgugan.com
"".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in 
"jvyy*jvyyzpthtna^pbz")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: overload builtin operator

2005-08-28 Thread Bengt Richter
On Sun, 28 Aug 2005 04:09:10 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote:

[... a response to the OP's apparent desire to "overload the divide operator" 
with a call
to his safediv function ...]

The part that rewrote the the AugAssign could only work for plain name 
Augassign targets, so
I introduced a helper function to generate a suitable assignment target node 
for attributes,
subscripts, and slices as well. So the test (still very alpha) looks like the 
following now:



< testdiv.py 
>-
def test():
print 1.0/2.0
print 12/3
a=12; b=3
print a/b
print 2**a/(b+1)
try:
print 'print 1/0 =>'
print 1/0
except Exception, e: print '%s: %s' %(e.__class__.__name__, e)
try:
print 'print a/(b*(a-12)) =>'
print a/(b*(a-12))
except Exception, e: print '%s: %s' %(e.__class__.__name__, e)
try:
print 'def foo(x=1/(b-3)): return x =>'
def foo(x=1/(b-3)): return x
print 'print foo() =>'
print foo()
except Exception, e: print '%s: %s' %(e.__class__.__name__, e)
try:
print 'b /= (a-12) =>'
b /= (a-12)
print 'b after b/=(a-12):', b
except Exception, e: print '%s: %s' %(e.__class__.__name__, e)
print 's=[15]; s[0] /= 3; print s =>'
s=[15]; s[0] /= 3; print s
class T(list):
def __getitem__(self, i): print i; return 42
def __setitem__(self, i, v): print i, v
def __div__(self, other): print self, other; return 4242
t = T()
print 't.x=15; t.x /= 3; print t.x =>'
t.x=15; t.x /= 3; print t.x
print 't=T([15, 27]); t /= 3; print t =>'
t=T([15, 27]); t /= 3; print t

def foo(x, y):
"""for dis.dis to show code"""
z = x/y
x /= y
x.a /= y
x[z] /= y
x[:] /= y

if __name__ == '__main__': test()
--
Outputfrom run without conversion of / :


< import_safediv.py 
>--
# import_safediv.py
from arborist import import_editing_ast, get_augassign_tgt
from compiler.ast import Div, CallFunc, Name, AugAssign, Assign

def safediv(num, den):
if den==0: result = 0*num
else: result = num/den
print 'safediv(%r, %r) => %r'%(num, den, result)
return result

def div2safediv(divnode):
"""replace Div nodes with CallFunc nodes calling safediv with same args"""
return  CallFunc(Name('safediv'),[divnode.left, divnode.right], None, None, 
divnode.lineno)
 
def divaugass2safediv(auganode):
if auganode.op != '/=': return auganode
return Assign([get_augassign_tgt(auganode)],
CallFunc(Name('safediv'),[auganode.node, auganode.expr], None, None, 
auganode.lineno))

callbacks = {Div:div2safediv, AugAssign:divaugass2safediv}
def import_safediv(modname, verbose=False):
modsafe = import_editing_ast(modname, callbacks, verbose)
modsafe.safediv = safediv
return modsafe

if __name__ == '__main__':
modsafe = import_safediv('testdiv', verbose=True)
modsafe.test()
---

Result from using the above interactively:

 [14:21] C:\pywk\ut\ast>py24
 Python 2.4b1 (#56, Nov  3 2004, 01:47:27)
 [GCC 3.2.3 (mingw special 20030504-1)] on win32
 Type "help", "copyright", "credits" or "license" for more information.

First import as usual and run test()
 >>> import testdiv
 >>> testdiv.test()
 0.5
 4
 4
 1024
 print 1/0 =>
 ZeroDivisionError: integer division or modulo by zero
 print a/(b*(a-12)) =>
 ZeroDivisionError: integer division or modulo by zero
 def foo(x=1/(b-3)): return x =>
 ZeroDivisionError: integer division or modulo by zero
 b /= (a-12) =>
 ZeroDivisionError: integer division or modulo by zero
 s=[15]; s[0] /= 3; print s =>
 [5]
 t.x=15; t.x /= 3; print t.x =>
 5
 t=T([15, 27]); t /= 3; print t =>
 [15, 27] 3
 4242

Now import the import_safediv importer, to import with
conversion of ast to effect translation of divides to safediv calls:

Import and runs test() much as before:

 >>> from import_safediv import import_safediv
 >>> tdsafe = import_safediv('testdiv')
 >>> tdsafe.test()
 safediv(1.0, 2.0) => 0.5
 0.5
 safediv(12, 3) => 4
 4
 safediv(12, 3) => 4
 4
 safediv(4096, 4) => 1024
 1024
 print 1/0 =>
 safediv(1, 0) => 0
 0
 print a/(b*(a-12)) =>
 safediv(12, 0) => 0
 0
 def foo(x=1/(b-3)): return x =>
 safediv(1, 0) => 0
 print foo() =>
 0
 b /= (a-12) =>
 safediv(3, 0) => 0
 b after b/=(a-12): 0
 s=[15]; s[0] /= 3; print s =>
 safediv(15, 3) => 5
 [5]
 t.x=15; t.x /= 3; print t.x =>
 safediv(15, 3) => 5
 5
 t=T([15, 27]); t /= 3; print t =>
 [15, 27] 3
 safediv([15, 27], 3) => 4242
 4242

Look at the code generated by normal import first

 >>> import dis
 >>> dis.dis(testdiv.foo)
  40   0 LOAD_FAST0 (x)
   3 LOAD_FAST

Re: aproximate a number

2005-08-28 Thread billiejoex
Thank you. :-) 


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


Re: aproximate a number

2005-08-28 Thread Michael Sparks
billiejoex wrote:

> Hi all. I'd need to aproximate a given float number into the next (int)
> bigger one. Because of my bad english I try to explain it with some
> example:
> 
> 5.7 --> 6
> 52.987 --> 53
> 3.34 --> 4
> 2.1 --> 3

What about 2.0? By your spec that should be rounded to 3 - is that what you
intend?

If you do, you can simply do this:

def approx(x):
return int(x+1.0)

Regards,


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


using common lisp with python.

2005-08-28 Thread [EMAIL PROTECTED]
is there a way to embed common lisp programs in python?

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


Lossless Number Conversion

2005-08-28 Thread Chris Spencer
Is there any library for Python that implements a kind of universal 
number object. Something that, if you divide two integers, generates a 
ratio instead of a float, or if you take the square root of a negative, 
generates a complex number instead of raising an exception? Lisp has 
something like this, and it makes number crunching much more convenient.

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


Re: Dynamic image creation for the web...

2005-08-28 Thread Benjamin Niemann
Tompa wrote:

> Benjamin Niemann  odahoda.de> writes:
>> You are almost there.
> I don't feel so...
> 
>> Your create_image.py does not return anything to the
>> browser yet.
> Yes, I am aware of that but I do not what to return.
> 
>> First return proper HTTP headers, e.g.
>> 
>> sys.stdout.write('Status: 200 OK\r\n')
>> sys.stdout.write('Content-type: image/gif\r\n')
>> sys.stdout.write('\r\n')
> 
> Ok, but if possible I'd rather not return anything HTTP/HTML-related from
> my create_image.py file.

When the browser fetches the images for displaying, it performs just another
HTTP request, and you must reply with a valid HTTP response. The
Content-type header is the absolute minimum that must always be returned.
(IIRC the 'Status' can be omitted, if it's 200).

>> Then check the PIL docs to find out, how to output the image to
>> sys.stdout (instead of writing to a file).
>> 
> Ok, then I get this:
> 
> from PIL import Image, ImageDraw
> import sys
> 
> im = Image.new("P", (600, 400))
> draw = ImageDraw.Draw(im)
> draw.rectangle((0, 0) + im.size, fill="blue")
> 
> sys.stdout.write('Status: 200 OK\r\n')
> sys.stdout.write('Content-type: image/gif\r\n')
> sys.stdout.write('\r\n')
> 
> im.save(sys.stdout, "GIF")
> 
> But this does not work.
> I also tested to skip the HTTP-header stuff and just write the gif to
> sys.stdout, believing that that would work. But not so...

Works perfectly here...
What does the error.log of the webserver say?

> Hmm, I'm a newbie to Python (as you already probably have noticed ;-) so I
> don't know what else I should try. Any hints are welcome!
> 
> /Tompa

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


trictionary?

2005-08-28 Thread Randy Bush
i have some code which looks kinda like 

bin = {}
for whatever:
   for [a, b] in foo:
  x = 42 - a
  y = 42 - b
  if bin.has_key(x):
 bin[x] += 1
  else:
 bin[x] = 1
for i, j in bin.iteritems():
   print i, j

now i want to add a second count column, kinda like

bin = {}
for whatever:
   for [a, b] in foo:
  x = 42 - a
  if bin.has_key(x):
 bin[x.b] += 1
  else:
 bin[x.b] = 1
 bin[x.not b] = 0
for x, y, z in bin.iteritems():
   print x, y, z

should the dict value become a two element list, or is
there a cleaner way to do this?

randy

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


Re: trictionary?

2005-08-28 Thread Adam Tomjack
Randy,

I'd probably use a two element list.

Instead of using an if/else to check if an element is in your dict and 
initialize it, you can use the setdefault() function.  The docs for 
dictionaries explain it pretty well.

  bin = {}
  for whatever:
 for [a, b] in foo:
  x = 42 - a
  bin_item = bin.setdefault(x, [1, 0])
  bin_item[0] += 1
  for x, (y, z) in bin.iteritems():
 print x, y, z

You could also use a class like a C-style struct if you want named items:

class BinItem:
   def __init__(self, s=0, t=0):
 self.s = s
 self.t = t

bin = {}
for a, b in foo:
   x = 42 - a
   bin_item = bin.setdefault(x, BinItem(1, 0))
   bin_item.s += 1

for x, item in bin.iteritems():
   print x, item.s, item.t


Luck in battle,

Adam


Randy Bush wrote:
> i have some code which looks kinda like 
> 
> bin = {}
> for whatever:
>for [a, b] in foo:
> x = 42 - a
> y = 42 - b
> if bin.has_key(x):
>bin[x] += 1
> else:
>bin[x] = 1
> for i, j in bin.iteritems():
>print i, j
> 
> now i want to add a second count column, kinda like
> 
> bin = {}
> for whatever:
>for [a, b] in foo:
> x = 42 - a
> if bin.has_key(x):
>bin[x.b] += 1
> else:
>bin[x.b] = 1
>bin[x.not b] = 0
> for x, y, z in bin.iteritems():
>print x, y, z
> 
> should the dict value become a two element list, or is
> there a cleaner way to do this?
> 
> randy
> 




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


Re: NooB Question

2005-08-28 Thread Sybren Stuvel
APCass enlightened us with:
> How do you execute a .py in Linux with KDE?  If I double click on my
> program it opens Kwrite, for editing.

Make it executable (properties, permissions, executable). Make sure it
has #!/usr/bin/python as the first line.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trictionary?

2005-08-28 Thread Adam Tomjack
Oops, I found a bug in my previous code.

If you say

   bin_item = bin.setdefault(x, [1, 0])
   bin_item[0] += 1

then if x wasn't in bin, it'll get initialized to [1, 0], then 
incremented to [2, 0] in the first loop.  The code you asked about would 
have produced [1, 0].  Instead, you can say:

   bin_item = bin.setdefault(x, [0, 0])
   bin_item[0] += 1

That should be equivalent.  My example with the class is similarly broken.

Adam




Adam Tomjack wrote:
> Randy,
> 
> I'd probably use a two element list.
> 
> Instead of using an if/else to check if an element is in your dict and 
> initialize it, you can use the setdefault() function.  The docs for 
> dictionaries explain it pretty well.
> 
>   bin = {}
>   for whatever:
>  for [a, b] in foo:
> x = 42 - a
> bin_item = bin.setdefault(x, [1, 0])
> bin_item[0] += 1
>   for x, (y, z) in bin.iteritems():
>  print x, y, z
> 
> You could also use a class like a C-style struct if you want named items:
> 
> class BinItem:
>def __init__(self, s=0, t=0):
>  self.s = s
>  self.t = t
> 
> bin = {}
> for a, b in foo:
>x = 42 - a
>bin_item = bin.setdefault(x, BinItem(1, 0))
>bin_item.s += 1
> 
> for x, item in bin.iteritems():
>print x, item.s, item.t
> 
> 
> Luck in battle,
> 
> Adam
> 
> 
> Randy Bush wrote:
> 
>>i have some code which looks kinda like 
>>
>>bin = {}
>>for whatever:
>>   for [a, b] in foo:
>>x = 42 - a
>>y = 42 - b
>>if bin.has_key(x):
>>   bin[x] += 1
>>else:
>>   bin[x] = 1
>>for i, j in bin.iteritems():
>>   print i, j
>>
>>now i want to add a second count column, kinda like
>>
>>bin = {}
>>for whatever:
>>   for [a, b] in foo:
>>x = 42 - a
>>if bin.has_key(x):
>>   bin[x.b] += 1
>>else:
>>   bin[x.b] = 1
>>   bin[x.not b] = 0
>>for x, y, z in bin.iteritems():
>>   print x, y, z
>>
>>should the dict value become a two element list, or is
>>there a cleaner way to do this?
>>
>>randy
>>
> 
> 
> 
> 
> 

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


Re: Writing portable applications

2005-08-28 Thread Mike Meyer
Ulrich Hobelmann <[EMAIL PROTECTED]> writes:
> Mike Meyer wrote:
>>> I'd rather develop a native client for the machine that people
>>> actually WANT to use, instead of forcing them to use that
>>> little-fiddly web browser on a teeny tiny display.
>> You missed the point: How are you going to provide native clients for
>> platforms you've never heard of?
> Who says I have to?  With open protocols, everybody can.  I know many
> platforms that STILL don't have a browser that would work with most
> websites out there.  They all have NNTP, SMTP and POP
> clients. Text-mode, GUI-mode, your choice.

The people who are distributing applications via the web. You want to
convince them to quit using web technologies, you have to provide
something that can do the job that they do.

>>> And again: connections might be slow, a compact protocol is better
>>> than loading the whole UI every time.  And while Ajax might work,
>>> despite the UI being maybe too big for the little browser window, and
>>> even if it works, it's still probably more work than a simple, native
>>> UI.  First of all it needs to load all the JS on first load, secondly
>>> sometimes for a flexible UI you'd have to replace huge parts of the
>>> page with something else.  Native UIs are more up to the task.
>> I'm not arguing that native UI's aren't better. I'm arguing that web
>> applications provide more portability - which is important for some
>> applications and some developers.
> Like Java provides more portability.  Unless you ran NetBSD in 2003
> (there was no Java back then that worked for me), hm, IRIX?, Plan9,
> BeOS the list goes on...  LOTS of platforms don't have the manpower to
> develop a client that renders all of the huge bloated wagonload of W3C
> tech that was only designed for *markup* from the beginning.

I'm still waiting for an answer to that one - where's the Java toolkit
that handles full-featured GUIs as well as character cell
interfaces. Without that, you aren't doing the job that the web
technologies do.

>>> I just wonder who wrote fully standards compliant web browsers for
>>> those 90 platforms.
>> Nobody. I doubt there's a fully standards compliant web browser
> Nobody, huh?  Then how could you run just ANY web application on those
> platforms?

The same way you write POSIX applications in the face of buggy
implementations - by working around the bugs in the working part of
the implementation, and using conditional code where that makes a
serious difference.

>> available for *any* platform, much less any non-trivial collection of
>> them. You write portable web applications to the standards, and design
>> them to degrade gracefully. Then you go back and work around any new
> Oh right, they degrade gracefully.  So without Javascript or cookies
> (the former is often not implemented) you get a HTML page with an
> error notice -- if you're lucky.

You left off the important part of what I had to say - that the
application be written by a moderately competent web author.

> A server AND client for a simple protocol designed for its task
> (i.e. not FTP for instance) can be implemented in much less work than
> even designing even part of a web application backend that does that
> kind of stuff.

Well, if it that easy (and web applications are dead simple), it
should be done fairly frequently. Care to provide an example?

>> You think you're done. A lot of developers think you can stop with
>> the
>> first one or two. You're all right for some applications. For others,
>> you're not.  Personally, I like applications that run on all the
>> platforms I use - and your set doesn't cover all three of those
>> systems.
> Ok, I'd be interested to hear what those are.  VMS, RiscOS, Mac OS 9...?

FreeBSD, OS X and a Palm Vx.

> If a system's scheduler, or select implementation sucks, though, I'd
> complain to the vendor or simply abandon the platform for
> another. Competition is good :)

Complaining to the vendor doesn't always get the bug fixed. And
refusing to support a platform isn't always an option. Sometimes, you
have to byte the bullet and work around the bug on that platform.

>> same thing applies to threads, except such code typically includes a
>> third option of not using threads at all. And so on.
> Well, who doesn't do threads after several years of POSIX IMHO can't
> be taken seriously.  Ok, the BSDs didn't until recently, but those are
> volunteer projects.

Not all platforms are POSIX. If you're ok limiting your application to
a small subset of the total number of platforms available, then
there's no advantage to using web technologies. Some of us aren't
satisifed with that, though.

>> And we haven't even started talking about the build process...
> If the libraries are installed, just build and link it (if you use
> standard C, POSIX + 3rd party libs that do the same).  If not, then
> tough luck -- it couldn't even run in theory then.

You have to have the right build tool installed. Since you use BSD,
you've s

Re: Dynamic image creation for the web...

2005-08-28 Thread Mike Meyer
Tompa <[EMAIL PROTECTED]> writes:
>> The other thing you may need to check is the HTTP header of the
>> generated image. 
> If possible I'd rather separate the HTTP/HTML-stuff from image creation.
> I'd like to have an HTML file that refers to a py-file that creates images 
> which are returned somehow (sys.stdout or something else in memory) and 
> incorporated within the HTTP-response.

The only relation between HTTP and HTML is that most full pages
retrieved by HTTP are HTML. If you're going to use HTTP to fetch the
image, *something* has to deal with generating the HTTP headers.

The best you can do is write a wrapper that deals with the HTTP
headers then invokes your program to send just the image.

>> It should be possible to create an HTTP response from
>> your create_image.py script (as opposed to just an image) with a MIME
>> type of image/jpeg and manually insert the binary image data in the
>> response body...
> Yes, I believe so too. Something like this, as suggested by Benjamin:
> sys.stdout.write('Status: 200 OK\r\n')
> sys.stdout.write('Content-type: image/gif\r\n')
> sys.stdout.write('\r\n')
> im.save(sys.stdout, "GIF")
>
> But it does not work for some reason!?

You know, it's *really* hard to figure out why something doesn't work
if you don't know what happens when you try it. What happens when you
try fetching the URL for the python script directly? How about if you
telnet to the web server and do a HEAD on that URL? And so on...

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Question

2005-08-28 Thread Beginner/Not Yet Programmer
I've never programmed before, so I thought I'd try and learn a bit by
using some Python tutorials.  I started using the tutorial at
http://www.honors.montana.edu/~jjc/easytut/easytut/node3.html.  It
mentioned different forms of Python, specifically Command Line and
IDLE.  Being inexperienced, I'm not sure how to change from Command
Line to IDLE, and I'm not sure which one I'm in when I start up the
program.  In my Python folder, the only applications I have are
python.exe and pythonw.exe.  Pythonw.exe won't run.  So, I run
python.exe, and I'm not sure whether it is IDLE, Command Line, or
neither.  Also, I'm unsure of how to save programs, considering when I
run python.exe, it opens up a window which does not have the little bar
with the "File", "Edit", "View" and "Help" buttons on it.  If you can
help me out at all, thank you.

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


Re: trictionary?

2005-08-28 Thread Steven Bethard
Randy Bush wrote:
> now i want to add a second count column, kinda like
> 
> bin = {}
> for whatever:
>for [a, b] in foo:
> x = 42 - a
> if bin.has_key(x):
>bin[x.b] += 1
> else:
>bin[x.b] = 1
>bin[x.not b] = 0
> for x, y, z in bin.iteritems():
>print x, y, z
> 
> should the dict value become a two element list, or is
> there a cleaner way to do this?

It would probably help if you explained what the real problem is you're 
trying to solve.  Using a two element list to store a pair of counts has 
a bad code smell to me.

That said, you could write your code something like:

 bin = {}
 for whatever:
# NOTE: brackets are unnecessary
for a, b in foo:
  x = 42 - a
   # NOTE: 'in' is generally faster than has_key()
  if x in bin
 bin[x][0] += 1
  else:
  bin[x] = [1, 0]
 # NOTE: extra parens necessary to unpack count list
 for x, (y, z) in bin.iteritems():
print x, y, z

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


Re: Question

2005-08-28 Thread Adam Tomjack
Double clicking python.exe will give you the command line version.  To 
run IDLE, click Start -> Programs -> Python 2.x -> IDLE.

pythonw.exe is useful for running GUI scripts.  In Windows there are two 
types of programs: command line and gui programs.  python.exe is the 
command line version.  Suppose you write a Tk or a wxWindows program 
with python and you save it to a file.  You can still use python.exe to 
run that gui program, but it'll open an extra black window with nothing 
in it.  That's what pythonw.exe is for.  It can't give you a command 
line (which is why it disappears right away when you double click it), 
but it also doesn't open than extra window when you use it to run a gui 
application.

Adam

Beginner/Not Yet Programmer wrote:
> I've never programmed before, so I thought I'd try and learn a bit by
> using some Python tutorials.  I started using the tutorial at
> http://www.honors.montana.edu/~jjc/easytut/easytut/node3.html.  It
> mentioned different forms of Python, specifically Command Line and
> IDLE.  Being inexperienced, I'm not sure how to change from Command
> Line to IDLE, and I'm not sure which one I'm in when I start up the
> program.  In my Python folder, the only applications I have are
> python.exe and pythonw.exe.  Pythonw.exe won't run.  So, I run
> python.exe, and I'm not sure whether it is IDLE, Command Line, or
> neither.  Also, I'm unsure of how to save programs, considering when I
> run python.exe, it opens up a window which does not have the little bar
> with the "File", "Edit", "View" and "Help" buttons on it.  If you can
> help me out at all, thank you.
> 

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


Re: global interpreter lock

2005-08-28 Thread Mike Meyer
Bryan Olson <[EMAIL PROTECTED]> writes:
phil hunt wrote:
>  > What's important is *predictability*, e.g. which instruction will
>  > the computer execute next?
>  >
>  > If you only have one thread, you can tell by looking at the code
>  > what gets executed next. It's very simple.
> Not really. Trivially, an 'if' statement that depends upon input
> data is statically predictable. Use of async I/O means makes the
> programs execution dependent upon external timing.

Yes, but that depenency is tied to a single point - the select
call. The paths after that are statically predictable. This makes the
code very managable.

>  > If you have 2 threads you can easily have a timing-based situation
>  > that occurs rarely but which causes your program to behave wierdly.
>  > This sort of bug is very hard to reproduce and therefore to fix.
> So we need to learn to avoid it.

No, we need tools that make it impossible to write codde that triggers
it. Async I/O is one such tool, but it has lots of other limitations
that make it unsuitable for many applications.

> [...]
>  > Yes, find solutions. Don't find dangerous dead-ends that look like
>  > solutions but which will give you lots of trouble.
> If concurrency is a dead end, why do the programs that provide
> the most sophisticated services of any in the world rely on it
> so heavily?

I don't know what Phil is saying, but I'm not calling concurrency a
dead end. I'm calling the tools available in most programming
languages for dealing with it primitive.

We need better tools.

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trictionary?

2005-08-28 Thread Adam Tomjack
Steven Bethard wrote:
...
> Using a two element list to store a pair of counts has 
> a bad code smell to me.
...

Why is that?  It strikes me as the cleanest way to solve that problem, 
as long as it's easy enough to figure out what each element really 
represents.  You could name each element, but for a block of code eight 
lines long, doing anything more descriptive would be too verbose.

Adam

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


Re: trictionary?

2005-08-28 Thread Steven Bethard
Adam Tomjack wrote:
> Steven Bethard wrote:
> ...
>> Using a two element list to store a pair of counts has a bad code 
>> smell to me.
> ...
> 
> Why is that?

Note that "code smell"[1] doesn't mean that something is actually wrong, 
just that it might be.  In Python, pairs are usually handled with 
tuples[2], but tuples would be inconvenient in this case, since the 
first value must be modified.  Declaring a class with two attributes as 
you suggested is often a good substitute, but if the OP's code is really 
what it looks like, I get another code smell because declaring a class 
to be used by only 10 lines of code seems like overkill.

I also get a code smell from a dict holding two-element lists because 
I've been writing in Python and answering questions on the Python-list 
for a couple of years now, and I've never needed one yet. ;-)

STeVe

[1]http://en.wikipedia.org/wiki/Code_smell
[2]http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lossless Number Conversion

2005-08-28 Thread [EMAIL PROTECTED]

Chris Spencer wrote:
> Is there any library for Python that implements a kind of universal
> number object. Something that, if you divide two integers, generates a
> ratio instead of a float, or if you take the square root of a negative,
> generates a complex number instead of raising an exception? Lisp has
> something like this, and it makes number crunching much more convenient.
>
> Chris

The GMPY module has unlimited precision rationals:

>>> from gmpy import *

>>> r = mpq(1,1)# create the rational 1/1
>>> for i in range(2,50):
r = r + mpq(1,i)# add the rational 1/i to the running sum
print r


3/2
11/6
25/12
137/60
49/20
363/140
761/280
7129/2520
7381/2520
83711/27720
86021/27720
1145993/360360
1171733/360360
1195757/360360
2436559/720720
42142223/12252240
14274301/4084080
275295799/77597520
55835135/15519504
18858053/5173168
19093197/5173168
444316699/118982864
1347822955/356948592
34052522467/8923714800
34395742267/8923714800
312536252003/80313433200
315404588903/80313433200
9227046511387/2329089562800
9304682830147/2329089562800
290774257297357/72201776446800
586061125622639/144403552893600

So you can keep absolute precision all the way to the end
of the calculation. And you can always convert it to a float
by dividing the numerator by the denominator:

>>> print mpf(r.numer())/mpf(r.denom())
4.47920533832942505756047179296

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


Re: formal math ?

2005-08-28 Thread mehdi . rabah
Thanks you two.

I was just thinking if it was possible.

If I really want to do this, maybe the best way is to do an interface
to python of an open source project I have just discovered : maxima.

So long,

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


Re: trictionary?

2005-08-28 Thread [EMAIL PROTECTED]
Steven Bethard wrote:
> Adam Tomjack wrote:
> > Steven Bethard wrote:
> > ...
> >> Using a two element list to store a pair of counts has a bad code
> >> smell to me.
> > ...
> >
> > Why is that?
>
> Note that "code smell"[1] doesn't mean that something is actually wrong,
> just that it might be.  In Python, pairs are usually handled with
> tuples[2], but tuples would be inconvenient in this case, since the
> first value must be modified.  Declaring a class with two attributes as
> you suggested is often a good substitute, but if the OP's code is really
> what it looks like, I get another code smell because declaring a class
> to be used by only 10 lines of code seems like overkill.
>
> I also get a code smell from a dict holding two-element lists because
> I've been writing in Python and answering questions on the Python-list
> for a couple of years now, and I've never needed one yet. ;-)
>
> STeVe
>
> [1]http://en.wikipedia.org/wiki/Code_smell
> [2]http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types

Could you do me a favor and see what this smells like?

I put some data in a csv file (with headers) and this will
bring it in quite simply as a dictionary with [names] as
keys and an attribute dictionary as the value.

py_monsters.csv:

name,hardiness,agility,friend,courage,room,weight,special_def_odds,armor,weapon,odds,dice,side,hits,reaction,desc
PIRATE,5,20,0,10,26,300,0,0,11,60,1,10,0,"not met",You see a man with a
beard and a brass ring in his ear.  He is wearing clothes  made of silk
and is wielding a very fancily engraved sword.


import csv
temp1 = []
temp2 = []
reader = csv.reader(file(r"py_monsters.csv"))
for rec in reader:
temp1.append(rec)
for i in temp1[1:]:
temp2.append((i[0],dict(zip(temp1[0][1:],i[1:]
monsters = dict(temp2)

This gives me what I want

[('PIRATE', {'reaction': 'not met',
'agility': '20',
'room': '26',
'weight': '300',
'armor': '0',
'weapon': '11',
'hits': '0',
'side': '10',
'special_def_odds': '0',
'courage': '10',
'hardiness': '5',
'desc': 'You see a man with a beard and a brass ring in his ear.
He is wearing clothes  made of silk and is wielding a very fancily
engraved sword.',
'odds': '60',
'friend': '0',
'dice': '1'})]

so that I can now write code like

if monsters['PIRATE']['reaction']=='not met':
print monsters['PIRATE']['desc']

instead of using stupid index numbers.

But the loader seems to have a kind of perl-like odor to it,
i.e., next week I won't understand what it does.

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


Re: trictionary?

2005-08-28 Thread Roy Smith
Steven Bethard <[EMAIL PROTECTED]> wrote:
> In Python, pairs are usually handled with tuples[2], but tuples would be 
> inconvenient in this case, since the first value must be modified.

Instead of modifying the tuple (which you can't do), you can create a new 
one:

a, b = myDict[key]
myDict[key] = (a+1, b)

It's a bit inefficient, but get it working first, with clear, easy to 
understand code, then worry about how efficient it is.  

> Declaring a class with two attributes as 
> you suggested is often a good substitute, but if the OP's code is really 
> what it looks like, I get another code smell because declaring a class 
> to be used by only 10 lines of code seems like overkill.

But, classes are so lightweight in Python.  You can get away with nothing 
more than:

class Data:
   pass

and then you can do things like:

myData = Data
myData.a = a
myData.b = b

More likely, I would want to write:

class Data:
   def __init__ (self, a, b):
  self.a = a
  self.b = b

but I've done the minimilist Data class more than once.  It doesn't cost 
much, and it's often more self-documenting than just a tuple.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trictionary?

2005-08-28 Thread Randy Bush
>> bin = {}
>> for whatever:
>>for [a, b] in foo:
>>x = 42 - a
>>if bin.has_key(x):
>>   bin[x.b] += 1
>>else:
>>   bin[x.b] = 1
>>   bin[x.not b] = 0
>> for x, y, z in bin.iteritems():
>>print x, y, z
>> 
>> should the dict value become a two element list, or is there a
>> cleaner way to do this?
> It would probably help if you explained what the real problem is
> you're trying to solve.

actually, that code fragment was meant to do that.  it's pretty much
what i needed to do at that point, just the variable names made
simple.

> Using a two element list to store a pair of counts has a bad code
> smell to me.

exactly.  which is why i was asking.

> That said, you could write your code something like:
>  bin = {}
>  for whatever:
> # NOTE: brackets are unnecessary
> for a, b in foo:
> x = 42 - a
># NOTE: 'in' is generally faster than has_key()
> if x in bin
>bin[x][0] += 1
> else:
>   bin[x] = [1, 0]
>  # NOTE: extra parens necessary to unpack count list
>  for x, (y, z) in bin.iteritems():
> print x, y, z

so, to do this using the real names, it looks like

   for [start, end, AS, full] in heard:
  week = int((start-startDate)/aWeek)
  if week in bin:
 if full:
bin[week][0] += 1
 else:
bin[week][1] += 1
  else:
 if full:
bin[week] = [1, 0]
 else:
bin[week] = [0, 1]
   ...
   for i, (j, k) in bin.iteritems():
  if j == 0:
 print str(i) + ",," + str(k)
  elif k == 0:
 print str(i) + "," + str(j)
  else:
 print str(i) + "," + str(j) + "," + str(k)

which is still pretty darned grotty and unexpressive.  of course,
i could be a bit more obscure and do

  if week in bin:
 bin[week][not full] += 1
  else:
 bin[week] = [ full, not full ]

except i probably have to coerce the types or something.  less
code but less obvious.

randy

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


Re: overload builtin operator

2005-08-28 Thread Terry Reedy
I suspect that PyPy, when further alone, will make it easier to do things 
like develop a customized interpreter that has alternate definitions for 
builtin operators.  So maybe the OP should ask again in a year or two.

TJR



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


Re: Embedding Python in other programs

2005-08-28 Thread Gregory Piñero
Guys, I am so lost.  I followed the instructions exactly at 
http://www.python.org/windows/win32com/QuickStartServerCom.html

But then when I opened up Visual Basic 6 and went to
project>references, It is not listing anything like the helloworld com
thingy I just registered?  What do I need to do to use this com server
thingy from within VB?  I'd really appriciate any help.

Thanks,

Greg

On 8/28/05, Gregory Piñero <[EMAIL PROTECTED]> wrote:
> Thanks Ravi, I'll take a look
> 
> 
> On 27 Aug 2005 22:55:40 -0700, Ravi Teja <[EMAIL PROTECTED]> wrote:
> > http://www.python.org/windows/win32com/QuickStartServerCom.html
> >
> > If you are using ActivePython, that tutorial is included (PyWin32
> > documentation -> Python COM -> Overviews) along with the needed
> > win32all module.
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
> 
> 
> --
> Gregory Piñero
> Chief Innovation Officer
> Blended Technologies
> (www.blendedtechnologies.com)
> 


-- 
Gregory Piñero
Chief Innovation Officer
Blended Technologies
(www.blendedtechnologies.com)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Release of PyPy 0.7.0

2005-08-28 Thread Terry Reedy

"Michael Sparks" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> (Factor of ~450 though is pretty d*^%n cool though :)

I think the ratio was 10 or 100 times higher when first measureable.  I 
have long expected success but am still impressed.

TJR



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


Re: Embedding Python in other programs

2005-08-28 Thread Ravi Teja
Greg,
  I don't recall touching VB6 in 4 years. From whatever I remember, you
are trying to do early binding (trying to find a registered type
library). You need to do late binding instead (use CreateObject) to
dynamically instantiate the COM object.

Ravi Teja.

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


Re: trictionary?

2005-08-28 Thread Adam Tomjack
I'd write it like this:

bin = {}
for start, end, AS, full in heard:
   week = int((start-startDate)/aWeek)
   counters = bin.setdefault(week, [0, 0])
   if full:
  counters[0] += 1
   else:
  counters[1] += 1

for week, (times_full, times_not_full) in bin.iteritems():
   print ...

Seriously, use setdefault() as often as you can.  It may be a little 
awkward at first, but after a little bit, you instantly know what it 
means.  It takes out a whole if/else statement which will make your code 
smaller and more readable at the same time.

The list is actually representing a struct.  Regardless of how it 
smells, it's tight, small, and elegant.  (This is the sort of problem 
where Python shines.)  I do stuff like this all the time.  Lists are so 
lightweight that there really isn't a better way to solve this problem. 
  Anything else either involves more code or is less readable, in my 
opinion.

Using an idea you used earlier, you could get smaller code by saying:
for start, end, AS, full in heard:
   week = int((start-startDate)/aWeek)
   counters = bin.setdefault(week, [0, 0])
   counters[not full] += 1

Or
for start, end, AS, full in heard:
   week = int((start-startDate)/aWeek)
   bin.setdefault(week, [0, 0])[not full] += 1

Or even
for start, end, AS, full in heard:
  bin.setdefault(int((start-startDate)/aWeek), [0, 0])[not full] += 1

While smaller, those are all too tricky for my taste.  I think they're 
harder to read.  I'd personally use the if/else.  YMMV.


Using lists to represent structs is perfectly fine if the list doesn't 
live longer than about one screen of code.  If the list-struct gets 
returned from a top-level function and gets used elsewhere, then you 
should start to worry.  It's too easy to forget what each element is 
supposed to represent if you have to scroll your editor to see the place 
where the list was created.  That, in my opinion, would smell fishy.  In 
that case, you should probably represent your struct with a class or a 
dict so that each element has a name.  On the flip side, using such a 
heavy solution for such a simple problem also smells bad.  The solution 
should should be as complicated as the problem -- no more, no less.

Adam


Randy Bush wrote:
>>>bin = {}
>>>for whatever:
>>>   for [a, b] in foo:
>>>   x = 42 - a
>>>   if bin.has_key(x):
>>>  bin[x.b] += 1
>>>   else:
>>>  bin[x.b] = 1
>>>  bin[x.not b] = 0
>>>for x, y, z in bin.iteritems():
>>>   print x, y, z
>>>
>>>should the dict value become a two element list, or is there a
>>>cleaner way to do this?
>>
>>It would probably help if you explained what the real problem is
>>you're trying to solve.
> 
> 
> actually, that code fragment was meant to do that.  it's pretty much
> what i needed to do at that point, just the variable names made
> simple.
> 
> 
>>Using a two element list to store a pair of counts has a bad code
>>smell to me.
> 
> 
> exactly.  which is why i was asking.
> 
> 
>>That said, you could write your code something like:
>> bin = {}
>> for whatever:
>># NOTE: brackets are unnecessary
>>for a, b in foo:
>>x = 42 - a
>>   # NOTE: 'in' is generally faster than has_key()
>>if x in bin
>>   bin[x][0] += 1
>>else:
>>  bin[x] = [1, 0]
>> # NOTE: extra parens necessary to unpack count list
>> for x, (y, z) in bin.iteritems():
>>print x, y, z
> 
> 
> so, to do this using the real names, it looks like
> 
>for [start, end, AS, full] in heard:
>   week = int((start-startDate)/aWeek)
>   if week in bin:
>  if full:
>   bin[week][0] += 1
>else:
>   bin[week][1] += 1
>   else:
>  if full:
>   bin[week] = [1, 0]
>else:
>   bin[week] = [0, 1]
>...
>for i, (j, k) in bin.iteritems():
>   if j == 0:
>print str(i) + ",," + str(k)
>   elif k == 0:
>print str(i) + "," + str(j)
>   else:
>print str(i) + "," + str(j) + "," + str(k)
> 
> which is still pretty darned grotty and unexpressive.  of course,
> i could be a bit more obscure and do
> 
>   if week in bin:
>  bin[week][not full] += 1
>   else:
>  bin[week] = [ full, not full ]
> 
> except i probably have to coerce the types or something.  less
> code but less obvious.
> 
> randy
> 

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


Re: trictionary?

2005-08-28 Thread Scott David Daniels
Randy Bush wrote:
>... i could be a bit more obscure and do
>   if week in bin:
>  bin[week][not full] += 1
>   else:
>  bin[week] = [ full, not full ]

If you cannot take the setdefault advice, at least do:

 try:
 bin[week][not full] += 1
 except KeyError:
 bin[week] = [full, not full]

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SocketServer and a Java applet listener

2005-08-28 Thread google

Steve Horsley schreef:

> [EMAIL PROTECTED] wrote:
> > Dear newsgroup,
> >
> > I give up, I must be overseeing something terribly trivial, but I can't
> > get a simple (Java) applet to react to incoming (python) SocketServer
> > messages.
> >
> > Without boring you with the details of my code (on request available,
> > though), here is what I do :
> >
> > I have a TCPServer and BaseRequestHandler .
> > Connecting via telnet : everything goes OK.
> >
> > Connecting from Applet :
> > problem 1 (worked around it) : java has some 'propietary' UTF-8 format,
> > python's unicode doesn't seem to handle it correctly and I have to
> > strip the first two bytes/chars , then all goes OK .
> >
>
> Those 2 bytes are important! They are a string length indicator.
> Here are the docs that tell you that it puts a 2-byte length on
> the front:
> http://java.sun.com/j2se/1.5.0/docs/api/java/io/DataOutputStream.html#writeUTF(java.lang.String)
> If you are ignoring these bytes, then how can you be sure you
> have received the whole string? Please don't tell me you "just
> hope" that the whole string will always arrive in a single read()
> call. There is no guarantee of that. TCP does NOT have message
> boundaries, and TCP packets can be both fragmented and coalesced.

Ah, I see... I worked around this (see below), the workaround is
consistent with what you assume.
My question "How to send/receive between python SocketServer and java
Applet (SocketListener)" then seems to be boiling down to: "How to
interface between python unicode and java read/writeUTF?"

>
> Probably the same problem. If you didn't send a 2 byte length
> indicator first, then java's readUTF() will have tried to
> interpret the first 2 bytes that you did actually send as the
> string length, and may well simply be waiting patiently for the
> rest to arrive.
>
I just couldn't get read/writeUTF and python unicode to interface, so I
refactored the applet's socketlistener to convert the
socket.getInputStream to a BufferedInputReader on which I call the
readline() method.
I still skip the first two bytes in the python receiver which seems
harmless since python doesn't use the byte length.
On both sides I have other way to know when the end-of-message has been
reached. A timeout mechanism provides some safety for partial
transmission handling.


Thanks !



Thijs

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