ANN: Veusz 1.3 - a scientific plotting module and package

2009-02-25 Thread Jeremy Sanders
Veusz 1.3
-
Velvet Ember Under Sky Zenith
-
http://home.gna.org/veusz/

Veusz is Copyright (C) 2003-2009 Jeremy Sanders jer...@jeremysanders.net
Licenced under the GPL (version 2 or greater).

Veusz is a scientific plotting package. It is written in Python, using
PyQt4 for display and user-interfaces, and numpy for handling the
numeric data. Veusz is designed to produce publication-ready
Postscript/PDF output. The user interface aims to be simple,
consistent and powerful.

Veusz provides a GUI, command line, embedding and scripting interface
(based on Python) to its plotting facilities. It also allows for
manipulation and editing of datasets.

Changes in 1.3:
 * Add data capture from sockets, files and external programs
 * Remembers previous entries in dialog boxes
 * Add shaded regions or lines error bar style
 * Plot keys can be dragged around with the mouse
 * New clearer scalable icons
 * Now requires Python = 2.4

 * minor changes
  - Add filename completion in several places
  - Remember import dialog tab selection
  - Use font drop-down to select font
  - Add icons for error bar styles
  - Error bar code rewritten and simplified
  - Add import dialog to toolbar
 
 * bug fixes:
  - Fix incorrect security errors when loading invalid documents
  - Fix dragging around of shapes and lines problems
  - Fix address of FSF in license
  - Fix appearance of dialog box fonts on some systems
  - Fix recent files menu
  - Fix hiding of pages and graphs

Features of package:
 * X-Y plots (with errorbars)
 * Line and function plots
 * Contour plots
 * Images (with colour mappings and colorbars)
 * Stepped plots (for histograms)
 * Fitting functions to data
 * Stacked plots and arrays of plots
 * Plot keys
 * Plot labels
 * Shapes and arrows on plots
 * LaTeX-like formatting for text
 * EPS/PDF/PNG/SVG export
 * Scripting interface
 * Dataset creation/manipulation
 * Embed Veusz within other programs
 * Text, CSV and FITS importing

Requirements:
 Python (2.4 or greater required)
   http://www.python.org/
 Qt = 4.3 (free edition)
   http://www.trolltech.com/products/qt/  
 PyQt = 4.3 (SIP is required to be installed first)
   http://www.riverbankcomputing.co.uk/pyqt/
   http://www.riverbankcomputing.co.uk/sip/
 numpy = 1.0
   http://numpy.scipy.org/

Optional:
 Microsoft Core Fonts (recommended for nice output)
   http://corefonts.sourceforge.net/
 PyFITS = 1.1 (optional for FITS import)
   http://www.stsci.edu/resources/software_hardware/pyfits

For documentation on using Veusz, see the Documents directory. The
manual is in pdf, html and text format (generated from docbook).

Issues:
 * Can be very slow to plot large datasets if antialiasing is enabled.
   Right click on graph and disable antialias to speed up output.

If you enjoy using Veusz, I would love to hear from you. Please join
the mailing lists at

https://gna.org/mail/?group=veusz

to discuss new features or if you'd like to contribute code. The
latest code can always be found in the SVN repository.

Jeremy Sanders


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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


PyAMF 0.4.1 released

2009-02-25 Thread Thijs Triemstra | Collab

The PyAMF team is proud to announce the release of 0.4.1!

PyAMF [1] is a lightweight library that allows Flash and Python  
applications to communicate via Adobe’s

ActionScript Message Format.

This is a bugfix release [2], see the changelog [3] for the complete  
list of changes. A brief overview of the

changes:

- amf0.Encoder.use_amf3 has been extended to cover all object types
- Encoding {0:0, ‘0′:1} will now raise an AttributeError.
- Improvements to the Google App Engine adapter - see ticket 479 for  
details

- Unicode handling in __repr__ functions has been improved
- Django models.TimeField, models.DateField will now be converted to  
the correct type
  (datetime.time and datetime.date respectively). fields.NOT_PROVIDED  
is also checked for

  by converting to pyamf.Undefined and back again.

Check out the download page [4], installation instructions [5] or the  
API documentation [6] for more

information.

Questions? First stop is the mailing list [7] but we also hang out on  
IRC [8].


Cheers,

the PyAMF team.

[1] http://pyamf.org
[2] http://pyamf.org/milestone/0.4.1
[3] http://pyamf.org/browser/pyamf/tags/release-0.4.1/CHANGES.txt
[4] http://pyamf.org/wiki/Download
[5] http://pyamf.org/wiki/Install
[6] http://api.pyamf.org
[7] http://pyamf.org/wiki/MailingList
[8] irc://irc.collab.eu/pyamf

PGP.sig
Description: This is a digitally signed message part
--
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: Problem in identifying an archived file in Windows

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 05:40:22 -0200, venu madhav venutaurus...@gmail.com  
escribió:



   I am writing an application which has to identify the
archived files in a given directory.I've tried using the function
i = win32api.GetFileAttributes (full_path)

to obtain the attributes.But am unable to identify based on the value
it returns as it is returning 5152, 13856 etc for different files but
all of them are archived. Is there any way to come to a conclusion
using these numbers about whether a file is archived or not.


So you're using the pywin32 package. It comes with a help file  
(PyWin32.chm), you can open it right from the menu: Start, All Programs,  
Python XX, Python for Windows documentation.
Go to the GetFileAttributes topic. It says The return value is a  
combination of the win32con.FILE_ATTRIBUTE_* constants. Ok, which  
constants? Let Python tell us:


py import win32con
py [name for name in dir(win32con) if name.startswith(FILE_ATTRIBUTE_)]
['FILE_ATTRIBUTE_ARCHIVE', 'FILE_ATTRIBUTE_ATOMIC_WRITE',  
'FILE_ATTRIBUTE_COMPRESSED', 'FILE_ATTRIBUTE_DIRECTORY',  
'FILE_ATTRIBUTE_HIDDEN', 'FILE_ATTRIBUTE_NORMAL',  
'FILE_ATTRIBUTE_READONLY','FILE_ATTRIBUTE_SYSTEM',  
'FILE_ATTRIBUTE_TEMPORARY', 'FILE_ATTRIBUTE_XACTION_WRITE']


What do they mean? The best source is the Microsoft site. There is a very  
convenient link in the help topic: Search for GetFileAttributes at msdn,  
google or google groups. Click on msdn, the first result is  
http://msdn.microsoft.com/en-us/library/aa364944(VS.85).aspx

You apparently are looking for FILE_ATTRIBUTE_ARCHIVE.

--
Gabriel Genellina

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


Re: XML Parsing

2009-02-25 Thread hrishy
Hi Lie

I am not a python guy but very interested in the langauge and i consider the 
people on this list to be intelligent and was wundering why you people did not 
suggest xpath for this kind of a problem just curious and willing to learn.

I am searching for a answer but the question is 
why not use xpath to extract xml text from a xml doc ?

regards
Hrishy


--- On Wed, 25/2/09, Lie Ryan lie.1...@gmail.com wrote:

 From: Lie Ryan lie.1...@gmail.com
 Subject: Re: XML Parsing
 To: python-list@python.org
 Date: Wednesday, 25 February, 2009, 7:33 AM
 Are you searching for answer or searching for another people
 that have 
 the same answer as you? :)
 
 Many roads lead to Rome is a very famous
 quotation...
 
 --
 http://mail.python.org/mailman/listinfo/python-list


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


Re: pep 8 constants

2009-02-25 Thread Bruno Desthuilliers

Brendan Miller a écrit :

PEP 8 doesn't mention anything about using all caps to indicate a constant.

Is all caps meaning don't reassign this var a strong enough
convention to not be considered violating good python style? I see a
lot of people using it, but I also see a lot of people writing
non-pythonic code... so I thought I'd see what the consensus is.


Most - if not all - of the python code I've seen so far used this 
convention, and I always used (and respected) it myself.

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


Re: pep 8 constants

2009-02-25 Thread Bruno Desthuilliers

Ben Finney a écrit :
(snip - about using ALL_CAPS for pseudo-constants)

Perhaps I'd even
argue for an update to PEP 8 that endorses this as conventional.


+1

I've been a bit surprised last time I checked PEP8 to find out this 
wasn't already the case - I would have sweared it was.

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


Re: pep 8 constants

2009-02-25 Thread Bruno Desthuilliers

Brian Allen Vanderburg II a écrit :

bock...@virgilio.it wrote:

Constants would be a nice addition in python, sure enough.
But I'm not sure that this can be done without a run-time check every 
time

the constant is used, and python is already slow enough. Maybe a check
that is disabled when running with optimizing flags ?

But I'm sure this discussion has been already made and the FINAL WORD has
been already spoken.

  
One idea to make constants possible would be to extend properties to be 
able to exist at the module level as well as the class level:


@property
def pi():
   return 3.14159.

print(pi) # prints 3.14159
pi=32 # Raise an error Cannot set attribute ...



There are a couple problems with this suggestion:

- it would require modifying lookup rules to allow the protocol 
descriptor to be invoked on instance attributes[1] - which is not 
actually the case, by design.


- it adds the overhead of a method and a function call for what is 
mostly a simple constant attribute lookup.


FWIW, while it would already work for class-level pseudo-constants 
(using a very simple custom descriptor), I'd qualify such usage as a WTF.


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


Re: pep 8 constants

2009-02-25 Thread Bruno Desthuilliers

Ethan Furman a écrit :

Steve Holden wrote:

Brian Allen Vanderburg II wrote:


(snip)

One idea to make constants possible would be to extend properties to be
able to exist at the module level as well as the class level:

@property
def pi():
  return 3.14159.

print(pi) # prints 3.14159
pi=32 # Raise an error Cannot set attribute ...



I don't understand why this would print 3.14159 ... instead of function
__math__.pi, or whatever.

property would clearly have to do something very different in module
scope in order to make this work.



-- class tester(object):
...   @property
...   def pi(self):
... return 3.141596
...
-- testee = tester()
-- testee.pi
3.14159598

Looks like that's how property works, so the same behavior on a module 
level would do as Brian suggests.


s/module/instance/

At runtime, modules are instances of the module type - so 'module-level' 
names are really instance attributes of the module instance -, and the 
descriptor protocol is only invoked for class attributes.

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


variable length tuple assignment

2009-02-25 Thread Helmut Jarausch

Sorry if this is too simple but I couldn't find.

I vaguely remember there is a means to assign a variable length tuple
and catch the 'rest'  like

S=a,b,c,d

(A,B,list of remaining items) = S.split(',')

I know I could do
SL= split(',')
(A,B)=SL[:2]
Rest= SL[2:]

but is there some shorthand for this?

Many thanks for a hint,

Helmut Jarausch

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


Re: 'u' Obselete type – it is identical to 'd'. (7)

2009-02-25 Thread mathieu
On Feb 24, 11:06 pm, Steven D'Aprano st...@pearwood.info wrote:
 mathieu wrote:
  I did not know where to report that:

  'u'   Obselete type – it is identical to 'd'. (7)

 http://docs.python.org/library/stdtypes.html#string-formatting

  Thanks

 If you google on python bug tracker the first link is the correct one.

 I don't know what you want to report, but I've reported that obsolete is
 mispelled:

 http://bugs.python.org/issue5361

Thanks. Now I know :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: 'u' Obselete type – it is identical to 'd'. (7 )

2009-02-25 Thread mathieu
On Feb 24, 9:24 pm, John Machin sjmac...@lexicon.net wrote:
 On Feb 25, 4:48 am, mathieu mathieu.malate...@gmail.com wrote:

  I did not know where to report that:

  'u' Obselete type – it is identical to 'd'.   (7)

 http://docs.python.org/library/stdtypes.html#string-formatting

 So what's your problem with that? Do you believe that 'u' is not
 accepted? That 'u' is not identical to 'd' and thus the doc should be
 rewritten as its behaviour is identical to that of 'd'? That the
 behaviour of 'u' is NOT identical to that of 'd'? That 'u' should not
 be documented? That 'u' should not be described as obselete?
 

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


Re: variable length tuple assignment

2009-02-25 Thread Chris Rebert
On Wed, Feb 25, 2009 at 1:16 AM, Helmut Jarausch
jarau...@igpm.rwth-aachen.de wrote:
 Sorry if this is too simple but I couldn't find.

 I vaguely remember there is a means to assign a variable length tuple
 and catch the 'rest'  like

 S=a,b,c,d

 (A,B,list of remaining items) = S.split(',')

In Python 3.0 (IIRC):

A, B, *rest = S.split(',')

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: pep 8 constants

2009-02-25 Thread Robin Becker
well this sort of awful hackery will allow you to put read only constants on an 
existing module


 import reportlab
 reportlab.__class__
 class MyModule(reportlab.__class__):
... @property
... def pi(self):
... return 3
...
 z=MyModule('reportlab')
 z.__dict__.update(reportlab.__dict__)
 z.pi
3
 import sys
 sys.modules['reportlab']=z
 del reportlab
 import reportlab
 reportlab.pi
3
 reportlab.pi=4
Traceback (most recent call last):
  File interactive input, line 1, in module
AttributeError: can't set attribute


so I guess if you write your own module class and then use a special importer 
you can create module like objects with read only attributes.



--
Robin Becker

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


Re: Is there a way to increase memory allocated to the python interpreter

2009-02-25 Thread Roger Binns
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

janandith jayawardena wrote:
 Is there a way to configure the amount of memory allocated to the python
 interpreter.  Can it be increased or decreased using an argument like in
 the Java Virtual Machine.

Java needs the memory allocation number because of the way garbage
collection is done (or at least used to be done).  The CPython
interpreter doesn't have an explicit limit and will use all the address
space the operating system will let it have as needed.  (That typically
works out as around 2GB for a 32 bit process and exhausting swap space
on a 64 bit process).

If you want to prevent using more than a certain amount, then use
functionality provided by your operating system.  On Unix/Linux systems
the ulimit command will do the trick.

Roger
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkmlGMMACgkQmOOfHg372QQeMACfVhyccV91nU0WZswc2CNg8KMv
SlEAoMINnO48FoDp0vgxROOWAjYp2tPG
=Vjcf
-END PGP SIGNATURE-

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


Re: Unix Change Passwd Python CGI

2009-02-25 Thread Roger Binns
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Derek Tracy wrote:
 Apache is running on the same system that needs the password changed.  I
 need to keep security high and can not install additional modules at
 this time.
 
 I just need a general direction to start looking, and I do not have
 expect installed on the system.

I recommend looking in the Samba source code where they have a program
that does just that.

Roger
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkmlGVcACgkQmOOfHg372QTZHACdFG0+Ls2Su/jRqkc4YZyxXK35
N7AAoNKfd7bMypR7b6Ex6auaU/9D4rKa
=POal
-END PGP SIGNATURE-

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


Re: pep 8 constants

2009-02-25 Thread Bruno Desthuilliers

Robin Becker a écrit :
well this sort of awful hackery will allow you to put read only 
constants on an existing module



(snip example code)


so I guess if you write your own module class and then use a special 
importer you can create module like objects with read only attributes.




Fine technical solution. But, err, isn't all this a bit overkill for 
something that can easily be handled by a simple convention ?-)


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


H-Index with Google Scholar

2009-02-25 Thread Gonsolo
I wrote a small script to compute the H-Index of an author.
It is modeled after activestate's google search:
http://code.activestate.com/recipes/523047/

Example use:
hindex i daubechies
Result:
49

The script:

#!/usr/bin/python

import httplib, urllib, re, sys
from BeautifulSoup import BeautifulSoup

terms = sys.argv[1:]
limit = 100
params = urllib.urlencode( { 'q': +.join( terms ), 'num': limit } )
headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows
NT)'}
url = '/scholar'+?+params
conn = httplib.HTTPConnection( 'scholar.google.com' )
conn.request( GET, url, {}, headers )

resp = conn.getresponse()
cites = []
if resp.status == 200:
html = resp.read()
html = html.decode( 'ascii', 'ignore' )
soup = BeautifulSoup( html )
for record in soup( 'p', { 'class': 'g' } ):
match = re.search(Cited by ([^]*), str(record))
if match != None:
cite = int( match.group( 1 ) )
cites.append( cite )
else:
print 'Error: '
print resp.status, resp.reason

cites.sort()
cites.reverse()

h = 0
for cite in cites:
if cite  h:
h += 1
print h
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Image Library IOError - cannot find JPEG decoder?

2009-02-25 Thread wongobongo
On Feb 24, 9:34 am, Dario Traverso traver...@gmail.com wrote:
 I've been trying to install the Python Image Library  (PIL) on my Mac  
 OSX Leopard laptop, but have been running into some difficulties.

 I've built the library, using the included setup.py  script. The build  
 summary checks out ok, and sounds the option libraries to all be  
 found. I grabbed both libjpeg and freetype2  using  fink.

 
 PIL 1.1.6 BUILD SUMMARY
 
 version       1.1.6
 platform      darwin 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)
               [GCC 4.0.1 (Apple Inc. build 5465)]
 
 --- TKINTER support ok
 --- JPEG support ok
 --- ZLIB (PNG/ZIP) support ok
 --- FREETYPE2 support ok
 

 However,  I then run the included self test, and 1 out of 57 tests  
 fails. I receive an IOError. Specifically:

 *
 Failure in example: _info(Image.open(Images/lena.jpg))
 from line #24 of selftest.testimage
 Exception raised:
 Traceback (most recent call last):
   File ./doctest.py, line 499, in _run_examples_inner
     exec compile(source, string, single) in globs
   File string, line 1, in module
   File ./selftest.py, line 22, in _info
     im.load()
   File PIL/ImageFile.py, line 180, in load
     d = Image._getdecoder(self.mode, d, a, self.decoderconfig)
   File PIL/Image.py, line 375, in _getdecoder
     raise IOError(decoder %s not available % decoder_name)
 IOError: decoder jpeg not available
 1 items had failures:
    1 of  57 in selftest.testimage
 ***Test Failed*** 1 failures.
 *** 1 tests of 57 failed.

 I've followed all of the installation instructions exactly. The build  
 summary reported everything was ok. What could be the problem here.  
 Libjpeg-6b  is not accessible?

 Thank you for any insight you can provide!!

 -Dario


That would be my guess.

Two things you may want to try:

1. Check that your Fink libraries and headers were used to make your
PIL (check -I and -L settings on gcc after doing python setup.py
build_ext -i). They should point to your Fink lib and include dirs.
2. Line 372 in PIL/Image.py has a debug print line. Try uncommenting
that and see what comes out.

That might give you some clues as to what is going on. You can always
just call up Python in a terminal and try it out (from selftest.py
doctests beginning on line 29).

 import Image
 def _info(im):
...im.load()
...return im.format, im.mode, im.size
 im = Image.new(1, (128, 128))
 _info(im)
(None, '1', (128, 128))

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


Re: pep 8 constants

2009-02-25 Thread Robin Becker

Bruno Desthuilliers wrote:

Robin Becker a écrit :
well this sort of awful hackery will allow you to put read only 
constants on an existing module



(snip example code)


so I guess if you write your own module class and then use a special 
importer you can create module like objects with read only attributes.




Fine technical solution. But, err, isn't all this a bit overkill for 
something that can easily be handled by a simple convention ?-)

..
no dispute about that :)
--
Robin Becker

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


Re: reading file to list

2009-02-25 Thread nick_keighley_nospam
On 24 Feb, 15:00, nick_keighley_nos...@hotmail.com wrote:
 On 17 Jan, 17:16, Xah Lee xah...@gmail.com wrote:

  Here's a interesting toy problem posted by Drew Krause to
  comp.lang.lisp:

  
  On Jan 16, 2:29 pm, Drew Krause wrote [paraphrased a bit]:

  OK, I want to create a nested list in Lisp (always of only integers)
  from a text file, such that each line in the text file would be
  represented as a sublist in the 'imported' list.

  example of a file's content

  3 10 2
  4 1
  11 18

  example of programing behavior
  (make-list-from-text blob.txt) = ((3 10 2) (4 1) (11 18))

snip

 scheme:

 (define (read-line port)
     (define (rec-read-line port line)
         (define next-char (peek-char port))
         (define number #f)
         (cond ((eof-object? next-char) '())
               ((char=? next-char #\newline) (read-char port) line)
               ((char-numeric? next-char)
                    (set! number (read port))
                    (cons number (rec-read-line port line)))
               ((char=? next-char #\space)
                    (read-char port)
                    (rec-read-line port line))
               (else (error (string-append bad character \
                               (string next-char) \)))
     ))

     (rec-read-line port '())
 )

 (define (make-int-list port)
     (define line (read-line port))
     (if (null? line)
         '()
         (cons line (make-int-list port

 (define (make-list-from-text file)
     (make-int-list (open-input-file file)))

an assignment-free version

(define (read-line port)
(define (rec-read-line port line)
(let ((next-char (peek-char port)))
(cond ((eof-object? next-char) '())
  ((char=? next-char #\newline) (read-char port) line)
  ((char-numeric? next-char)
   (let ((number (read port)))
   (cons number (rec-read-line port line
  ((char=? next-char #\space)
   (read-char port)
   (rec-read-line port line))
  (else (error (string-append bad character \
   (string next-char) \))

(rec-read-line port '()))

(define (make-int-list port)
(let ((line (read-line port)))
(if (null? line)
'()
(cons line (make-int-list port)

(define (make-list-from-text file)
(make-int-list (open-input-file file)))

(define (mk) (make-list-from-text blob.txt))

snip

number was originally define'd but I discovered there were
limits to where you could define things
--
http://mail.python.org/mailman/listinfo/python-list


Re: reading file to list

2009-02-25 Thread nick_keighley_nospam
On 17 Jan, 17:16, Xah Lee xah...@gmail.com wrote:
 comp.lang.lisp,comp.lang.scheme,comp.lang.functional,comp.lang.python,comp.­lang.ruby

snip

 The lisp's cons fundamentally makes nested list a pain to work with.
 Lisp's nested syntax makes functional sequencing cumbersome.

so hide it

(define (make-list stream eos?)
(let ((atom (stream)))
(if (eos? atom)
'()
(cons atom (make-list stream eos?)

(define (make-int-list port)
(make-list (lambda () (read-line port)) null?))

the nasty cons then only appears in a single function which
you can hide in a library


 In the ruby code, its post-fix sequential notation (as a side effect
 of its OOP notation) brings out the beauty of functional sequencing
 paradigm (sometimes known as functional chain, sequencing, filtering,
 unix piping).

 its list, like all modern high level langs such as perl, php, python,
 javascript, don't have the lisp's cons problem. The cons destroys the
 usability of lists up-front, untill you have some at least 2 full-time
 years of coding lisp to utilize cons properly. (and even after that,
 it is still a pain to work with, and all you gain is a bit of speed
 optimization in rare cases that requires largish data, most of which
 has better solutions such as a database.)

is my code to build a list that bad?


 Both of these problems i've published articles on.

 For more detail on the cons problem, see
 the section “The Cons Business” at

 • Fundamental Problems of Lisp
  http://xahlee.org/UnixResource_dir/writ/lisp_problems.html

I read it. Your point seems to be cons becomes difficult
with deeply nested structures. Could you give an example?
--
http://mail.python.org/mailman/listinfo/python-list


Re: variable length tuple assignment

2009-02-25 Thread Tim Chase

Chris Rebert wrote:

On Wed, Feb 25, 2009 at 1:16 AM, Helmut Jarausch
jarau...@igpm.rwth-aachen.de wrote:

Sorry if this is too simple but I couldn't find.

I vaguely remember there is a means to assign a variable length tuple
and catch the 'rest'  like

S=a,b,c,d

(A,B,list of remaining items) = S.split(',')


In Python 3.0 (IIRC):

A, B, *rest = S.split(',')


As an aside, as of the last time I read the PEP[1] on this, I 
believe it exhausts (or attempts to exhaust) any iterator.  IMHO, 
I think this exhausting is a bad idea because it prevents things like


  def numbers(start=0):
i = start
while True:
  yield i
  i += 1

  CONST_A, CONST_B, CONST_C, *rest = numbers()

which will hang in current Py3.0 until you blow a stack or 
overrun your heap somewhere because it will try to exhaust the 
infinite loop.  It also changes the type from iter() to list() 
for the remaining content (not as grevious).



I agree that the internal star usage needs to exhaust the iterator:

  A, *rest, C, D = s.split(',')

but the terminal-star syntax should be a little more gracious 
with iterators.


Anyways, my $0.02 (minus taxes, money for multiple bailouts, and 
deflated by economic conditions -- so not worth much :).


-tkc

[1]
http://www.python.org/dev/peps/pep-3132/






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


PyCrypto AES MODE_CBC - How to?

2009-02-25 Thread Helmut Jarausch

Hi,

I've just tried to write a simple example using PyCrypto's
AES (CBC mode)

#!/usr/bin/python
from Crypto.Cipher import AES

PWD='abcdefghijklmnop'
Initial16bytes='0123456789ABCDEF'

crypt = AES.new(PWD, AES.MODE_CBC,Initial16bytes)
# crypt = AES.new(PWD, AES.MODE_ECB)

txt = 'ea523a664dabaa4476d31226a1e3bab0'

c = crypt.encrypt(txt)

txt_plain=crypt.decrypt(c)

print txt_plain

Unfortunately, txt_plain differs from txt - why?
(Using MODE_ECB does work however)

What am I missing?

Many thanks for a hint,

Helmut Jarausch

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


Lambda function

2009-02-25 Thread aditya saurabh
I defined two functions - lets say
fa = lambda x: 2*x
fb = lambda x: 3*x
Now I would like to use fa*fb in terms of x
is there a way?
Thanks in advance
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyCrypto AES MODE_CBC - How to?

2009-02-25 Thread Helmut Jarausch

Helmut Jarausch wrote:

Hi,

I've just tried to write a simple example using PyCrypto's
AES (CBC mode)

#!/usr/bin/python
from Crypto.Cipher import AES

PWD='abcdefghijklmnop'
Initial16bytes='0123456789ABCDEF'

crypt = AES.new(PWD, AES.MODE_CBC,Initial16bytes)
# crypt = AES.new(PWD, AES.MODE_ECB)

txt = 'ea523a664dabaa4476d31226a1e3bab0'

c = crypt.encrypt(txt)

txt_plain=crypt.decrypt(c)

print txt_plain

Unfortunately, txt_plain differs from txt - why?
(Using MODE_ECB does work however)



I just discovered that the following variant seems to work
crypt = AES.new(PWD, AES.MODE_CBC,Initial16bytes)
c = crypt.encrypt(txt)
crypt = AES.new(PWD, AES.MODE_CBC,Initial16bytes) #  re-initialize
txt_plain=crypt.decrypt(c)

So, the crypt object seems to keep some state.
I haven't seen this mentioned in the documentation.

Helmut.


--
Helmut Jarausch

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


Re: XML Parsing

2009-02-25 Thread J. Clifford Dyer
Probably because you responded an hour after the question was posted,
and in the dead of night.  Newsgroups often move slower than that.  But
now we have posted a solution like that, so all's well in the world.  :)

Cheers,
Cliff


On Wed, 2009-02-25 at 08:20 +, hrishy wrote:
 Hi Lie
 
 I am not a python guy but very interested in the langauge and i consider the 
 people on this list to be intelligent and was wundering why you people did 
 not suggest xpath for this kind of a problem just curious and willing to 
 learn.
 
 I am searching for a answer but the question is 
 why not use xpath to extract xml text from a xml doc ?
 
 regards
 Hrishy
 
 
 --- On Wed, 25/2/09, Lie Ryan lie.1...@gmail.com wrote:
 
  From: Lie Ryan lie.1...@gmail.com
  Subject: Re: XML Parsing
  To: python-list@python.org
  Date: Wednesday, 25 February, 2009, 7:33 AM
  Are you searching for answer or searching for another people
  that have 
  the same answer as you? :)
  
  Many roads lead to Rome is a very famous
  quotation...
  
  --
  http://mail.python.org/mailman/listinfo/python-list
 
 
   
 --
 http://mail.python.org/mailman/listinfo/python-list
 

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


Re: Convert PySerial to python 3.0

2009-02-25 Thread Seth
On Feb 24, 10:55 pm, Chris Rebert c...@rebertia.com wrote:
 On Tue, Feb 24, 2009 at 7:46 PM, Seth king.s...@gmail.com wrote:
  I am just messing around trying to get pyserial to work with 3.0.

  I am stuck on this line:

  if type(port) in [type(''), type(u'')]

  how can I convert this to 3.0? I tried changing the u to a d that did
  not do anything.

 Looks like it's doing the equivalent of the pre-3.0-ism
 `isinstance(port, basestring)`, but in a roundabout way.
 However, since basestring doesn't exist in 3.0, either:

 if isinstance(port, str):

 Or

 if isinstance(port, bytes):

 would be the appropriate replacement. Depends (obviously) on whether
 'port' is supposed to be unicode or a byte sequence.
 Without more context, I can't really say which is what you want.

 Cheers,
 Chris

 --
 Follow the path of the Iguana...http://rebertia.com

I implemented if isinstance(port, str):  that seems to work for now.

Currently I am running into:

err, n = win32file.WriteFile(self.hComPort, data,
self._overlappedWrite)
TypeError: expected an object with a buffer interface

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


glibc detected *** python: corrupted double-linked list

2009-02-25 Thread Christian Meesters
Hoi,

I have a problem using my software on my 64bit laptop, after an update of
my system. The same code still runs on 32bit Intel, but on my laptop I
provoke the crash in the title. The crash is caused - as narrowed down by
me - by returning a static PyObject from a C-extension function.

Well, now I wondering what to do? A web search delivered no relevant bug
reports about glibc on my system (the recent Ubuntu 8.10). Is there a
source for validated glibc for x86_64? Oh, and I'm using Ubuntu's ready-
made Python package, version 2.5.2..

Anyone experiences with such problems? Any ideas? Information missing?

TIA
Christian

PS The extension module itself can be found here: http://
svn.origo.ethz.ch/viewvc/sas-rigid/src/calc.c?revision=209view=markup
But, as I said, the code is perhaps far from being perfect, but it runs on
32bit computers. The crash occurs at line 164 - return py_pofr;.

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


Free Python Training

2009-02-25 Thread Steve Holden
Not a joke, but a genuine offer extended to anyone who has already
contributed to some open source project. See my blog for full details,
and please pass this on to non-Python programmers who are interested in
learning the language.

  http://holdenweb.blogspot.com/2009/02/free-python-training.html

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: glibc detected *** python: corrupted double-linked list

2009-02-25 Thread David Cournapeau
On Wed, Feb 25, 2009 at 9:40 PM, Christian Meesters meest...@gmx.de wrote:
 Hoi,

 I have a problem using my software on my 64bit laptop, after an update of
 my system. The same code still runs on 32bit Intel, but on my laptop I
 provoke the crash in the title. The crash is caused - as narrowed down by
 me - by returning a static PyObject from a C-extension function.

Those errors are caused by writing in an invalid pointer, but not far
enough to cause a direct segfault - just enough to corrupt core data
structures of the runtime :)


 Well, now I wondering what to do? A web search delivered no relevant bug
 reports about glibc on my system (the recent Ubuntu 8.10). Is there a
 source for validated glibc for x86_64? Oh, and I'm using Ubuntu's ready-
 made Python package, version 2.5.2..

It is very unlikely the problem is in glibc - I would check your code
carefully first :) On Linux, the following are useful:
 - first, try to compile with as many warning flags as possible (-W
-Wall -Wextra is a pretty good baseline)
 - then, if you have a small reproducible crash, run the extension
under valgrind after having built the extension with -g. This will
give you more informations.
 - if the above does not help, using gdb can help too.

If the program works in 32 but not in 64, there are several things to
look at (long is 8 bytes, not 4 on Linux, so some long - int
convertion may be broken). Sometimes, the program just happens to work
on 32 bits, but by accident (running valgrind on both 32 and 64 bits
may be helpful too).

cheers,

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


sorting tasks by importance and urgency

2009-02-25 Thread Alia Khouri
I recently considered the apparently simple problem is of how to
algorithmically sort a set of business tasks which have an associated
a value and a due_date, such that the most important and urgent are
pushed to the top of the stack.

The two example task types I am posing here are: (1) a bid on a
contract and (2) leaverequest from an employee.

To sort by importance: I just consider the proportional value of each
task in relation to the total value of tasks.

To sort by urgency: I used something along the lines of excel's
percentrank function (http://office.microsoft.com/en-us/excel/
HP052092121033.aspx) to rank the tasks in percentage terms of the set
of days_to delivery.

The code is pretty self-explanatory, and I think the algorithm seems
to work ok so far, but in case I have missed something or there exists
some better way of doing this...

priority.py
from datetime import date

weights = {
'Tender'  : 1.0,
'LeaveRequest': 0.1
}

rnd = lambda x: round(x,2)

class Task(object):
a simple prioritizing Task class

def __init__(self, kind, value, due_date=None):
self.kind = kind
self.value = value
self.due_date = due_date if due_date else date.today()
self.weight = weights[kind]
self.urgency = 0.0
self.importance = 0.0

def __repr__(self):
return 'Task: %5s - %4s - %5s - %12s - %3s - %s' % (
rnd(self.priority), rnd(self.importance), rnd
(self.urgency),
self.kind, self.days_to, self.value)

def __cmp__(self, other):
return cmp(self.priority, other.priority)

@property
def days_to(self):
return (self.due_date - date.today()).days

@property
def priority(self):
return self.weight * (self.importance + self.urgency)

def relative_urgency(self, N, due_days):
rank = due_days.index(self.days_to)
return float(rank) / (N - 1)

def relative_importance(self, total_value):
return self.value / total_value

@staticmethod
def prioritize(tasks):
print (Task: priority - importance - urgency - 
   kind - days_to - value\n)
N = len(tasks)
total_value = sum(t.value for t in tasks)
due_days = sorted([t.days_to for t in tasks], reverse=True)
for i in tasks:
i.importance = i.relative_importance(total_value)
i.urgency = i.relative_urgency(N, due_days)

for i in sorted(tasks, reverse=True):
print i

tasks = [
# name   value   due_date
Task(Tender,   100.0,  date(2009,4,1)),
Task(Tender,   500400.0,   date(2009,5,1)),
Task(Tender,   100.0,  date(2009,6,1)),
Task(LeaveRequest, 0.0,date(2009,7,1)),
Task(LeaveRequest, 0.0,date(2009,8,1)),
]


if __name__ == '__main__':
Task.prioritize(tasks)

/priority.py

regards,

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread rdmurray
John Machin sjmac...@lexicon.net wrote:
 On Feb 25, 11:07=A0am, Roy H. Han starsareblueandfara...@gmail.com
 wrote:
  Dear python-list,
 
  I'm having some trouble decoding an email header using the standard
  imaplib.IMAP4 class and email.message_from_string method.
 
  In particular, email.message_from_string() does not seem to properly
  decode unicode characters in the subject.
 
  How do I decode unicode characters in the subject?
 
 You don't. You can't. You decode str objects into unicode objects. You
 encode unicode objects into str objects. If your input is not a str
 object, you have a problem.

I can't speak for the OP, but I had a similar (and possibly
identical-in-intent) question.  Suppose you have a Subject line that
looks like this:

Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
=?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=

How do you get the email module to decode that into unicode?  The same
question applies to the other header lines, and the answer is it isn't
easy, and I had to read and reread the docs and experiment for a while
to figure it out.  I understand there's going to be a sprint on the
email module at pycon, maybe some of this will get improved then.

Here's the final version of my test program.  The third to last line is
one I thought ought to work given that Header has a __unicode__ method.
The final line is the one that did work (note the kludge to turn None
into 'ascii'...IMO 'ascii' is what deocde_header _should_ be returning,
and this code shows why!)

---
from email import message_from_string
from email.header import Header, decode_header

x = message_from_string(\
To: test
Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
=?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=

this is a test.
)

print x
print 
for key, header in x.items():
print key, 'type', type(header)
print key+:, unicode(Header(header)).decode('utf-8')
print key+:, decode_header(header)
print key+:, ''.join([s.decode(t or 'ascii') for (s, t) in 
decode_header(header)]).encode('utf-8')
---


From nobody Wed Feb 25 08:35:29 2009
To: test
Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=
=?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=

this is a test.


To type type 'str'
To: test
To: [('test', None)]
To: test
Subject type type 'str'
Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
=?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=
Subject: [('u' Obselete type, None), (-- it is identical to 'd'. (7), 
'iso-8859-1')]
Subject: 'u' Obselete type-- it is identical to 'd'. (7)


--RDM

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


Re: Convert PySerial to python 3.0

2009-02-25 Thread Christian Heimes
Seth wrote:
 I implemented if isinstance(port, str):  that seems to work for now.
 
 Currently I am running into:
 
 err, n = win32file.WriteFile(self.hComPort, data,
 self._overlappedWrite)
 TypeError: expected an object with a buffer interface

Unicode objects (in Py3k: str) don't implement the buffer interface. You
have to apply a bytes or bytearray instance.

Christian

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


Re: Python Imaging Library (PIL): create PDF from scratch

2009-02-25 Thread zelegolas
Like David said now i used PIL for individual images and reportlab to
generate a pdf.

Thanks for your advices :)

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


Re: Forwarding keyword arguments from one function to another

2009-02-25 Thread Ravi
Thnak you all.

 In the future, explain didn't work.
 Wrong output? give actual (copy and paste) and expected.
 Error message? give traceback (copy and paste).

I will be careful.
--
http://mail.python.org/mailman/listinfo/python-list


Re: XML Parsing

2009-02-25 Thread Paul McGuire
On Feb 25, 1:17 am, hrishy hris...@yahoo.co.uk wrote:
 Hi

 Something like this

snip solution using ElementTree

 Note i am not a python programmer just a enthusiast and i was curious why 
 people on the list didnt suggest a code like above


You just beat the rest of us to it - good example of ElementTree for
parsing XML (and I Iearned the '//' shortcut for one or more
intervening tag levels).

To the OP: if you are parsing XML, I would look hard at the modules
(esp. ElementTree) that are written explicitly for XML, before
considering using regular expressions.  There are just too many
potential surprises when trying to match XML tags - presence/absence/
order of attributes, namespaces, whitespace inside tags, to name a
few.

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Roy H. Han
Thanks for writing back, RDM and John Machin.  Tomorrow I'll try the
code you suggested, RDM.  It looks quite helpful and I'll report the
results.

In the meantime, John asked for more data.  The sender's email client
is Microsoft Outlook 11.  The recipient email client is Lotus Notes.



Actual Subject
=?us-ascii?Q?Inteum_C/SR_User_Tip:__Quick_Access_to_Recently_Opened_Inteu?=\r\n\t=?us-ascii?Q?m_C/SR_Records?=

Expected Subject
Inteum C/SR User Tip: Quick Access to Recently Opened Inteum C/SR Records

X-Mailer
Microsoft Office Outlook 11

X-MimeOLE
Produced By Microsoft MimeOLE V6.00.2900.5579



RHH



On Wed, Feb 25, 2009 at 8:39 AM,  rdmur...@bitdance.com wrote:
 John Machin sjmac...@lexicon.net wrote:
 On Feb 25, 11:07=A0am, Roy H. Han starsareblueandfara...@gmail.com
 wrote:
  Dear python-list,
 
  I'm having some trouble decoding an email header using the standard
  imaplib.IMAP4 class and email.message_from_string method.
 
  In particular, email.message_from_string() does not seem to properly
  decode unicode characters in the subject.
 
  How do I decode unicode characters in the subject?

 You don't. You can't. You decode str objects into unicode objects. You
 encode unicode objects into str objects. If your input is not a str
 object, you have a problem.

 I can't speak for the OP, but I had a similar (and possibly
 identical-in-intent) question.  Suppose you have a Subject line that
 looks like this:

    Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
 =?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=

 How do you get the email module to decode that into unicode?  The same
 question applies to the other header lines, and the answer is it isn't
 easy, and I had to read and reread the docs and experiment for a while
 to figure it out.  I understand there's going to be a sprint on the
 email module at pycon, maybe some of this will get improved then.

 Here's the final version of my test program.  The third to last line is
 one I thought ought to work given that Header has a __unicode__ method.
 The final line is the one that did work (note the kludge to turn None
 into 'ascii'...IMO 'ascii' is what deocde_header _should_ be returning,
 and this code shows why!)

 ---
 from email import message_from_string
 from email.header import Header, decode_header

 x = message_from_string(\
 To: test
 Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
 =?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=

 this is a test.
 )

 print x
 print 
 for key, header in x.items():
    print key, 'type', type(header)
    print key+:, unicode(Header(header)).decode('utf-8')
    print key+:, decode_header(header)
    print key+:, ''.join([s.decode(t or 'ascii') for (s, t) in 
 decode_header(header)]).encode('utf-8')
 ---


    From nobody Wed Feb 25 08:35:29 2009
    To: test
    Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=
            =?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=

    this is a test.

    
    To type type 'str'
    To: test
    To: [('test', None)]
    To: test
    Subject type type 'str'
    Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
 =?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=
    Subject: [('u' Obselete type, None), (-- it is identical to 'd'. (7), 
 'iso-8859-1')]
    Subject: 'u' Obselete type-- it is identical to 'd'. (7)


 --RDM

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

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Steve Holden
Roy H. Han wrote:
 On Wed, Feb 25, 2009 at 8:39 AM,  rdmur...@bitdance.com wrote:
[Top-posting corrected]
 John Machin sjmac...@lexicon.net wrote:
 On Feb 25, 11:07=A0am, Roy H. Han starsareblueandfara...@gmail.com
 wrote:
 Dear python-list,

 I'm having some trouble decoding an email header using the standard
 imaplib.IMAP4 class and email.message_from_string method.

 In particular, email.message_from_string() does not seem to properly
 decode unicode characters in the subject.

 How do I decode unicode characters in the subject?
 You don't. You can't. You decode str objects into unicode objects. You
 encode unicode objects into str objects. If your input is not a str
 object, you have a problem.
 I can't speak for the OP, but I had a similar (and possibly
 identical-in-intent) question.  Suppose you have a Subject line that
 looks like this:

Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
 =?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=

 How do you get the email module to decode that into unicode?  The same
 question applies to the other header lines, and the answer is it isn't
 easy, and I had to read and reread the docs and experiment for a while
 to figure it out.  I understand there's going to be a sprint on the
 email module at pycon, maybe some of this will get improved then.

 Here's the final version of my test program.  The third to last line is
 one I thought ought to work given that Header has a __unicode__ method.
 The final line is the one that did work (note the kludge to turn None
 into 'ascii'...IMO 'ascii' is what deocde_header _should_ be returning,
 and this code shows why!)

 ---
 from email import message_from_string
 from email.header import Header, decode_header

 x = message_from_string(\
 To: test
 Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
 =?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=

 this is a test.
 )

 print x
 print 
 for key, header in x.items():
print key, 'type', type(header)
print key+:, unicode(Header(header)).decode('utf-8')
print key+:, decode_header(header)
print key+:, ''.join([s.decode(t or 'ascii') for (s, t) in 
 decode_header(header)]).encode('utf-8')
 ---


From nobody Wed Feb 25 08:35:29 2009
To: test
Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=
=?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=

this is a test.


To type type 'str'
To: test
To: [('test', None)]
To: test
Subject type type 'str'
Subject: 'u' Obselete type =?ISO-8859-1?Q?--_it_is_identical_?=   
 =?ISO-8859-1?Q?to_=27d=27=2E_=287=29?=
Subject: [('u' Obselete type, None), (-- it is identical to 'd'. (7), 
 'iso-8859-1')]
Subject: 'u' Obselete type-- it is identical to 'd'. (7)


 Thanks for writing back, RDM and John Machin.  Tomorrow I'll try the
 code you suggested, RDM.  It looks quite helpful and I'll report the
 results.
 
 In the meantime, John asked for more data.  The sender's email client
 is Microsoft Outlook 11.  The recipient email client is Lotus Notes.
 
 
 
 Actual Subject
 =?us-ascii?Q?Inteum_C/SR_User_Tip:__Quick_Access_to_Recently_Opened_Inteu?=\r\n\t=?us-ascii?Q?m_C/SR_Records?=
 
 Expected Subject
 Inteum C/SR User Tip: Quick Access to Recently Opened Inteum C/SR Records
 
 X-Mailer
 Microsoft Office Outlook 11
 
 X-MimeOLE
 Produced By Microsoft MimeOLE V6.00.2900.5579
 
 from email.header import decode_header
 print
decode_header(=?us-ascii?Q?Inteum_C/SR_User_Tip:__Quick_Access_to_Recently_Opened_Inteu?=\r\n\t=?us-ascii?Q?m_C/SR_Records?=)
[('Inteum C/SR User Tip:  Quick Access to Recently Opened Inteum C/SR
Records', 'us-ascii')]


regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Free Python Training: Washington, DC (3/3-5)

2009-02-25 Thread Aahz
In article mailman.729.1235566709.11746.python-l...@python.org,
Steve Holden  st...@holdenweb.com wrote:

Not a joke, but a genuine offer extended to anyone who has already
contributed to some open source project. See my blog for full details,
and please pass this on to non-Python programmers who are interested in
learning the language.

  http://holdenweb.blogspot.com/2009/02/free-python-training.html

Fixed the Subject: line for you.  ;-)
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python dictionary size/entry limit?

2009-02-25 Thread Stefan Behnel
Martin v. Löwis wrote:
 intellimi...@gmail.com wrote:
 Is there a limit to the size or number of entries that a single 
 dictionary can possess?
 
 On a 32-bit system, the dictionary can have up to 2**31 slots,
 meaning that the maximum number of keys is slightly smaller
 (about 2**30).

Which, in practice, means that the size is limited by the available memory.

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


Re: Lambda function

2009-02-25 Thread Albert Hopkins
On Wed, 2009-02-25 at 17:56 +0530, aditya saurabh wrote:
 I defined two functions - lets say
 fa = lambda x: 2*x
 fb = lambda x: 3*x
 Now I would like to use fa*fb in terms of x
 is there a way?
 Thanks in advance

I'm not sure what use fa*fb in terms of x means.

But if you mean fa(x) * fb(x) then it's just:

fa(x) * fb(x)

-a

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


Re: Extending Python Questions .....

2009-02-25 Thread Ben
On Feb 24, 11:31 am, Nick Craig-Wood n...@craig-wood.com wrote:
 Ben bnsili...@gmail.com wrote:
   No, It uses the the S-lang for video, and input control. However, SLAG
   is more of an abstract layer on top of that.

   It has a Structures that contains menus and screens (menumodule /
   screenmodule). One LOADS them up with parameters.  such as creating
   a new menu is like:

   OpenMenu( Company name, SubSystem, this program name, mode, bottom
   status display) - Create initial menu structure Addtomenu(Menu
   Block Set name, DISPLAY line, ID, type of program, password ID ) -
   add to / update MENU blocks.  runMenu() - Displays the whole create
   menu structure.

   The Menu structure is done in pull downs and scrollable blocks in a
   TUI (text User Interface) and using the S-lang screen library is
   fully mouseable.

   The screen module works mych the same way, but with the abiltity to
   open and close and work within Sub Screens.

   For those who do not know, S-lang is a interpreted language much
   like Python. However, there is s direth of library modules. The
   original S-lang started out as library of screen of keyboard
   modules, but has been expanded

   My SLAG project does not care in reality WHICH or what language, it
   is simply handling menu and screen control.

 So do you want to embed python into your code?

 I'm still not clear what you are trying to achieve with python, though
 I have a better idea what SLAG is now!

 --
 Nick Craig-Wood n...@craig-wood.com --http://www.craig-wood.com/nick

Actually no, I want to EXTEND python using the lower levels of S-lang
screen modules.

My Modules are written in C and are a frame work for building pull-
down menus and data entry screens.

Very nice for writing business applications. Think along the lines of
FoxPro and/or the
Screen section in Cobol and you have a pretty good idea of what i
have done.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread rdmurray
Steve Holden st...@holdenweb.com wrote:
  from email.header import decode_header
  print
 decode_header(=?us-ascii?Q?Inteum_C/SR_User_Tip:__Quick_Access_to_Recently_Opened_Inteu?=\r\n\t=?us-ascii?Q?m_C/SR_Records?=)
 [('Inteum C/SR User Tip:  Quick Access to Recently Opened Inteum C/SR
 Records', 'us-ascii')]
 

It is interesting that decode_header does what I would consider to be
the right thing (from a pragmatic standpoint) with that particular bit
of Microsoft not-quite-standards-compliant brain-damage; but, removing
the tab is not in fact standards compliant if I'm reading the RFC
correctly.

--RDM

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


Re: Convert PySerial to python 3.0

2009-02-25 Thread Seth
I tried all three ways you guys listed nothing seems to convert the
string to bytes.

It may have to do with the makeDeviceName function, but I can't find
where that is defined.

Any thoughts??

Here is the whole block of code:

if type(port) in (str, bytes):   #strings are taken directly
Originally: if type(port) in [type(''), type(u'')]
self.portstr = port
else:
self.portstr = self.makeDeviceName(port)



On Feb 25, 8:47 am, Christian Heimes li...@cheimes.de wrote:
 Seth wrote:
  I implemented if isinstance(port, str):  that seems to work for now.

  Currently I am running into:

  err, n = win32file.WriteFile(self.hComPort, data,
  self._overlappedWrite)
  TypeError: expected an object with a buffer interface

 Unicode objects (in Py3k: str) don't implement the buffer interface. You
 have to apply a bytes or bytearray instance.

 Christian

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


Re: Lambda function

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 12:42:32 -0200, Albert Hopkins  
mar...@letterboxes.org escribió:

On Wed, 2009-02-25 at 17:56 +0530, aditya saurabh wrote:



I defined two functions - lets say
fa = lambda x: 2*x
fb = lambda x: 3*x
Now I would like to use fa*fb in terms of x
is there a way?
Thanks in advance


I'm not sure what use fa*fb in terms of x means.

But if you mean fa(x) * fb(x) then it's just:

fa(x) * fb(x)


I think he wants function composition, fb(fa(x)):

def compose(*funcs):
  def composed(x, funcs=funcs):
for f in reversed(funcs):
  x = f(x)
return x
  return composed

def square(x): return x**2
def plus1(x): return x+1
# same as plus1 = lambda x: x+1 but I like the def syntax

y = compose(square, plus1) # y=(x+1)**2
y(3) # - 16

(or is it fa(fb(x))?)

--
Gabriel Genellina

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


Re: Convert PySerial to python 3.0

2009-02-25 Thread Christian Heimes
Seth wrote:
 I tried all three ways you guys listed nothing seems to convert the
 string to bytes.
 
 It may have to do with the makeDeviceName function, but I can't find
 where that is defined.
 
 Any thoughts??
 
 Here is the whole block of code:
 
 if type(port) in (str, bytes):   #strings are taken directly
 Originally: if type(port) in [type(''), type(u'')]
 self.portstr = port
 else:
 self.portstr = self.makeDeviceName(port)

str and bytes are two totally unrelated things in Python 3.0. You can no
longer treat them equally like str and unicode in Python 2.x. Your could
should not work under Python 3.0 anyway. u'' is invalid in 3.x.

Also please don't use ugly type checks like type(something) == type('').
Starting with Python 2.2 you should use isinstance, for example
isinstance(number, (int, long)).

Christian

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Roy H. Han
Cool, it works!

Thanks, RDM, for stating the right approach.
Thanks, Steve, for teaching by example.

I wonder why the email.message_from_string() method doesn't call
email.header.decode_header() automatically.


On Wed, Feb 25, 2009 at 9:50 AM,  rdmur...@bitdance.com wrote:
 Steve Holden st...@holdenweb.com wrote:
  from email.header import decode_header
  print
 decode_header(=?us-ascii?Q?Inteum_C/SR_User_Tip:__Quick_Access_to_Recently_Opened_Inteu?=\r\n\t=?us-ascii?Q?m_C/SR_Records?=)
 [('Inteum C/SR User Tip:  Quick Access to Recently Opened Inteum C/SR
 Records', 'us-ascii')]
 

 It is interesting that decode_header does what I would consider to be
 the right thing (from a pragmatic standpoint) with that particular bit
 of Microsoft not-quite-standards-compliant brain-damage; but, removing
 the tab is not in fact standards compliant if I'm reading the RFC
 correctly.

 --RDM

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

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Steve Holden
rdmur...@bitdance.com wrote:
 Steve Holden st...@holdenweb.com wrote:
 from email.header import decode_header
 print
 decode_header(=?us-ascii?Q?Inteum_C/SR_User_Tip:__Quick_Access_to_Recently_Opened_Inteu?=\r\n\t=?us-ascii?Q?m_C/SR_Records?=)
 [('Inteum C/SR User Tip:  Quick Access to Recently Opened Inteum C/SR
 Records', 'us-ascii')]
 
 It is interesting that decode_header does what I would consider to be
 the right thing (from a pragmatic standpoint) with that particular bit
 of Microsoft not-quite-standards-compliant brain-damage; but, removing
 the tab is not in fact standards compliant if I'm reading the RFC
 correctly.
 
You'd need to quote me chapter and verse on that. I understood that the
tab simply indicated continuation, but it's a *long* time since I read
the RFCs.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


File Path retrieving problem

2009-02-25 Thread Sudhir Kakumanu
Hi all,

I am new to Python, i have installed python 2.5.4 and it is my requirement.

I need to retrieve the path of filename in python.

I have found some API's to get this:

from os.path import realpath
print realpath(NEWS.txt)  # here NEWS.txt exists and it shows the path of
the file as C:\Python25\WorkSpace\NEWS.txt
print realpath(abc.txt) # here abc.txt does not exist but still it shows
C:\Python25\WorkSpace\abc.txt

can anybody tell the reason why


Now took some safety measures:

found = lexists(realpath(filename))
if found == 0:
print Not Found
else:
print realpath(filename)

i have given the filename as NEWS.txt and abc.txt but i am always
getting the output as Not Found


Can anyone please tell me where am i doing wrong

also any suggestions to retrieve the filepath from a given filename is
highly appreciated.

Thanks in advance.


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


Newbie : this works in one direction but get the error on the return path

2009-02-25 Thread Gary Wood
'''Test animation of a group of objects making a face.
Combine the face elements in a function, and use it twice.
Have an extra level of repetition in the animation.
'''

from graphics import *
import time

def moveAll(shapeList, dx, dy):
''' Move all shapes in shapeList by (dx, dy).'''
for shape in shapeList: 
shape.move(dx, dy)


def moveAllOnLine(shapeList, dx, dy, repetitions, delay):
'''Animate the shapes in shapeList along a line.
Move by (dx, dy) each time.
Repeat the specified number of repetitions.
Have the specified delay (in seconds) after each repeat.
'''
for i in range(repetitions):
moveAll(shapeList, dx, dy)
time.sleep(delay)


def makeFace(center, win):
'''display face centered at center in window win.
Return a list of the shapes in the face.
'''

head = Circle(center, 25)
head.setFill(yellow)
head.draw(win)

eye1Center = center.clone()  #face positions are relative to the center
eye1Center.move(-10, 5)  #locate further points in relation to others
eye1 = Circle(eye1Center, 5)
eye1.setFill('blue')
eye1.draw(win)

eye2End1 = eye1Center.clone()
eye2End1.move(15, 0)
eye2End2 = eye2End1.clone()
eye2End2.move(10, 0)

eye2 = Line(eye2End1, eye2End2)
eye2.setWidth(3)
eye2.draw(win)

noseTop = center.clone()
noseTop.move(0,0)
noseLeft = noseTop.clone()
noseLeft.move(-2,-2)
noseRight = noseLeft.clone()
noseRight.move(5,0)
nose = Polygon(noseTop,noseLeft,noseRight)
nose.draw(win)


mouthCorner1 = center.clone()
mouthCorner1.move(-10, -10)
mouthCorner2 = mouthCorner1.clone()
mouthCorner2.move(20, -5)

mouth = Oval(mouthCorner1, mouthCorner2)
mouth.setFill(red)
mouth.draw(win)

return [head, eye1, eye2,nose, mouth]

def main():
winWidth = 300
winHeight = 300
win = GraphWin('Back and Forth', winWidth, winHeight)
win.setCoords(0, 0, winWidth, winHeight)  #make right side up coordinates!

rect = Rectangle(Point(200, 90), Point(220, 100))
rect.setFill(blue)
rect.draw(win)

faceList = makeFace(Point(40, 100), win)
faceList2 = makeFace(Point(150,125), win)

stepsAcross = 40
dx = 5
dy = 3
wait = .1
for i in range(2):
moveAllOnLine(faceList, dx, 0, stepsAcross, wait)
moveAllOnLine(faceList, -dx, dy, stepsAcross/2, wait)
moveAllOnLine(faceList, -dx, -dy, stepsAcross//2, wait) 

Text(Point(winWidth/2, 20), 'Click anywhere to quit.').draw(win)
win.getMouse()
win.close()

main()


Traceback (most recent call last):
  File E:/python/handson/backAndForth4.py, line 97, in module
main()
  File E:/python/handson/backAndForth4.py, line 90, in main
moveAllOnLine(faceList, -dx, dy, stepsAcross/2, wait)
  File E:/python/handson/backAndForth4.py, line 21, in moveAllOnLine
for i in range(repetitions):
TypeError: 'float' object cannot be interpreted as an integer
 --
http://mail.python.org/mailman/listinfo/python-list


Re: glibc detected *** python: corrupted double-linked list

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 10:40:23 -0200, Christian Meesters meest...@gmx.de  
escribió:



I have a problem using my software on my 64bit laptop, after an update of
my system. The same code still runs on 32bit Intel, but on my laptop I
provoke the crash in the title. The crash is caused - as narrowed down by
me - by returning a static PyObject from a C-extension function.


I think you got all the reference counts wrong, specially dummy1, dummy2  
and r.


(BTW, when you know the size, it's better to use PyList_New(size) +  
PyList_SET_ITEM instead of PyList_New(0) + PyList_Append)


--
Gabriel Genellina

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


Re: glibc detected *** python: corrupted double-linked list

2009-02-25 Thread Christian Meesters
Thanks David!

It's still not debugged, but indeed: I get a bunch of warnings. And this 
already showed me that there are more potential problems than my first 
guess indicated. Alas, for my specific problem I cannot work with ints 
chars and doubles. I need to have unsigned longs at some points.

Well, I'll sort it out.

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


File Path retrieving problem

2009-02-25 Thread music24by7
Hi all,

I am new to Python, i have installed python 2.5.4 and it is my
requirement.

I need to retrieve the path of filename in python.

I have found some API's to get this:

from os.path import realpath
print realpath(NEWS.txt)  # here NEWS.txt exists and it shows the
path of the file as C:\Python25\WorkSpace\NEWS.txt
print realpath(abc.txt) # here abc.txt does not exist but still it
shows C:\Python25\WorkSpace\abc.txt

can anybody tell the reason why


Now took some safety measures:

found = lexists(realpath(filename))
if found == 0:
print Not Found
else:
print realpath(filename)

i have given the filename as NEWS.txt and abc.txt but i am always
getting the output as Not Found


Can anyone please tell me where am i doing wrong

also any suggestions to retrieve the filepath from a given filename is
highly appreciated.

Thanks in advance.


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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Thorsten Kampe
* Roy H. Han (Wed, 25 Feb 2009 10:17:22 -0500)
 Thanks, RDM, for stating the right approach.
 Thanks, Steve, for teaching by example.
 
 I wonder why the email.message_from_string() method doesn't call
 email.header.decode_header() automatically.

And I wonder why you would think the header contains Unicode characters 
when it says us-ascii (=?us-ascii?Q?). I think there is a tendency 
to label everything Unicode someone does not understand.

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


Re: Newbie : this works in one direction but get the error on the return path

2009-02-25 Thread Gabriel Genellina

En Wed, 25 Feb 2009 13:31:25 -0200, Gary Wood python...@sky.com escribió:

Start looking at the error:


Traceback (most recent call last):
  File E:/python/handson/backAndForth4.py, line 97, in module
main()
  File E:/python/handson/backAndForth4.py, line 90, in main
moveAllOnLine(faceList, -dx, dy, stepsAcross/2, wait)
  File E:/python/handson/backAndForth4.py, line 21, in moveAllOnLine
for i in range(repetitions):
TypeError: 'float' object cannot be interpreted as an integer


It's rather understandable - you have a float object where Python is  
expecting an integer.

Where? The traceback says it all:


  File E:/python/handson/backAndForth4.py, line 21, in moveAllOnLine
for i in range(repetitions):


Ok, so repetitions should be an integer, but it isn't. Where does it come  
from? It's an argument to moveAllOnLine, and was called from main (see the  
line above that in the traceback). Now we look near that line:



for i in range(2):
moveAllOnLine(faceList, dx, 0, stepsAcross, wait)
moveAllOnLine(faceList, -dx, dy, stepsAcross/2, wait)
moveAllOnLine(faceList, -dx, -dy, stepsAcross//2, wait)


Don't you see something suspicious...?


--
Gabriel Genellina

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


Re: glibc detected *** python: corrupted double-linked list

2009-02-25 Thread Christian Meesters
Hi,

 I have a problem using my software on my 64bit laptop, after an update
 of my system. The same code still runs on 32bit Intel, but on my laptop
 I provoke the crash in the title. The crash is caused - as narrowed
 down by me - by returning a static PyObject from a C-extension
 function.
 
 I think you got all the reference counts wrong, specially dummy1, dummy2
 and r.
Might be a good point, but can you give me a hint where to look 
specifically?
 
 (BTW, when you know the size, it's better to use PyList_New(size) +
 PyList_SET_ITEM instead of PyList_New(0) + PyList_Append)
Just rewrote that section.

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


How to convert image into numpy.ndarray

2009-02-25 Thread anti-suho
In scipy module, there is a function named misc.lena which can return
an array of numpy.ndarray type. If you use this array as parameter of
matplotlib.pyplot.imshow and then call the matplotlib.pyplot.imshow
function, an image will be shown. The shown image is generated by the
numpy.ndarray array.

How to convert an arbitrary image into an array of numpy.ndarray type?
--
http://mail.python.org/mailman/listinfo/python-list


Re: File Path retrieving problem

2009-02-25 Thread Steve Holden
music24...@gmail.com wrote:
 Hi all,
 
 I am new to Python, i have installed python 2.5.4 and it is my
 requirement.
 
 I need to retrieve the path of filename in python.
 
 I have found some API's to get this:
 
 from os.path import realpath
 print realpath(NEWS.txt)  # here NEWS.txt exists and it shows the
 path of the file as C:\Python25\WorkSpace\NEWS.txt
 print realpath(abc.txt) # here abc.txt does not exist but still it
 shows C:\Python25\WorkSpace\abc.txt
 
 can anybody tell the reason why
 
 
 Now took some safety measures:
 
 found = lexists(realpath(filename))
 if found == 0:
 print Not Found
 else:
 print realpath(filename)
 
 i have given the filename as NEWS.txt and abc.txt but i am always
 getting the output as Not Found
 
 
 Can anyone please tell me where am i doing wrong
 
It seems pretty apparent that lexists() nevert returns a true result.

Why not just

if os.path.exists(filename):
print os.path.realpath(filename)
else:
print Not found

 also any suggestions to retrieve the filepath from a given filename is
 highly appreciated.
 
Well, realpath returns the path of the file targeted after any symbolic
links have been evaluated, which may or may not be what you want. Have
you looked at os.path.abspath?

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 13:40:31 -0200, Thorsten Kampe  
thors...@thorstenkampe.de escribió:



* Roy H. Han (Wed, 25 Feb 2009 10:17:22 -0500)

Thanks, RDM, for stating the right approach.
Thanks, Steve, for teaching by example.

I wonder why the email.message_from_string() method doesn't call
email.header.decode_header() automatically.


And I wonder why you would think the header contains Unicode characters
when it says us-ascii (=?us-ascii?Q?). I think there is a tendency
to label everything Unicode someone does not understand.


And I wonder why you would think the header does *not* contain Unicode  
characters when it says us-ascii?. I think there is a tendency here  
too...


--
Gabriel Genellina

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


Re: Convert PySerial to python 3.0

2009-02-25 Thread Seth
This is not my code and I am fairly new to Python.  I did not know how
much it would take to convert pyserial to 3.0. Someone more
knowledgeable than me could do it better and faster.  I just want to
see if I could help get it to work.

I was wrong, it seems that if type(port) in (str, bytes): or isinstance
(port, str) works just fine for setting the ports.

The issue now is reading and writing the data.

I got the read() to kind of work with:
bytes(buf[:n]) replacing str(buf[:n])

but with readline() it seems to be missing the '\n' because it just
runs indefinitely( I can see the \n if I read enough bytes with read()


write seems to be related to a win32 issue.  win32file.WriteFile does
not like anything I convert it to:
str gives the buffer error
bytes gives a string argument without an encoding error

Sorry for the confusion, I just want to be able to use all Py3k on
this project that I am working on and pyserial has not been converted
so I just started messing around with it.

Thanks for the help.

Seth




On Feb 25, 10:16 am, Christian Heimes li...@cheimes.de wrote:
 Seth wrote:
  I tried all three ways you guys listed nothing seems to convert the
  string to bytes.

  It may have to do with the makeDeviceName function, but I can't find
  where that is defined.

  Any thoughts??

  Here is the whole block of code:

  if type(port) in (str, bytes):       #strings are taken directly
  Originally:     if type(port) in [type(''), type(u'')]
                  self.portstr = port
              else:
                  self.portstr = self.makeDeviceName(port)

 str and bytes are two totally unrelated things in Python 3.0. You can no
 longer treat them equally like str and unicode in Python 2.x. Your could
 should not work under Python 3.0 anyway. u'' is invalid in 3.x.

 Also please don't use ugly type checks like type(something) == type('').
 Starting with Python 2.2 you should use isinstance, for example
 isinstance(number, (int, long)).

 Christian

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


Re: glibc detected *** python: corrupted double-linked list

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 13:51:20 -0200, Christian Meesters meest...@gmx.de  
escribió:



I have a problem using my software on my 64bit laptop, after an update
of my system. The same code still runs on 32bit Intel, but on my laptop
I provoke the crash in the title. The crash is caused - as narrowed
down by me - by returning a static PyObject from a C-extension
function.


I think you got all the reference counts wrong, specially dummy1, dummy2
and r.

Might be a good point, but can you give me a hint where to look
specifically?


  /* parse the input arguments r  vectors */
  if (!PyArg_ParseTuple(args, OO, r, py_vectors))
return NULL;
  ...

  for (i=0; i  vsize; i++) {
...
dummy_2 = PyList_GetItem(dummy_1, 0);
...
  }
  ...

  /* copy all items from pofr to py_pofr to be returned */
  if (!(py_pofr = PyList_New(0)))  return NULL;
  for (i=0; i  rlen; i++) {
dummy_1 = Py_BuildValue(i, pofr[i]);
if (!dummy_1) return NULL;
PyList_Append(py_pofr, dummy_1);
Py_CLEAR(dummy_1);
  }

  /* reference counters to zero */
  Py_CLEAR(dummy_1);
  Py_CLEAR(dummy_2);
  Py_CLEAR(r);


r is an argument, a borrowed reference; you can't Py_CLEAR it.
dummy_1 is decremented inside the loop, and again three lines below.
dummy_2 is used far above the final Py_CLEAR, and it comes from  
PyList_GetItem, which returns a borrowed reference - you can't decrement  
it either.
Also there are several return NULL that don't decrement active objects  
(like if (!dummy_1)... above)


Getting the reference count right is critical: if you err by +1, the  
object will never be destroyed (leaking memory). If you err by -1, the  
object will be still in use after it was destroyed.


--
Gabriel Genellina

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


Re: How to convert image into numpy.ndarray

2009-02-25 Thread Christian Meesters
On Wed, 25 Feb 2009 07:52:03 -0800, anti-suho wrote:

 In scipy module, there is a function named misc.lena which can return an
 array of numpy.ndarray type. If you use this array as parameter of
 matplotlib.pyplot.imshow and then call the matplotlib.pyplot.imshow
 function, an image will be shown. The shown image is generated by the
 numpy.ndarray array.
 
 How to convert an arbitrary image into an array of numpy.ndarray type?
Well, arbitrary ...

But this may serve as a starting point:

from scipy.misc import fromimage
import Image #PIL
my_array = fromimage(Image.open(_file_name_))

Of course, you should perform the appropriate error checking, too. ;-)

HTH
Christian


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


Re: File Path retrieving problem

2009-02-25 Thread music24by7
On Feb 25, 8:57 pm, Steve Holden st...@holdenweb.com wrote:
 music24...@gmail.com wrote:
  Hi all,

  I am new to Python, i have installed python 2.5.4 and it is my
  requirement.

  I need to retrieve the path of filename in python.

  I have found some API's to get this:

  from os.path import realpath
  print realpath(NEWS.txt)  # here NEWS.txt exists and it shows the
  path of the file as C:\Python25\WorkSpace\NEWS.txt
  print realpath(abc.txt) # here abc.txt does not exist but still it
  shows C:\Python25\WorkSpace\abc.txt

  can anybody tell the reason why

  Now took some safety measures:

  found = lexists(realpath(filename))
          if found == 0:
              print Not Found
          else:
              print realpath(filename)

  i have given the filename as NEWS.txt and abc.txt but i am always
  getting the output as Not Found

  Can anyone please tell me where am i doing wrong

 It seems pretty apparent that lexists() nevert returns a true result.

 Why not just

 if os.path.exists(filename):
     print os.path.realpath(filename)
 else:
     print Not found

  also any suggestions to retrieve the filepath from a given filename is
  highly appreciated.

 Well, realpath returns the path of the file targeted after any symbolic
 links have been evaluated, which may or may not be what you want. Have
 you looked at os.path.abspath?

 regards
  Steve
 --
 Steve Holden        +1 571 484 6266   +1 800 494 3119
 Holden Web LLC              http://www.holdenweb.com/



Hi Steve,

I have tried your suggested code and also replaced os.path.realpath
with os.path.abspath but still getting the same result.
I want to know is there any workaround for retrieving the filepaths
given only filename

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


Re: Convert PySerial to python 3.0

2009-02-25 Thread Gabriel Genellina

En Wed, 25 Feb 2009 14:07:30 -0200, Seth king.s...@gmail.com escribió:


This is not my code and I am fairly new to Python.  I did not know how
much it would take to convert pyserial to 3.0. Someone more
knowledgeable than me could do it better and faster.  I just want to
see if I could help get it to work.


The last commit to pyserial repository was 8 days ago, so it's not like an  
abandoned project.

Have you contacted the author?

That said, Python 3.0 is still very recent and doesn't have a big set of  
3rd party libraries as earlier versions. Maybe you should stick to 2.6 or  
even 2.5 for a while.


--
Gabriel Genellina

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


Battleship style game

2009-02-25 Thread Shawn Milochik
I started learning Java for fun, and the first project assignment in
the book is to create a game like Battleship. So, of course, I wrote
it in Python first, just for fun. I haven't had the time to look up
all the Java syntax.

So, here it is, fully functional. I thought I'd throw it out there and
see if anyone would like to offer any useful tips. I'm not claiming
it's bulletproof, but it works. I just kind of came up with all the
methods off of the top of my head, so if anyone has any suggestions
for more elegant or efficient code, please let me know.

http://shawnmilo.com/ships/

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


Re: Battleship style game

2009-02-25 Thread Marco Mariani

Shawn Milochik wrote:

 I'm not claiming it's bulletproof, but it works. I just kind of came 
up with all the

methods off of the top of my head, so if anyone has any suggestions
for more elegant or efficient code, please let me know.


Yes it's in Python alright, but it's not Pythonese yet. You could try 
avoiding the getter/setter stuff, and camelCase method naming, things 
like that, for a start.


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


Re: Battleship style game

2009-02-25 Thread Shawn Milochik
On Wed, Feb 25, 2009 at 11:38 AM, Marco Mariani ma...@sferacarta.com wrote:

 Yes it's in Python alright, but it's not Pythonese yet. You could try
 avoiding the getter/setter stuff, and camelCase method naming, things like
 that, for a start.

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



What do you mean avoiding the getter/setter stuff? If I understand
correctly, you're saying to directly access the attributes, which I
specifically want to avoid because I may want to enforce some rules
(such as not changing a ship length after it's created).

The camel-case thing I get -- I use that and this_type quite a bit,
probably because of the inconsistency of the languages I use
regularly, and standards at work and conventions in my hobby
programming.
--
http://mail.python.org/mailman/listinfo/python-list


Re: File Path retrieving problem

2009-02-25 Thread Steve Holden
music24...@gmail.com wrote:
 On Feb 25, 8:57 pm, Steve Holden st...@holdenweb.com wrote:
 music24...@gmail.com wrote:
 Hi all,
 I am new to Python, i have installed python 2.5.4 and it is my
 requirement.
 I need to retrieve the path of filename in python.
 I have found some API's to get this:
 from os.path import realpath
 print realpath(NEWS.txt)  # here NEWS.txt exists and it shows the
 path of the file as C:\Python25\WorkSpace\NEWS.txt
 print realpath(abc.txt) # here abc.txt does not exist but still it
 shows C:\Python25\WorkSpace\abc.txt
 can anybody tell the reason why
 Now took some safety measures:
 found = lexists(realpath(filename))
 if found == 0:
 print Not Found
 else:
 print realpath(filename)
 i have given the filename as NEWS.txt and abc.txt but i am always
 getting the output as Not Found
 Can anyone please tell me where am i doing wrong
 It seems pretty apparent that lexists() nevert returns a true result.

 Why not just

 if os.path.exists(filename):
 print os.path.realpath(filename)
 else:
 print Not found

 also any suggestions to retrieve the filepath from a given filename is
 highly appreciated.
 Well, realpath returns the path of the file targeted after any symbolic
 links have been evaluated, which may or may not be what you want. Have
 you looked at os.path.abspath?

 regards
  Steve
 --
 Steve Holden+1 571 484 6266   +1 800 494 3119
 Holden Web LLC  http://www.holdenweb.com/
 
 
 
 Hi Steve,
 
 I have tried your suggested code and also replaced os.path.realpath
 with os.path.abspath but still getting the same result.
 I want to know is there any workaround for retrieving the filepaths
 given only filename
 
What, you are saying that

  os.path.exists(filename)

is returning false when the file exists? I find that hard to believe.

Please display some evidence so I can understand this.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Thorsten Kampe
* Gabriel Genellina (Wed, 25 Feb 2009 14:00:16 -0200)
 En Wed, 25 Feb 2009 13:40:31 -0200, Thorsten Kampe  
 thors...@thorstenkampe.de escribió:
  * Roy H. Han (Wed, 25 Feb 2009 10:17:22 -0500)
  Thanks, RDM, for stating the right approach.
  Thanks, Steve, for teaching by example.
 
  I wonder why the email.message_from_string() method doesn't call
  email.header.decode_header() automatically.
 
  And I wonder why you would think the header contains Unicode characters
  when it says us-ascii (=?us-ascii?Q?). I think there is a tendency
  to label everything Unicode someone does not understand.
 
 And I wonder why you would think the header does *not* contain Unicode  
 characters when it says us-ascii?.

Basically because it didn't contain any Unicode characters (anything 
outside the ASCII range).

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


Re: Battleship style game

2009-02-25 Thread Steve Holden
Shawn Milochik wrote:
 On Wed, Feb 25, 2009 at 11:38 AM, Marco Mariani ma...@sferacarta.com wrote:
 Yes it's in Python alright, but it's not Pythonese yet. You could try
 avoiding the getter/setter stuff, and camelCase method naming, things like
 that, for a start.

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

 
 
 What do you mean avoiding the getter/setter stuff? If I understand
 correctly, you're saying to directly access the attributes, which I
 specifically want to avoid because I may want to enforce some rules
 (such as not changing a ship length after it's created).
 
If you wanted to enforce those restrictions you could just turn
attributes into properties.

 The camel-case thing I get -- I use that and this_type quite a bit,
 probably because of the inconsistency of the languages I use
 regularly, and standards at work and conventions in my hobby
 programming.

PEP 008 is the usual style recommendation.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Battleship style game

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 14:50:18 -0200, Shawn Milochik sh...@milochik.com  
escribió:
On Wed, Feb 25, 2009 at 11:38 AM, Marco Mariani ma...@sferacarta.com  
wrote:


Yes it's in Python alright, but it's not Pythonese yet. You could try
avoiding the getter/setter stuff, and camelCase method naming, things  
like

that, for a start.


What do you mean avoiding the getter/setter stuff? If I understand
correctly, you're saying to directly access the attributes, which I
specifically want to avoid because I may want to enforce some rules
(such as not changing a ship length after it's created).


I think Marco Mariani was suggesting something like this:

class Ship(object):

def __init__(self, length):
self._length = length

def get_length(self):
return self._length
length = property(get_length)  # a read only property

--
Gabriel Genellina

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


Re: File Path retrieving problem

2009-02-25 Thread Peter Otten
Steve Holden wrote:

 What, you are saying that
 
 os.path.exists(filename)
 
 is returning false when the file exists? I find that hard to believe.
 
 Please display some evidence so I can understand this.

Maybe it's about access rights?

$ mkdir alpha
$ touch alpha/beta
$ python -cimport os; print os.path.exists('alpha/beta')
True
$ chmod u-x alpha
$ python -cimport os; print os.path.exists('alpha/beta')
False
$

I Don't know how this is handled on Windows...

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Tim Golden

Thorsten Kampe wrote:

* Gabriel Genellina (Wed, 25 Feb 2009 14:00:16 -0200)
En Wed, 25 Feb 2009 13:40:31 -0200, Thorsten Kampe  
thors...@thorstenkampe.de escribió:

* Roy H. Han (Wed, 25 Feb 2009 10:17:22 -0500)

Thanks, RDM, for stating the right approach.
Thanks, Steve, for teaching by example.

I wonder why the email.message_from_string() method doesn't call
email.header.decode_header() automatically.

And I wonder why you would think the header contains Unicode characters
when it says us-ascii (=?us-ascii?Q?). I think there is a tendency
to label everything Unicode someone does not understand.
And I wonder why you would think the header does *not* contain Unicode  
characters when it says us-ascii?.


Basically because it didn't contain any Unicode characters (anything 
outside the ASCII range).


And I imagine that Gabriel's point was -- and my point certainly
is -- that Unicode includes all the characters *inside* the
ASCII range.


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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 15:01:08 -0200, Thorsten Kampe  
thors...@thorstenkampe.de escribió:

* Gabriel Genellina (Wed, 25 Feb 2009 14:00:16 -0200)

En Wed, 25 Feb 2009 13:40:31 -0200, Thorsten Kampe
thors...@thorstenkampe.de escribió:
 * Roy H. Han (Wed, 25 Feb 2009 10:17:22 -0500)
 Thanks, RDM, for stating the right approach.
 Thanks, Steve, for teaching by example.

 I wonder why the email.message_from_string() method doesn't call
 email.header.decode_header() automatically.

 And I wonder why you would think the header contains Unicode  
characters

 when it says us-ascii (=?us-ascii?Q?). I think there is a tendency
 to label everything Unicode someone does not understand.

And I wonder why you would think the header does *not* contain Unicode
characters when it says us-ascii?.


Basically because it didn't contain any Unicode characters (anything
outside the ASCII range).


I think you have to revise your definition of Unicode.

--
Gabriel Genellina

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


coding style - try, except

2009-02-25 Thread RGK


I'm still learning, so eager to see if there is some community wisdom 
about use of the try/except structures in this situation.


I find myself with some potentially risky stuff and wrap it in a 
try/except structure with good functional results, though my code leaves 
me a bit uneasy. Maybe it's just esoteric, but your input is appreciated.


Consider

  try:
do something 1
do something 2
do something 3
do something 4
...
do something 25

  except:
print Oops something didn't work


The risky things are just 1  2, and the others are not of concern, but 
are dependent on 1  2.  The alternative is to do:


  wentOkay = True
  try:
do something 1
do something 2

  except:
print Oops something didn't work
wentOkay = False

  if wentOkay:
do something 3
do something 4
 ...
do something 25


Which seems a bit verbose, but likely the better approach.  Is there 
some other option I should be considering?


Any input appreciated :)

Ross.

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread rdmurray
Steve Holden st...@holdenweb.com wrote:
 rdmur...@bitdance.com wrote:
  Steve Holden st...@holdenweb.com wrote:
  from email.header import decode_header
  print
  decode_header(=?us-ascii?Q?Inteum_C/SR_User_Tip:__Quick_Access_to_Recently_Opened_Inteu?=\r\n\t=?us-ascii?Q?m_C/SR_Records?=)
  [('Inteum C/SR User Tip:  Quick Access to Recently Opened Inteum C/SR
  Records', 'us-ascii')]
  
  It is interesting that decode_header does what I would consider to be
  the right thing (from a pragmatic standpoint) with that particular bit
  of Microsoft not-quite-standards-compliant brain-damage; but, removing
  the tab is not in fact standards compliant if I'm reading the RFC
  correctly.
  
 You'd need to quote me chapter and verse on that. I understood that the
 tab simply indicated continuation, but it's a *long* time since I read
 the RFCs.

Tab is not mentioned in RFC 2822 except to say that it is a valid
whitespace character.  Header folding (insertion of crlf) can
occur most places whitespace appears, and is defined in section
2.2.3 thusly:

   Each header field is logically a single line of characters comprising
   the field name, the colon, and the field body.  For convenience
   however, and to deal with the 998/78 character limitations per line,
   the field body portion of a header field can be split into a multiple
   line representation; this is called folding.  The general rule is
   that wherever this standard allows for folding white space (not
   simply WSP characters), a CRLF may be inserted before any WSP.  For
   example, the header field:

   Subject: This is a test

   can be represented as:

   Subject: This
is a test

   [irrelevant note elided]

   The process of moving from this folded multiple-line representation
   of a header field to its single line representation is called
   unfolding. Unfolding is accomplished by simply removing any CRLF
   that is immediately followed by WSP.  Each header field should be
   treated in its unfolded form for further syntactic and semantic
   evaluation.

So, the whitespace characters are supposed to be left unchanged
after unfolding.

--David

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Steve Holden
rdmur...@bitdance.com wrote:
[...]
 
The process of moving from this folded multiple-line representation
of a header field to its single line representation is called
unfolding. Unfolding is accomplished by simply removing any CRLF
that is immediately followed by WSP.  Each header field should be
treated in its unfolded form for further syntactic and semantic
evaluation.
 
 So, the whitespace characters are supposed to be left unchanged
 after unfolding.
 
That would certainly appear to be the case. Thanks.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: coding style - try, except

2009-02-25 Thread Steve Holden
RGK wrote:
 
 I'm still learning, so eager to see if there is some community wisdom
 about use of the try/except structures in this situation.
 
 I find myself with some potentially risky stuff and wrap it in a
 try/except structure with good functional results, though my code leaves
 me a bit uneasy. Maybe it's just esoteric, but your input is appreciated.
 
 Consider
 
   try:
 do something 1
 do something 2
 do something 3
 do something 4
 ...
 do something 25
 
   except:
 print Oops something didn't work
 
 
 The risky things are just 1  2, and the others are not of concern, but
 are dependent on 1  2.  The alternative is to do:
 
   wentOkay = True
   try:
 do something 1
 do something 2
 
   except:
 print Oops something didn't work
 wentOkay = False
 
   if wentOkay:
 do something 3
 do something 4
  ...
 do something 25
 
 
 Which seems a bit verbose, but likely the better approach.  Is there
 some other option I should be considering?
 
 Any input appreciated :)
 
The first form is far preferable: it expresses the logic directly and
clearly, and is much easier to read than the second, which I personally
find somewhat contorted.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: This application has failed to start because the application configuration is incorrect

2009-02-25 Thread Lorenzo
On 17 feb, 19:44, Mark Hammond skippy.hamm...@gmail.com wrote:
 On 18/02/2009 5:49 AM, Sam Clark wrote:

  I am receiving the message Thisapplicationhasfailedtostartbecause
  theapplicationconfiguration is incorrect when I attempt to run a
  compiled Python program on another machine. I have used py2exe on both a
  2.6.1 and a 2.6.0 version of the .py and .pyw files. Everything works
  great on the machine where Python 2.6 is loaded, but fails on machines
  where I copy the .exe to the machine. I'm a beginner at python
  programming. In fact this is my first packaged program. Any thoughts at
  a beginners level would be helpful.

 This will be due to the C runtime library not being installed correctly
 on the target machine.  

I had the same issue. After looking some patch solutions of putting
manually some dlls on the dist folder, I realized that you can fix it
by installing one of these packages, see which one fits your system:
x86
http://www.microsoft.com/downloads/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2displaylang=en

x64
http://www.microsoft.com/downloads/details.aspx?familyid=BA9257CA-337F-4B40-8C14-157CFDFFEE4Edisplaylang=en

PS: Mark, this could be added to a kind of Deployment entry in
py2exe wiki, it would be useful.
--
http://mail.python.org/mailman/listinfo/python-list


Re: glibc detected *** python: corrupted double-linked list

2009-02-25 Thread Duncan Grisby
In article mailman.730.1235567202.11746.python-l...@python.org,
David Cournapeau  courn...@gmail.com wrote:

[...]
It is very unlikely the problem is in glibc - I would check your code
carefully first :) On Linux, the following are useful:

You are right that it is extremely unlikely that the bug is in glibc.
However, it is not impossible. Several of my colleagues and I spent
months trying to track down a bug where Python would occasionally
crash with a segfault while iterating through large lists. Of course
the problem only ever happened on customer sites, and not in our lab.
I eventually tracked it down to a bug in glibc's realloc()
implementation, where once in a blue moon it would fail to copy all
the data into the newly-allocated buffer.

It turned out to be a bug that had been found before, but had been
closed as invalid a few months earlier:

  http://sources.redhat.com/bugzilla/show_bug.cgi?id=5743

The fix had then been applied about a week before I found it myself.

I'm not sure that particular fix has found it into any of the major
Linux distributions yet.

Cheers,

Duncan.

-- 
 -- Duncan Grisby --
  -- dun...@grisby.org --
   -- http://www.grisby.org --
--
http://mail.python.org/mailman/listinfo/python-list


Re: coding style - try, except

2009-02-25 Thread Chris Rebert
On Wed, Feb 25, 2009 at 9:36 AM, RGK bl...@empty.blank wrote:

 I'm still learning, so eager to see if there is some community wisdom about
 use of the try/except structures in this situation.

 I find myself with some potentially risky stuff and wrap it in a try/except
 structure with good functional results, though my code leaves me a bit
 uneasy. Maybe it's just esoteric, but your input is appreciated.

 Consider

  try:
    do something 1
    do something 2
    do something 3
    do something 4
    ...
    do something 25

  except:
    print Oops something didn't work


 The risky things are just 1  2, and the others are not of concern, but are
 dependent on 1  2.  The alternative is to do:

  wentOkay = True
  try:
    do something 1
    do something 2

  except:
    print Oops something didn't work
    wentOkay = False

  if wentOkay:
    do something 3
    do something 4
     ...
    do something 25


 Which seems a bit verbose, but likely the better approach.  Is there some
 other option I should be considering?

Yes. try-except-*else*.

try:
do_something_1()
do_something_2()
except:
print Houston, we have a problem
else: #runs only if no exception was thrown
do_something_3()
do_something_4()
et_cetera()

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: coding style - try, except

2009-02-25 Thread Peter Otten
Steve Holden wrote:

 RGK wrote:
 
 I'm still learning, so eager to see if there is some community wisdom
 about use of the try/except structures in this situation.
 
 I find myself with some potentially risky stuff and wrap it in a
 try/except structure with good functional results, though my code leaves
 me a bit uneasy. Maybe it's just esoteric, but your input is appreciated.
 
 Consider
 
   try:
 do something 1
 do something 2
 do something 3
 do something 4
 ...
 do something 25
 
   except:
 print Oops something didn't work

If you don't want a specific treatment for errors anticipated in 1 and 2
there's no need for try...except at this level at all. Just pass control up
the stack.

 The risky things are just 1  2, and the others are not of concern, but
 are dependent on 1  2.  The alternative is to do:
 
   wentOkay = True
   try:
 do something 1
 do something 2
 
   except:
 print Oops something didn't work
 wentOkay = False
 
   if wentOkay:
 do something 3
 do something 4
  ...
 do something 25
 
 
 Which seems a bit verbose, but likely the better approach.  Is there
 some other option I should be considering?
 
 Any input appreciated :)
 
 The first form is far preferable: it expresses the logic directly and
 clearly, and is much easier to read than the second, which I personally
 find somewhat contorted.

How about

try:
# do something that may fail in a way you anticipate
do something 1
do something 2
except SpecificError:
deal with the problem or reraise
else:
# no errors above
do something 3...25

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


Re: reading file to list

2009-02-25 Thread Xah Lee
On Feb 25, 3:34 am, nick_keighley_nos...@hotmail.com wrote:
 the nasty cons then only appears in a single function which
 you can hide in a library

I think the following answers that.

Q: If you don't like cons, lisp has arrays and hashmaps, too.

A: Suppose there's a lang called gisp. In gisp, there's cons but also
fons. Fons are just like cons except it has 3 cells with 3 accessors:
car, cbr, cdr. Now, gisp is a old lang, the fons are deeply rooted in
the lang. Every some 100 lines of code you'll see a use of fons with
its extra accessor cbr, or any one of the cbaar, cdabr, cbbar, cbbbar,
etc. You got annoyed by this. You as a critic, complains that fons is
bad. But then some gisp fanatics retorts: “If you don't like fons,
gisp has cons, too!”.

You see, by “having something too”, does not solve the problem of
pollution. Sure, you can use just cons in gisp, but every lib or
other's code you encounter, there's a invasion of fons with its cbar,
cbbar, cbbbar. The problem created by fons does not go away by “having
cons too”.

above is from

• Fundamental Problems of Lisp
  http://xahlee.org/UnixResource_dir/writ/lisp_problems.html

-

 I read it. Your point seems to be cons becomes difficult
 with deeply nested structures. Could you give an example?

There are few examples in these articles:

• The Concepts and Confusions of Prefix, Infix, Postfix and Fully
Nested Notations
  http://xahlee.org/UnixResource_dir/writ/notations.html

the above, 3rd section, gives detail about the problems of fully
nested syntax. In particular, it shows a source code snippet of
language with fully nested syntax, but is not lisp, so that lispers
can get a fresh impression.

• A Ruby Illustration of Lisp Problems
  http://xahlee.org/UnixResource_dir/writ/lisp_problems_by_ruby.html

the above, is a concrete example of showing how full nesting is
cumbersome, by constrasting a simple program in Ruby and lisp.

• Why Lisp Do Not Have A Generic Copy-List Function
  http://xahlee.org/UnixResource_dir/writ/lisp_equal_copy_list.html

the above, shows the cons problem, by looking Kent Pitman's article
with a different perspective.

A short Plain Text Excerpt of the ruby article cited above follows.
--

More specifically, 2 fundamental problems of lisp i feel this ruby
example illustrates well:

• the cons impedes many aspects of lists. e.g. difficult to learn,
confusing, hard to use, prevent development of coherent list
manipulation functions.

• nested syntax impedes the functional programing paradigm of function
chaining, esp when each function has 2 or more arguments (e.g. map).

here's a short summary of the nesting problem:

(map f x) ; 1 level of chaining
(map g (map f x)) ; 2 levels
(map h (map g (map f x))) ; 3 levels

compare:

x | f | g | h    unix pipe
x // f // g // h    Mathematica
h @ g @ f @ x Mathematica
x.f.g.h--- various OOP langs, esp Ruby, javascript
h g f x   --- some functional langs, Haskell, Ocaml

The way the above works is that each of f, g, h is a lambda themselves
that maps. (that is, something like “(lambda (y) (map f y))”)

Note, that any of the f, g, h may be complex pure functions (aka
lambda).  Because in lisp, each lambda itself will in general have
quite a lot nested parens (which cannot be avoided), so this makes any
chaining of functions of 2 args, for more than 2 or 3 levels of
nesting, unusable for practical coding. One must define the functions
separately and just call their names, or use function composition with
lambda (which gets complex quickly). One major aspect of this problem
is that the scope of vars becomes hard to understand in the deep
nested source code. This is worse in elisp, because emacs is
dynamically scoped, so you have to avoid using var of same name.

 Xah
∑http://xahlee.org/

☄

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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Thorsten Kampe
* Tim Golden (Wed, 25 Feb 2009 17:27:07 +)
 Thorsten Kampe wrote:
  * Gabriel Genellina (Wed, 25 Feb 2009 14:00:16 -0200)
  En Wed, 25 Feb 2009 13:40:31 -0200, Thorsten Kampe  
[...]
  And I wonder why you would think the header contains Unicode characters
  when it says us-ascii (=?us-ascii?Q?). I think there is a tendency
  to label everything Unicode someone does not understand.
  And I wonder why you would think the header does *not* contain Unicode  
  characters when it says us-ascii?.
  
  Basically because it didn't contain any Unicode characters (anything 
  outside the ASCII range).
 
 And I imagine that Gabriel's point was -- and my point certainly
 is -- that Unicode includes all the characters *inside* the
 ASCII range.

I know that this was Gabriel's point. And my point was that Gabriel's 
point was pointless. If you call any text (or character) Unicode then 
the word Unicode is generalized to an extent where it doesn't mean 
anything at all anymore and becomes a buzz word.

With the same reason you could call ASCII an Unicode encoding (which it 
isn't) because all ASCII characters are Unicode characters (code 
points). Only encodings that cover the full Unicode range can reasonably 
be called Unicode encodings.

The OP just saw some weird characters in the email subject and thought 
I know. It looks weird. Must be Unicode. But it wasn't. It was good 
ole ASCII - only Quoted Printable encoded.


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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Gabriel Genellina

En Wed, 25 Feb 2009 15:44:18 -0200, rdmur...@bitdance.com escribió:


Tab is not mentioned in RFC 2822 except to say that it is a valid
whitespace character.  Header folding (insertion of crlf) can
occur most places whitespace appears, and is defined in section
2.2.3 thusly: [...]
So, the whitespace characters are supposed to be left unchanged
after unfolding.


Yep, there is an old bug report sleeping in the tracker about this...

--
Gabriel Genellina

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


Re: coding style - try, except

2009-02-25 Thread Scott David Daniels

RGK wrote:
I'm still learning, so eager to see if there is some community wisdom 
about use of the try/except structures in this situation

  try:
do something 1
do something 2
do something 3
do something 4
...
do something 25
  except:
print Oops something didn't work

The risky things are just 1  2, and the others are not of concern, but 
are dependent on 1  2.  The alternative is to do:


  wentOkay = True
  try:
do something 1
do something 2
  except:
print Oops something didn't work
wentOkay = False
  if wentOkay:
do something 3
do something 4
 ...
do something 25
Which seems a bit verbose, but likely the better approach.  Is there 
some other option I should be considering?

What's wrong with:
try:
do something 1
do something 2
except (AttributeError, ValueError), why: # Don't use bare except
print Oops something didn't work: %s % why
else:
do something 3
do something 4
...
do something 25
--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: coding style - try, except

2009-02-25 Thread Christian Heimes
RGK wrote:
 Any input appreciated :)

How about:

import logging

try:
   # run your function
   some_function()
except Exception:
   # except only the exceptions you *really* want to catch
   # at most you should except Exception since it doesn't
   # catch KeyboardInterrupt and SystemExit
   logging.exception(An error has occured)
   # logging is preferred over a simple print because it
   # also prints out a nice traceback
else:
   # the else block is reached when no exception has occured
   some_other()
finally:
   # the finally block is *always* executed at least
   # use it to clean up some resources
   some_cleanup_code()

Christian

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


Re: Battleship style game

2009-02-25 Thread Shawn Milochik
Thanks. I wasn't aware of the property() function, but I read up on
it. I modified the Vessels.py file, but not the board file (except
where necessary to handle the changes made to Vessels. Is this better?

http://shawnmilo.com/ships/ships2/
--
http://mail.python.org/mailman/listinfo/python-list


Re: variables bound in moudules are None when module is not completely imported

2009-02-25 Thread chrysn
On Tue, Feb 24, 2009 at 03:27:19PM +0100, chr...@fsfe.org wrote:
 * is there a workaround?
 * especially, is there a workaround that works w/o rewriting the
   modules that raise the exceptions? (otherwise, wrapping all the
   stuff called in the __name__==__main__ wrapper into a main()
   function and then calling that would trivially solve that)

update: i've found one, but this only works if the exception is raised
at a point determined by the outside.

to explain why this is applicable: in the examples, i used `1/0` to
raise a zero division exception inside the module whose scope i want to
preserve. in my practical application, the exception is thrown by a
function that was previously prepared by the outside module and monkey
patched to where the inner module is expected to call a method from (in
my case, the gtk main loop).

now if the function raising the exception saves both
`sys._getframe().f_back.f_globals` and a .copy() of that dictionary, the
original dictionary can later (when the exception is caught and the
module's globals are all None) be .update()d with the copy, and the
original module globals are restored.

as said, this is just a workaround -- the original question still
remains open.

regards
chrysn

-- 
To use raw power is to make yourself infinitely vulnerable to greater powers.
  -- Bene Gesserit axiom


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


Re: How do I decode unicode characters in the subject using email.message_from_string()?

2009-02-25 Thread Gabriel Genellina
En Wed, 25 Feb 2009 16:19:35 -0200, Thorsten Kampe  
thors...@thorstenkampe.de escribió:

* Tim Golden (Wed, 25 Feb 2009 17:27:07 +)

Thorsten Kampe wrote:
 * Gabriel Genellina (Wed, 25 Feb 2009 14:00:16 -0200)
 En Wed, 25 Feb 2009 13:40:31 -0200, Thorsten Kampe

[...]
 And I wonder why you would think the header contains Unicode  
characters
 when it says us-ascii (=?us-ascii?Q?). I think there is a  
tendency

 to label everything Unicode someone does not understand.
 And I wonder why you would think the header does *not* contain  
Unicode

 characters when it says us-ascii?.

 Basically because it didn't contain any Unicode characters (anything
 outside the ASCII range).

And I imagine that Gabriel's point was -- and my point certainly
is -- that Unicode includes all the characters *inside* the
ASCII range.


I know that this was Gabriel's point. And my point was that Gabriel's
point was pointless. If you call any text (or character) Unicode then
the word Unicode is generalized to an extent where it doesn't mean
anything at all anymore and becomes a buzz word.


If it's text, it should use Unicode. Maybe not now, but in a few years, it  
will be totally unacceptable not to properly use Unicode to process  
textual data.



With the same reason you could call ASCII an Unicode encoding (which it
isn't) because all ASCII characters are Unicode characters (code
points). Only encodings that cover the full Unicode range can reasonably
be called Unicode encodings.


Not at all. ASCII is as valid as character encoding (coded character set  
as the Unicode guys like to say) as ISO 10646 (which covers the whole  
range).



The OP just saw some weird characters in the email subject and thought
I know. It looks weird. Must be Unicode. But it wasn't. It was good
ole ASCII - only Quoted Printable encoded.


Good f*cked ASCII is Unicode too.

--
Gabriel Genellina

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


Re: variables bound in moudules are None when module is not completely imported

2009-02-25 Thread Gabriel Genellina

En Wed, 25 Feb 2009 16:48:16 -0200, chr...@fsfe.org escribió:


update: i've found one, but this only works if the exception is raised
at a point determined by the outside.

to explain why this is applicable: in the examples, i used `1/0` to
raise a zero division exception inside the module whose scope i want to
preserve. in my practical application, the exception is thrown by a
function that was previously prepared by the outside module and monkey
patched to where the inner module is expected to call a method from (in
my case, the gtk main loop).

now if the function raising the exception saves both
`sys._getframe().f_back.f_globals` and a .copy() of that dictionary, the
original dictionary can later (when the exception is caught and the
module's globals are all None) be .update()d with the copy, and the
original module globals are restored.


That makes a strange situation where the module doesn't exist in  
sys.modules but its globals are still alive...



as said, this is just a workaround -- the original question still
remains open.


I'd try to move all the global stuff in that module into a function,  
init. Importing the module will always succeed - you have to manually  
call init() after importing it.


--
Gabriel Genellina

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


Re: Free Python Training: Washington, DC (3/3-5)

2009-02-25 Thread Alan G Isaac

Great idea, but if you do it again, a bit
more lead time would be helpful.

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


Re: coding style - try, except

2009-02-25 Thread RGK


I'm glad I asked :)

Thanks all who posted for your replies, the else-statement is a nice 
option.


Python again comes through to deal with those pesky feelings that 
something could be better :)


Ross.



Chris Rebert wrote:


Yes. try-except-*else*.

try:
do_something_1()
do_something_2()
except:
print Houston, we have a problem
else: #runs only if no exception was thrown
do_something_3()
do_something_4()
et_cetera()

Cheers,
Chris


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


Re: Free Python Training: Washington, DC (3/3-5)

2009-02-25 Thread Steve Holden
Alan G Isaac wrote:
 Great idea, but if you do it again, a bit
 more lead time would be helpful.
 
Appreciate that. Last-minute idea.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Battleship style game

2009-02-25 Thread Diez B. Roggisch

Shawn Milochik schrieb:

Thanks. I wasn't aware of the property() function, but I read up on
it. I modified the Vessels.py file, but not the board file (except
where necessary to handle the changes made to Vessels. Is this better?

http://shawnmilo.com/ships/ships2/



Not really. The point about properties is that you *can* make attribute 
access trigger getter or setter code.


But not that you do unless there is an actual reason for that. The way 
you do it now is simply introducing clutter, without benefit. Your class 
would be half the current size - without loss of functionality.




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


Re: Python dictionary size/entry limit?

2009-02-25 Thread Martin v. Löwis
 On a 32-bit system, the dictionary can have up to 2**31 slots,
 meaning that the maximum number of keys is slightly smaller
 (about 2**30).
 
 Which, in practice, means that the size is limited by the available memory.

Right. Each slot takes 12 bytes, so the storage for the slots alone
would consume all available address space.

From that point of view, you can't possibly have more than 314M slots
in a 32-bit address space (roughly 2**28).

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


PYTHONPATH on Mac 10.5

2009-02-25 Thread Vincent Davis
I have looked around for a good howto setup PYTHONPATH on Mac os x
10.5 Although I get many results I am not sure which is correct. I am not
sure if it is different for 10.5 over previous versions. Does anyone know of
a well documented set of instructions.
In my python scripts I specify which python I want to use like this
#!/Library/Frameworks/Python.framework/Versions/4.1.30101/bin/python

Is there a way to specify a module location or working directory? Which is
best? Or should I just add location to PYTHONPATH?


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


Re: Python Image Library IOError - cannot find JPEG decoder?

2009-02-25 Thread Irmen de Jong

wongobongo wrote:

On Feb 24, 9:34 am, Dario Traverso traver...@gmail.com wrote:
I've been trying to install the Python Image Library  (PIL) on my Mac  
OSX Leopard laptop, but have been running into some difficulties.


I've built the library, using the included setup.py  script. The build  
summary checks out ok, and sounds the option libraries to all be  
found. I grabbed both libjpeg and freetype2  using  fink.




I did a similar thing, but not using Fink, on my mac (running osx 10.4)
I documented the procedure I had to take to get it to work:
http://www.razorvine.net/frog/user/irmen/article/2008-08-02/127

It's in Dutch but you can probably figure it out.
I guess since you were on 10.5 that you have to adapt the
'DEPLOMENT_TARGET' variable in a suitable manner.

Hope it helps,

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


Re: Battleship style game

2009-02-25 Thread Shawn Milochik
On Wed, Feb 25, 2009 at 3:15 PM, Diez B. Roggisch de...@nospam.web.de wrote:

 Not really. The point about properties is that you *can* make attribute
 access trigger getter or setter code.

 But not that you do unless there is an actual reason for that. The way you
 do it now is simply introducing clutter, without benefit. Your class would
 be half the current size - without loss of functionality.



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


It is true that it would be fewer lines of code with the same
functionality, but it's better practice to have that framework in
place so that any changes made in the future wouldn't break any of the
code accessing my class. Obviously this is a fairly simple game that
has a fixed set of rules, but I'm trying to cultivate good habits, and
I don't think that doing it this way is anti-Pythonic.

Unless, of course, anything I said is wrong, which is always possible.
If I'm missing a bigger-picture idea, I'd like to know about it.

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


Re: Battleship style game

2009-02-25 Thread Steve Holden
Shawn Milochik wrote:
 On Wed, Feb 25, 2009 at 3:15 PM, Diez B. Roggisch de...@nospam.web.de wrote:
 
 Not really. The point about properties is that you *can* make attribute
 access trigger getter or setter code.

 But not that you do unless there is an actual reason for that. The way you
 do it now is simply introducing clutter, without benefit. Your class would
 be half the current size - without loss of functionality.



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

 
 It is true that it would be fewer lines of code with the same
 functionality, but it's better practice to have that framework in
 place so that any changes made in the future wouldn't break any of the
 code accessing my class. Obviously this is a fairly simple game that
 has a fixed set of rules, but I'm trying to cultivate good habits, and
 I don't think that doing it this way is anti-Pythonic.
 
 Unless, of course, anything I said is wrong, which is always possible.
 If I'm missing a bigger-picture idea, I'd like to know about it.
 
The point of using property() is that you can start out using attribute
access on its own (which is the standard Python way to do things:
getters and setters are seen by most as redundant code).

Once you need programmed access on read and/or write, leave the client
code (the code that accesses the attributes) as it is, but turn the
attributes into properties so that the functions are invoked
automatically on attribute-style access.

So I believe what Diez was saying is that by using properties in your
existing code you are getting the worst of both worlds - unnecessarily
complex objects, and code that uses those objects by calling methods
when it could be accessing attributes (or properties - depending on the
implementation). At least this is true of your Ship test code.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


  1   2   >