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

2008-01-29 Thread Gabriel Genellina
QOTW:  The nice thing with Pyrex is that you can use the Python
interpreter, or not use it, more or less depending on your way to declare
things and your way to code.  So, in a way, you have full control over
the compromise between speed and facility.  The temptation is always
strong to use Python facilities, but I guess that with enough discipline,
you can displace and put the equilibrium wherever you want. - Francois Pinard  

If you don't ever need or have the chance to debug it, you probably aren't
doing programming. - Peter Hansen


Early-bird registration for PyCon 2008 continues through 20 February:
http://us.pycon.org/2008/registration/

Proposal: auto-assignment to self of some constructor arguments:

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

Looking for self-evaluating strings, such that eval(s)==s:

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

Four small problems, with several answers and timings:
  Find the minimum value from those associated to keys in a dict:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/c852ac37c28311cb/
  
  Find the index of the maximum element in a list:

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

  Same but minimum element instead:

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

  Take pairs sequentially from a list:

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

Countdown game solver: combine a few numbers with +-*/()
to obtain a given result. Several, very different solutions:

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

Another game: Sudoku, several approaches too, some incredibly short:

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

A guy *really* trying to make sense of Python bytecode disassembled
as if it were actual 80x86 code (still LOLAROTF!!!):

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



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

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

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

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

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

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

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

http://groups.google.com/groups?oi=djqas_ugroup=comp.lang.python.announce

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

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

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

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

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

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

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and 

Storm 0.12 is out!

2008-01-29 Thread Gustavo Niemeyer

On behalf of the Storm development team, I'm proud to announce that
the release 0.12 is out!  This is a very exciting release, as it
brings several fixes and quite a few new features.

Thank you very much to everyone who contributed.

Storm is available at: https://storm.canonical.com


Improvements

 - The Connection will reconnect automatically when connection
   drops are detected and a rollback is performed.  As a result,
   the Store should handle reconnections in a seamless way in
   most circumstances (#94986, by James Henstridge).  This is
   supported in the MySQL and PostgreSQL backends.
 - Store.flush() will not load values inserted in the database.
   Instead, undefined variables are set to AutoReload, and resolved
   once first accessed.  This won't be noticeable in normal usage,
   but will boost the performance of inserts.
 - Support in the postgres backend to use the RETURNING extension of
   the INSERT statement to retrieve the primary key on inserts for
   object identity mapping (PostgreSQL = 8.2 only)
 - Introduced a cache mechanism that keeps the N last retrieved objects
   in memory to optimize cases where the same object is retrieved
   often while no strong references are kept elsewhere.  Implemented by
   Bernd Dorn, from Lovely Systems.
 - Improved support for TimeDelta properties on all backends.  Many
   more formats are accepted now, and some issues were fixed.

Bug fixes
-
 - TimeDelta was added to storm.locals.
 - Fixed TimeDelta support in SQLite, MySQL, and PostgreSQL,
   and enabled base test for all backends to ensure that it
   continues to work.
 - Schema names are accepted in __storm_table__ when using
   PostgreSQL as the database (e.g. schema.table). (#146580,
   reported by James Mayfield)
 - Test runner handles path correctly on Windows, and SQLite
   tests won't break (patch by Ali Afshar).
 - In the SQLite backend, ensure that we're able to recommit a
   transaction after database is locked errors.  Also make sure
   that when this happens the timeout is actually the expected
   one (patch by Richard Boulton)
 - TransactionFailedError is now imported from the public
   place: ZODB.POSException (#129715, by James Henstridge).
 - TimeDelta was added to storm.locals.
 - Tables named with reserved keywords are properly escaped.
 - Reserved keywords on column names are properly escaped when
   part of an insert or update statement (#184849, by Thomas Herve).
 - Prevent cached objects from issuing selects to retrieve their
   data when find()s were previously made and already brough
   their data (#174388, reported and fixed by Bernd Dorn).
 - Fixed bug which caused an object to be readded to the store
   when a reference of an object that had already been removed
   was looked up.
 - Prevent pathological case which happens when a statement like
   SELECT ... WHERE table.id = currval(...) is executed in
   PostgreSQL.  The change is only meaningful on PostgreSQL  8.2,
   as newer versions will use the RETURNING extension instead.
 - Specify both of the joining tables explicitly when compiling Proxy,
   so that it doesn't break due to incorrect references in the ON clause
   when multiple tables are used (reported in #162528 by S3ym0ur and
   Hamilton Tran)
 - MySQL client charset now defaults to UTF-8 (reported
   by Brad Crittenden).


-- 
Gustavo Niemeyer
http://niemeyer.net

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

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


Pydev 1.3.12 Released

2008-01-29 Thread Fabio Zadrozny
Hi All,

Pydev and Pydev Extensions 1.3.12 have been released

Details on Pydev Extensions: http://www.fabioz.com/pydev
Details on Pydev: http://pydev.sf.net
Details on its development: http://pydev.blogspot.com

Release Highlights in Pydev Extensions:
-

* Mark occurrences: only requested on mouse-clicks and cursor changes.
* Code-Analysis: No longer running in UI-Thread (bug which slowed
things down in 1.3.10 and 1.3.11).
* Code-Analysis: Cache optimizations.
* Code-Analysis: Fixed 'statement without effect' when raising
exception with arguments without using the exception constructor.
* Code-Analysis: Fixed 'statement without effect' on tuple creation.
* Code-Analysis: __path__ found for packages (__init__.py files).
* Context-insensitive info: Correctly updated when code-analysis is
off (or if file is not analyzed).


Release Highlights in Pydev:
--

* Code Coverage: coverage.py updated to version 2.78
(http://nedbatchelder.com/code/modules/coverage.html).
* Optimization: Caches (with no memory overhead) added for a number of
situations, which can speed completion requests a lot (up to 40x on
tests).



What is PyDev?
---

PyDev is a plugin that enables users to use Eclipse for Python and
Jython development -- making Eclipse a first class Python IDE -- It
comes with many goodies such as code completion, syntax highlighting,
syntax analysis, refactor, debug and many others.


Cheers,

-- 
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
http://www.esss.com.br

Pydev Extensions
http://www.fabioz.com/pydev

Pydev - Python Development Enviroment for Eclipse
http://pydev.sf.net
http://pydev.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

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


Re: [HELP] SMTPlib not sending my mail

2008-01-29 Thread ashok.raavi

Hi,

I am also facing the same problem, smtplib used to send mail a while
back but it stopped sending mails.

when i run this in interpreter
 import smtplib
 s = smtplib.SMTP(localhost)
 s.sendmail(from, to, message)
{}


though it is not giving any error, it is not sending mail.

Any help is appreciated.

ornto wrote:
 Hi, I'm trying to create an application which checks a
 dynamic web site and on certain events sends an email to me.
 My problem though is with the email task. By now I made this
   simple test code:

 #prova invio email
 smtpserver = smtplib.SMTP(mailserver)
 messaggio= Messaggio di prova
 print mail
 print messaggio
 smtpresult=smtpserver.sendmail(Watcher,mail,messaggio)
 if smtpresult:
  print smtpresult
 smtpserver.quit()

 mailserver and mail values are loaded from a ini file
 and they're correct.
 The call to smtpserver gives back no errors (smtpresult
 remains empty).
 The running enviroment gives no error.
 So, it looks like that the program works alloright, sending
 the mail- BUT, I receive no mail! I've tried to change the
 smtp server with another one which still works with my isp,
 with no luck. If I try a smtp which doesn't give me access,
 I correctly receive an error from the program.
 What might be the problem?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Encryption Recommendation

2008-01-29 Thread Michael Ströder
Diez B. Roggisch wrote:
 [EMAIL PROTECTED] wrote:
 
 I'm still using Python 2.4.  In my code, I want to encrypt a password
 and at another point decrypt it.  What is the standard way of doing
 encryption in python?  Is it the Pycrypto module?
 
 Usually, one doesn't store clear-text passwords. Instead, use a
 hash-algorithm like md5 or crypt (the former is in the standard lib, don't
 know of the other out of my head) and hash the password, and store that
 hash.
 
 If a user enters the password, use the same algorithm, and compare the
 resulting hashes with the stored one.

And don't forget to add a salt so that same passwords do not have the 
same hash.

But if the password checking is done with a challenge-response mechanism 
(e.g. HTTP-Digest Auth or SASL with DIGEST-MD5) it's required that the 
instance checking the password has the clear-text password available. So 
reversible encryption for storing passwords might be required.

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


Re: Just for fun: Countdown numbers game solver

2008-01-29 Thread david . hotham
On Jan 28, 10:11 pm, Arnaud Delobelle [EMAIL PROTECTED] wrote:
 My strategy was to walk through each solution only once (for a
 certain definition of only once :), thus I was hoping not to need a
 hashtable.

Yes, that seems like it should be preferable (and indeed necessary for
a more general problem with larger numbers of seeds).  But I wasn't
smart enough to figure out how to do it ;-)

 Did you pick these numbers at random?  Interestingly, the solution is
 unique:

Not at random -  this particular puzzle came out of the first post in
this thread.

  Mine is faster on this example, but one example is not representative!

If you've found an efficient way to walk through the possible
solutions only once, then
-  I expect that yours will be faster
-  and well done!

I guess I should try to understand your code...

 --
 Arnaud

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


Announcing the Python core sprint at PyCon 2008

2008-01-29 Thread Brett Cannon
As has occurred since the inception of PyCon, there will be a sprint
on the Python core at this year's conference!

If you will be attending PyCon (or will be in Chicago during the dates
of the sprints), attending the sprint is a great way to give back to
Python. Working on Python itself tends to deepens one knowledge of the
language and the standard library. Plus it is just plain fun getting
to sit around some tables with fellow Python programmers for several
days (the sprint will last four days, but you do not need to attend
all four days to participate).

The sprint is open to everyone of all skill levels. We can always use
help with things from updating documentation to preparing for the next
release of Python 3.0.

On Sunday evening of the conference there will not only be a sprint
intro session, but also a tutorial on how to develop for Python.
Details will be covered from where to look in the code base for things
to some best practices tips.

If you are interested enough to want to sign up to attend, please go
to http://wiki.python.org/moin/PyCon2008/SprintSignups/Python and add
your name and email address. If you have questions you may email me.

Please sign up for the sprint by the end of February as an email on
what you need to do beforehand will be sent at that time based on the
sprint sign-up page.

And if you are not attending PyCon, we will most likely have several
people in attendance on IRC, thus allowing even people not at PyCon to
participate!

-Brett Cannon
Python core sprint coach, PyCon 2008
-- 
http://mail.python.org/mailman/listinfo/python-list


Intra-package References?? (again)

2008-01-29 Thread marcroy . olsen
Hi Python list,

I have been struggleling with this before, but have never been able to
find a good solution.
The thing I dont understand is, I follow the guide here:
http://docs.python.org/tut/node8.html#SECTION00842
And have the same setup as the packages howto here:http://
docs.python.org/tut/node8.html#SECTION00840

But when I want to use Intra-package References, I need to put the
path to the packages explicit like this:
#sys.path.append('/path/to/pack/')
Before I can make import like this:
#from Sound.Effects import echo
from within the karaoke.py (just to stay with the tut)
If I print the sys.path from the same file, I can see that
#/path/to/pack/Sound/Filters/
is in the path.

Is there something that I completely is missing or could someone
please show me how, by example, how I use Intra-package References.

Best regards

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


Re: [HELP] SMTPlib not sending my mail

2008-01-29 Thread Lars Johansen
have you checked your mail server logs ?

tir, 29.01.2008 kl. 00.24 -0800, skrev ashok.raavi:
 Hi,
 
 I am also facing the same problem, smtplib used to send mail a while
 back but it stopped sending mails.
 
 when i run this in interpreter
  import smtplib
  s = smtplib.SMTP(localhost)
  s.sendmail(from, to, message)
 {}
 
 
 though it is not giving any error, it is not sending mail.
 
 Any help is appreciated.
 
 ornto wrote:
  Hi, I'm trying to create an application which checks a
  dynamic web site and on certain events sends an email to me.
  My problem though is with the email task. By now I made this
simple test code:
 
  #prova invio email
  smtpserver = smtplib.SMTP(mailserver)
  messaggio= Messaggio di prova
  print mail
  print messaggio
  smtpresult=smtpserver.sendmail(Watcher,mail,messaggio)
  if smtpresult:
   print smtpresult
  smtpserver.quit()
 
  mailserver and mail values are loaded from a ini file
  and they're correct.
  The call to smtpserver gives back no errors (smtpresult
  remains empty).
  The running enviroment gives no error.
  So, it looks like that the program works alloright, sending
  the mail- BUT, I receive no mail! I've tried to change the
  smtp server with another one which still works with my isp,
  with no luck. If I try a smtp which doesn't give me access,
  I correctly receive an error from the program.
  What might be the problem?

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


Re: Python self-evaluating strings

2008-01-29 Thread Ant
In the spirit of Simple is better than complex. and totally
bypassing the intention of quines (though not necessarily the
definition):

--- probably_not_a_real_quine.py  
import sys

for line in open(sys.argv[0]):
print line,

--
;-)

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


Re: Python Standardization: Wikipedia entry

2008-01-29 Thread Terry Reedy

Roy Smith [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
| But, surely Python has plenty of implementation defined aspects.
| Especially in the libraries.

I personally do not consider the libraries as part of the language (as 
opposed to the distribution) and was not referring to them.  The semantics 
of the syntax is pretty tightly defined.  The main exception is floating 
point, which is a nuisance.  Which is why one implementation aspect thereof 
is being standardized in the next version.

| Especially those parts of the libraries which
| are thin layers on top of operating system services (os and socket come 
to
| mind as two highly variable areas).

I am sure that sockets are not part of the C89 standard.  Hence the high 
variability.  (I don't know about the newer C standard).   I would expect 
that socket.py makes the variability no worse and presume that it masks at 
least a bit of it.  Ditto for some os services.

tjr




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


Re: Encryption Recommendation

2008-01-29 Thread Paul Rubin
Michael Ströder [EMAIL PROTECTED] writes:
 But if the password checking is done with a challenge-response
 mechanism (e.g. HTTP-Digest Auth or SASL with DIGEST-MD5) it's
 required that the instance checking the password has the clear-text
 password available. So reversible encryption for storing passwords
 might be required.

If you're trying to authenticate network logins using passwords, and
if you have control over both ends of the protocol but for some reason
don't want to use a full-blown encryption scheme, it's far better to
authenticate with something like SRP (http://srp.stanford.edu) than a
more primitive method like HTTP digest auth.  SRP doesn't require
storing plaintext passwords, and more importantly, it protects the
password from offline dictionary searches by someone sniffing the
network connection.  

There is a Python SRP implementation embedded in TLSLite
(www.trevp.com/tlslite) but it might be nice to extract or reimplement
the SRP code so that it can be used separately from TLS.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optional static typing for Python

2008-01-29 Thread Ben Finney
Russ P. [EMAIL PROTECTED] writes:

 I would just like to thank you for reminding me about what losers
 hang out perpetually on sites like this one, thinking they are in
 some kind of real community. Being reminded of that will help
 prevent me from becoming such a loser myself. No, I didn't say that
 all the regulars here are losers, but you most certainly are.

We're a community largely because we don't tolerate this level of
content-free insult. Please find a different forum for this stuff.

-- 
 \   We spend the first twelve months of our children's lives |
  `\  teaching them to walk and talk and the next twelve years |
_o__)telling them to sit down and shut up.  -- Phyllis Diller |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


refcount

2008-01-29 Thread Simon Pickles
Hi,

Is is possible to access the refcount for an object?

Ideally, I am looking to see if I have a refcount of 1 before calling del

Thanks

Simon

-- 
Linux Counter: User# 424693 



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


Re: validate string is valid maths

2008-01-29 Thread Matthew_WARREN

It was a very loosely thought out problem, and my Maths isn't good enough
to define 'sane' rules for collapsing the signs/operators to  make a
sensible expression; so take my constraints with a pinch of salt.

I guess a better way of putting it may be - now it has been pointed out
that 8+++9 is valid;

Remove the smalles number of symbols such that eval() will always return a
number, and the result is always the same.

and I havent had a chance to play with the couple of solutions posted
yet, so those criteria may have already been met.

One thing I have discovered is you cant just pass arbitrary valid
(expression wise) numeral/symbol strings to eval and have it work as
expected;

 eval('8-038')
Traceback (most recent call last):
  File stdin, line 1, in module
  File string, line 1
8-038
   ^
SyntaxError: invalid token

becasue of
 eval('8-010')
0

Can I escape the meaning of the leading 0's on an integer?

and despite my initial claims, there is an overall aim. Still purely
just to play with python though - after someone mentioned Genetic
Algorithms on the list yesterday I thought I'd have a go at a very simple
one.

These long symbol/number strings are the 'genomes/chromosomes' (not certain
on correct terms), the 'genes' are 1234567890+/-*


I'm generating large populations of arbitrary length chromosomes. Using
eval(chromosome) to compute a number. The fittest individuals are the ones
who's genome evaluates closest to 1000, so in essence I'm evolving
solutions to making the number 1000 using 1234567890/*-+ (this was
partially inspired by the countdown numbers game discussed here too.).
Trivial and possibly pointless, but shiny enough for me to play with :)


Matt.




   
   Internet 
   
   [EMAIL PROTECTED]
  

To 

python-list
   Sent by: 
cc 
   python-list-bounces+matthew.warren=uk.bnpparibas.com@
   
   python.org   
   Subject 
Re: 
validate string is valid maths 
   28/01/2008 18:30 
   

   

   

   

   

   

   




impor tOn 28 ene, 14:31, [EMAIL PROTECTED] wrote:

 What would be the 'sensible' way of transforming the string, for example
 changing '3++8' into 3+8
 or '3++--*-9' into '3+-9' such that  eval(string) will always return a
 number?

'3++8' is already a valid expresion, like '3++---9'

 in cases where multiple symbols conflict in meaning (as '3++--*-9' the
 earliest valid symbols in the sequence should be preserved

 so for example,

 '3++*/-9' = 3+-9
 '45--/**/+7'  = 45-+7
 '55/-**+-6**' = 55/-6

Why not 3++-9, 45--+7? Does it have to be two operators? Why not 3++9
instead? they're the two earliest valid symbols. Can't repeat yourself
then? (I'm trying to understand the rules...)

This approach uses regular expressions. It doesn't follow all your
rules, and tries to get the longest valid expression:

import re

def repl_middle(match):
  g = match.group()
  if g[0] in '*/':
g0 = g[0]
g = g[1:]
  else: g0 = ''
  return g0 + g.replace('*','').replace('/','')

def repl_start(match):
  g = match.group()
  return g.replace('*','').replace('/','')

def dropinvalid(s):
  s = re.sub(r'(?=\d)[+*/-]+(?=\d)', repl_middle, s)
  s = re.sub(r'^[+*/-]+', repl_start, s)
  s = re.sub(r'[+*/-]+$', '', s)
  return s

cases = [
  ('3++8', '3+8'),
  ('3++--*-9', '3+-9'),
  ('3++*/-9', '3+-9'),
  ('45--/**/+70', '45-+70'),
  ('55/-**+-6**', '55/-6'),
 

Re: Error in parsing XML for following test data

2008-01-29 Thread Stefan Behnel
abhishek wrote:
 I am having problem parsing following data set from XML. Please
 provide hints on how to rectify this problem.
 
 I am using python2.4 version
 
 this is te test data that i am using --
 
 
 1!!!11
 2@@@22
 3###33
 4$$$44

[...]

How is this related to XML?

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


Error in parsing XML for following test data

2008-01-29 Thread abhishek
Hello group,


I am having problem parsing following data set from XML. Please
provide hints on how to rectify this problem.


I am using python2.4 version

this is te test data that i am using --


1!!!11
2@@@22
3###33
4$$$44
5%%%55
6^^^66
777
8***88
9(((99
10)))00
11-
12=
13+
14|
15\
16
17
18/
19?
20;
21:
22'
23
24[
25]
26{
27}
28*
29+
30-
31`
32~
33.
Special Characters
#!/bin/bash
#start TG app
cd $1
exec ./start-infopsyM.py




This is really a nasty data set.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py3k feature proposal: field auto-assignment in constructors

2008-01-29 Thread coldpizza
Hi,

I appreciate everyone's feedback on the topic.

Having reflected on what has been said here, I now realize that
creating more complexity is not the way to go. I would rather favor
something that relies on existing language features, something like
the default keyword argument assignment in functions.

This is probably stupid but as a noob I would have liked something
like:
def __init__( self. = host, self. = port, self. = timeout, message =
Connected.):
pass

This is probably even more preposterous than @host, @port, but to me
it would make more sense.

I suppose the subject has exhausted itself and I am not going to
follow it up. If anyone is interested in taking it on, then please do.

Best,
coldpizza


On Jan 29, 6:01 am, Terry Reedy [EMAIL PROTECTED] wrote:
 André [EMAIL PROTECTED] wrote in message

 news:[EMAIL PROTECTED]
 |Here's a version that
 |1. does not require new syntax
 |2. does not *necessarily* override the _ prefix convention

 'self_' is way too bulky and intrusive.  Putting '_' at the end of the word
 is nearly as easy to detect and conflicts with no convention I know of.

 tjr

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


Re: refcount

2008-01-29 Thread Duncan Booth
Simon Pickles [EMAIL PROTECTED] wrote:
 Is is possible to access the refcount for an object?

 import sys
 sys.getrefcount(42)
6

 Ideally, I am looking to see if I have a refcount of 1 before calling del

That's a pointless exercise: you probably don't understand what del does.

All that del does is remove one reference from an object, either by 
removing a name from the namespace, or by removing a reference from 
something like a list. 'del x' does NOT destroy the object referenced by x, 
unless it happens that there are no other references to the object.

Also note that the only time you will see a reference count of 1 is on an 
object which you cannot otherwise access (the only reference is being used 
for the call to getrefcount()):

 x = 9
 sys.getrefcount(x)
2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: REALLY simple xml reader

2008-01-29 Thread Stefan Behnel
Ricardo Aráoz wrote:
 What about :
 
 doc = 
 moo
bar99/bar
 /moo
 foo
bar42/bar
 /foo
 

That's not an XML document, so what about it?

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


Pydev 1.3.12 Released

2008-01-29 Thread Fabio Zadrozny
Hi All,

Pydev and Pydev Extensions 1.3.12 have been released

Details on Pydev Extensions: http://www.fabioz.com/pydev
Details on Pydev: http://pydev.sf.net
Details on its development: http://pydev.blogspot.com

Release Highlights in Pydev Extensions:
-

* Mark occurrences: only requested on mouse-clicks and cursor changes.
* Code-Analysis: No longer running in UI-Thread (bug which slowed
things down in 1.3.10 and 1.3.11).
* Code-Analysis: Cache optimizations.
* Code-Analysis: Fixed 'statement without effect' when raising
exception with arguments without using the exception constructor.
* Code-Analysis: Fixed 'statement without effect' on tuple creation.
* Code-Analysis: __path__ found for packages (__init__.py files).
* Context-insensitive info: Correctly updated when code-analysis is
off (or if file is not analyzed).


Release Highlights in Pydev:
--

* Code Coverage: coverage.py updated to version 2.78
(http://nedbatchelder.com/code/modules/coverage.html).
* Optimization: Caches (with no memory overhead) added for a number of
situations, which can speed completion requests a lot (up to 40x on
tests).



What is PyDev?
---

PyDev is a plugin that enables users to use Eclipse for Python and
Jython development -- making Eclipse a first class Python IDE -- It
comes with many goodies such as code completion, syntax highlighting,
syntax analysis, refactor, debug and many others.


Cheers,

-- 
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
http://www.esss.com.br

Pydev Extensions
http://www.fabioz.com/pydev

Pydev - Python Development Enviroment for Eclipse
http://pydev.sf.net
http://pydev.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Executing other python code

2008-01-29 Thread Diez B. Roggisch
Tim Rau wrote:

 I'm working on a game, and I'd like players to be able to define thier
 ships with scripts. Naturally, I don't want to give them the entire
 program as thier romping ground. I would like to invoke a seperate
 interpreter for these files, and give it a limited subset of the
 functions in my game. What is the best way to achieve this effect?

You might consider spawning a process and using Pyro to communicate. I've
done that before and it worked pretty well.

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


Re: extending Python - passing nested lists

2008-01-29 Thread Christian Meesters
Thanks. Point is that all such approaches would require lots(!) of calls to
the Python API - a way by which I won't gain the desired speed. 

I've tried pyrex and the corresponding C-file is so convoluted with dummy
variables, incrementing  decrementing references, and other stuff, that I
want to try to write a C-function myself. My goal is not to avoid 
PyObjects* and the corresponding reference handling - apart from the head
and end of the function. (I could use ctypes instead, but that again would
obfuscate the API of my package a bit.)

Christian

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


Changing module variables.

2008-01-29 Thread Albert van der Horst
I have made a sudoku solver, and discovered I simply 
can turn it into a hexadoku solver, like so:
___
# sudoku solver using sets
import sudoku

sudoku.symbols=0123456789ABCDEF
sudoku.size=16 
sudoku.sqs=4 # square root of size .
___

Example of usage:


___
y=sudoku.sudoku(
  B   95E  8 1C
9 7  1 C   8 B A 46
 4  0  871 3 59
C 8 7FA 24 BD  

7   4  1 5  
   42  0   BAC1
   8 6A F  5  2 9D 
C281 7   9 

A3 E5 B 
   08 E B C96  1A3 
   D 50  AE
   6  1  A F  5DC28

58  3C   6 41AD 
   1E 6 54273D  08F
   B3814 67
   240D 16F 8 3

)


y.show()
y.solve()
y.show()

___

I like this. It certainly is reusability.
  
Still I wonder what you guys think of this?
(I know some OO-boys who would spank me for it.)

Groetjes Albert

-- 

-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- like all pyramid schemes -- ultimately falters.
[EMAIL PROTECTED]arc.xs4all.nl =n http://home.hccnet.nl/a.w.m.van.der.horst
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: refcount

2008-01-29 Thread Benjamin
On Jan 29, 5:46 am, Christian Heimes [EMAIL PROTECTED] wrote:
 Simon Pickles wrote:
  Hi,

  Is is possible to access the refcount for an object?

  Ideally, I am looking to see if I have a refcount of 1 before calling del

 Help on built-in function getrefcount in module sys:

 getrefcount(...)
 getrefcount(object) - integer

 Return the reference count of object.  The count returned is generally
 one higher than you might expect, because it includes the (temporary)
 reference as an argument to getrefcount().
Are there any cases when it wouldn't?

 Christian

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


MySQLdb

2008-01-29 Thread [EMAIL PROTECTED]
hello,
i have problem manipulating mySQL data. When i add values in a Table,
i can recieve them instantly but when i check the table from another
script, the new values dont exist.

i'm not experienced in sql dbses so the problem might be something
outside python.

example (i do this to add values, and then i check and values have
been added):


import MySQLdb
conn = MySQLdb.connect (host = 'localhost',
   user = 'root',
   passwd = 'MYPASHERE',
   db = 'test')
cursor = conn.cursor ()

cursor.execute (
  INSERT INTO testsignin (user, pass, secretcode)
  VALUES
('dkiauser', 'dkiapass', 'dkiacode'),
('gmtuser', 'gmtpass', 'gmtcode')
)

print Number of rows inserted: %d % cursor.rowcount

cursor.execute ('SELECT * FROM testsignin WHERE user=gmtuser')
row = cursor.fetchone()
print row


but then when i try to get them from another script with this:


import MySQLdb
conn = MySQLdb.connect (host = 'localhost',
   user = 'root',
   passwd = 'MYPASHERE',
   db = 'test')
cursor = conn.cursor ()

cursor.execute ('SELECT * FROM testsignin WHERE user=gmtuser')
row = cursor.fetchone()
print row


i get a None
-- 
http://mail.python.org/mailman/listinfo/python-list


Mx.ODBC insert error

2008-01-29 Thread Greg Corradini

Hello,
I've never gotten this traceback error before using mx.ODBC. Any ideas about
resolving this issue? The statement and the error it generates are listed
below.

curse.execute(Insert into FHWA_StandSamp_2008(LRS_ID_NEW)
values('040210') where LRS_ID = '0403700010')

Traceback (most recent call last):
File pyshell#37, line 1, in ?
  curse.execute(Insert into FHWA_StandSamp_2008(LRS_ID_NEW) values
('040210') where LRS_ID = '0403700010')
ProgrammingError: ('37000', -3516, '[Microsoft][ODBC Microsoft Access
Driver] Missing semicolon (;) at end of SQL statement.', 4612)

Thanks
Greg

-- 
View this message in context: 
http://www.nabble.com/Mx.ODBC-insert-error-tp15163149p15163149.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: extending Python - passing nested lists

2008-01-29 Thread Christian Meesters
 You didn't mention speed in your original post.
Sorry, perhaps I considered this self-evident - which it is, of course, not.

 What about using 
 array.array?  Unless I am mistaken, these are just a thin wrapper
 around normal C arrays.
The algorithm I want to implement requires several million floating point
operations. Neither the array-modules nor numpy's thin layer seem thin
enough for me. ;-)

 Anyway you could always convert your list 
 into a c array, do lots and lots of fast calculations, then convert it
 back again to a list.
I guess I am too blind to see, but I couldn't discover a method description
like double* PyList_toDouble. So, yes, my question is a C-API-newbie
question: What is the way to say myCarray = SomePyMethod(InputPyList)? Or
better, what should be here instead
static PyObject *_foo(PyObject *self, PyObject *args) {
  double *v;
  if (!PyArg_Parse(args, (d), v))
return NULL;
to get a list as an array of doubles into 'v' (and back to Python)?

I did read the API-description, but still am lost at this point. I presume,
once I get to know the answer I'll bang my head on the table ... ;-)

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


Re: optional static typing for Python

2008-01-29 Thread Chris Mellon
On Jan 28, 2008 10:31 AM, John Nagle [EMAIL PROTECTED] wrote:
 Arnaud Delobelle wrote:
  On Jan 27, 11:00 pm, Russ P. [EMAIL PROTECTED] wrote:
  On Jan 27, 2:49 pm, André [EMAIL PROTECTED] wrote:
  Perhaps this:http://www.python.org/dev/peps/pep-3107/mightbe
  relevant?
  André
  Thanks. If I read this correctly, this PEP is on track for Python 3.0.
  Wonderful!
 
  Note that annotations do not provide explicit typing, AFAIK:
 
  def f(x:int) - int: return x*2
 
  is stricly equivalent to
 
  def f(x): return x*2
  f.__annotations__ = {'x':int, 'return':int}
 
  You still need to write a type-checking wrapper.

 Unenforced static typing is somewhat pointless.  If that
 goes in, it should be enforced by implementations.  Otherwise,
 maintenance programmers can't trust the type information they see.

 Enforced, it makes it possible to start getting serious about
 optimizing compilers for Python, like Shed Skin.  Shed Skin
 can usually figure out typing within a module, but across module
 boundaries, some help is needed if you want to push optimization from
 run time to compile time.

Given the difficulty of statically analyzing Python, and the
limitations you need to add for either static typing or type inference
to be practical, I think that the real future for faster Python code
is JIT, not static optimizations. Languages which enforce static
typing are, of course, not Python - that's why they have different
names, like Pyrex or ShedSkin or RPython.

I think static Python is pretty much a waste of time, really - if I'm
going to write statically typed code using a traditional C/C++/Java
style type system, I'll use a language designed for it, like D. If I
want *real* strict typing - the kind where you can actually make a
useful inference from the fact that the program is type-correct - I'll
use Haskell or Ocaml. There is a lot of choice out there and there's
no reason to try to make Python into whatever your favorite paradigm
is.
-- 
http://mail.python.org/mailman/listinfo/python-list


runscript module, where are the docs...

2008-01-29 Thread glomde
Hi!

I am going through some code and found
import runscript

BUT I cant find and information about this module. I searched Google
did a grep in
the /usr/lib/python directory.

What is the purpose of this module and where can I find information
about it. Or  the source.

Best regards,

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


Reflection and aspect programming in Python

2008-01-29 Thread Jean-François Houzard
Hello,

I'm a student at UCL Belgium and I have to write a paper about reflection
and introspection in Python.

It is somewhat difficult to find advanced information about reflection in
Python, not only introspection but also the other sides of reflection.
I'm using the book: Programming Python, Thrid Edition but the chapter only
describes briefly some useful functions. The IBM site talks somewhat about
the concept of metaclass but is there more about reflection than only
metaclass programming?

I'm also looking for a class diagram of the hierachy of the python classes
metaclass, class, object but didn't find it nor did I find lots of
information about that subject.

I looked around on the site www.python.org and some others about what could
be a killer application using reflection in Python an maybe more information
about it. Like how does it use reflection to do the trick.

Is there an advanced and completed Aspect Python plugin or are they all
experimental?
Are there some papers about that part of reflection or more detailed sites
that talks about it.


It's a wide subject with open questions. I lack a lot of information about
it and finding advanced topics on the subject isn't that easy. That's why I
ask those questions here, to have some enlightments and maybe some leads to
explore.

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

Re: Removal of element from list while traversing causes the next element to be skipped

2008-01-29 Thread [EMAIL PROTECTED]
On Jan 29, 8:34 am, William McBrine [EMAIL PROTECTED] wrote:
 Look at this -- from Python 2.5.1:

  a = [1, 2, 3, 4, 5]
  for x in a:

 ... if x == 3:
 ... a.remove(x)
 ... print x
 ...
 1
 2
 3
 5

  a
 [1, 2, 4, 5]

 Sure, the resulting list is correct. But 4 is never printed during the
 loop!

(snipped)


If you're going to delete elements from
a list while iterating over it, then do
it in reverse order:

 a = [ 98, 99, 100 ]
 last_idx = len(a) - 1
 for i, x in enumerate(a[::-1]):
... if x == 99: del(a[last_idx - i])
... print x
...
100
99
98
 a
[98, 100]

--
Hope this helps,
Steven

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


RE: Python noob SOS (any [former?] Perlheads out there?)

2008-01-29 Thread Reedick, Andrew
 -Original Message-
 From: [EMAIL PROTECTED] [mailto:python-
 [EMAIL PROTECTED] On Behalf Of kj
 Sent: Tuesday, January 29, 2008 11:39 AM
 To: python-list@python.org
 Subject: Python noob SOS (any [former?] Perlheads out there?)
 
 
 
 For many months now I've been trying to learn Python, but I guess
 I'm too old a dog trying to learn new tricks...  For better or
 worse, I'm so used to Perl when it comes to scripting, that I'm
 just having a very hard time getting a hang of The Python Way.
 
 It's not the Python syntax that I'm having problems with, but rather
 with larger scale issues such as the structuring of packages,
 techniques for code reuse, test suites, the structure of
 distributions,...  Python and Perl seem to come from different
 galaxies altogether...


It sound like less of a How to do Things the Python Way problem, a
more of a How to do Object Oriented Programming problem.
 
Coming from a C++/Perl background, I found the O'Reilly 'Learning
Python' book to be useful.  It has a section on OOP, which covers basic
OO theory that you may find useful.  I can't think of a decent OO book
to recommend though.  


 Be that as it may, the activation barrier to using Python for my
 scripting remains too high.
 
 I'd written a Perl module to facilitate the writing of scripts.
 It contained all my boilerplate code for parsing and validating
 command-line options, generating of accessor functions for these
 options, printing of the help message and of the full documentation,
 testing, etc.

Bleh.  Perl and Python have really good libraries.  Why waste time
rolling your own when you can use Python's getopt or optparse, or Perl's
Getopt and Getopt::Long?


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


Re: Removal of element from list while traversing causes the next element to be skipped

2008-01-29 Thread Berteun Damman
On Tue, 29 Jan 2008 16:34:17 GMT, William McBrine [EMAIL PROTECTED] wrote:
 Look at this -- from Python 2.5.1:

 a = [1, 2, 3, 4, 5]
 for x in a:
 ... if x == 3:
 ... a.remove(x)
 ... print x
 ... 
 1
 2
 3
 5
 a
 [1, 2, 4, 5]

You have to iterate over a copy of 'a', so for x in a[:]. Modifying a
list while iterating over is a recipe for problems. (As it is in many
other programming languages.)

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


Re: Module/package hierarchy and its separation from file structure

2008-01-29 Thread Carl Banks
On Jan 29, 7:48 am, Peter Schuller [EMAIL PROTECTED]
wrote:
  You can also put, in animal/__init__.py:
   from monkey import Monkey
  and now you can refer to it as org.lib.animal.Monkey, but keep the
  implementation of Monkey class and all related stuff into
  .../animal/monkey.py

 The problem is that we are now back to the identity problem. The class
 won't actually *BE* org.lib.animal.Monkey.

The usage is the same; it works in all cases once you redefine
__module__.  Who cares what it really is?


 Perhaps manipulating
 __module__ is enough; perhaps not (for example, what about
 sys.modules?).

It's enough.  It satisfies the criteria you listed. sys.modules has
nothing to do with it.  Monkey is a class, not a module.

If you set __module__, the only remaining discernable difference is
that the global variables accessed from the Monkey class will be in
org.lib.animal.monkey instead of org.lib.animal.  This has no ill
effects when unpickling or instantiating the class from
org.lib.animal.

 Looks like I'll just live with putting more than I
 would like in the same file.

Whatever.  ISTM you came here looking for a particular means and not a
particular end.  Python already has the power to meet your stated
needs, but you won't use that solution because it's hacky.
Apparently all you really wanted was the loosened file structure in
the first place.


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


Re: Python Standardization: Wikipedia entry

2008-01-29 Thread John Nagle
Paddy wrote:
 I would value the opinion of fellow Pythoneers who have also
 contributed to Wikipedia, on the issue of Is Python Standardized.
 Specifically in the context of this table:
   
 http://en.wikipedia.org/wiki/Comparison_of_programming_languages#General_comparison
   (Comparison of programming languages)
 And this entry in the talk page
   
 http://en.wikipedia.org/wiki/Talk:Comparison_of_programming_languages#Standardized_Python.3F
   (Talk:Comparison of programming languages#Standardized Python?)
 
 - Thanks.

   That's correct.  Python is not standardized by any standards body.  And no
two implementations are even close to compiling the same language.

   A consequence of the lack of standardization is that it discourages
implementations.  There are about four implementations of something like
Python (other than CPython), and none of them are close to being usable.
Letting the author of one implementation control the language discourages
other implementations.

   Submitting Python 2.5 to ISO/ANSI might be a good idea.

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


Re: MySQLdb

2008-01-29 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

 hello,
 i have problem manipulating mySQL data. When i add values in a Table,
 i can recieve them instantly but when i check the table from another
 script, the new values dont exist.
 
 i'm not experienced in sql dbses so the problem might be something
 outside python.
 
 example (i do this to add values, and then i check and values have
 been added):
 
 
 import MySQLdb
 conn = MySQLdb.connect (host = 'localhost',
user = 'root',
passwd = 'MYPASHERE',
db = 'test')
 cursor = conn.cursor ()
 
 cursor.execute (
   INSERT INTO testsignin (user, pass, secretcode)
   VALUES
 ('dkiauser', 'dkiapass', 'dkiacode'),
 ('gmtuser', 'gmtpass', 'gmtcode')
 )
 
 print Number of rows inserted: %d % cursor.rowcount
 
 cursor.execute ('SELECT * FROM testsignin WHERE user=gmtuser')
 row = cursor.fetchone()
 print row
 
 
 but then when i try to get them from another script with this:
 
 
 import MySQLdb
 conn = MySQLdb.connect (host = 'localhost',
user = 'root',
passwd = 'MYPASHERE',
db = 'test')
 cursor = conn.cursor ()
 
 cursor.execute ('SELECT * FROM testsignin WHERE user=gmtuser')
 row = cursor.fetchone()
 print row
 
 
 i get a None

You need to commit your changes, using

conn.commit()

after doing them.

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


Re: refcount

2008-01-29 Thread Mel
Benjamin wrote:
 On Jan 29, 5:46 am, Christian Heimes [EMAIL PROTECTED] wrote:
 Simon Pickles wrote:
 Hi,
 Is is possible to access the refcount for an object?
 Ideally, I am looking to see if I have a refcount of 1 before calling del
 Help on built-in function getrefcount in module sys:

 getrefcount(...)
 getrefcount(object) - integer

 Return the reference count of object.  The count returned is generally
 one higher than you might expect, because it includes the (temporary)
 reference as an argument to getrefcount().
 Are there any cases when it wouldn't?

Well, as long as the object is named object in sys.getrefcount's 
namespace, there's at least that one reference to it...

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


Re: Terse Syntax through External Methods

2008-01-29 Thread Bruno Desthuilliers
Jens a écrit :
 On Jan 25, 3:19 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 Jens schrieb:



 Hello Everyone
 I'm newbie to Zope and i have a few questions regarding external
 methods. 
(snip)
 This doesn't work because because the method doesn't have access to
 the environment.

 If it has to be an External method, you can't access such a context
 AFAIK.

IIRC, that's what the 'self' argument is for. Now I don't know if it 
will solve the OP's problem with dtml (which I avoid like pest).

 But then you can create a python script that _has_ this context,
 and passese it to the external method. Not the nicest solution, but
 should work.

 
 Like I said i'm a newbie. I though the deal with Zope was that i
 couldn't really do inline scripting (for security reasons)
 like in php but had to use these external methods. how does one go
 about creating a normal python script exactly and
 how do I invoke it's functionality?

Zope (well... Zope2.x) has an object type named Script (Python). What 
you can do with them is restricted (for security reasons) but is 
obviously enough for what you want here. And really, you should *not* 
use dtml unless you have no other choice at all.

Anyway: Zope is a world in itself, and most pythoneers don't use it. The 
Zope experts are mostly on the Zope's mailing list, so that's where you 
should post such questions.

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


Trouble loading dll via ctypes

2008-01-29 Thread subopt inTheVicinityOf geemail.com
I'm trying to load a dll via ctypes by doing this:

cdll.LoadLibrary('/path/to/mylib.so')

But i'm getting this:

/path/to/mylib.so: cannot open shared object file: No such file or
directory What am i doing wrong?

The dll in question is in a directory mounted via NSF, but no part of
the path/filename is a symlink. When i try code from the docs:

cdll.LoadLibrary('libc.so.6')

,then all is fine.

I've also tried to set my LD_LIBRARY_PATH before starting Python,
checking it via os.environ, then doing the cdll.LoadLibrary(...), but
that fails with the same complaint. What am i doing wrong?

tia,
Eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems installing Python on server

2008-01-29 Thread jim-on-linux
On Tuesday 29 January 2008 01:20, Devraj 
wrote:
 Also be careful and setup all the paths
 that is required for compiling various
 Python modules etc.

 On Jan 29, 8:28 am, Yansky 
[EMAIL PROTECTED] wrote:
  I asked my hosting company if they would
  upgrade Python on my server to the
  latest version. They responded with:
 
  Sorry no. We tend to stick with what
  comes packaged with the unix
  distribution to ease maintenance issues.
 
  There is nothing stopping you from
  running your own version of python from
  within your own account. Download the
  source and compile it and install it
  into your own space. Adjust the fist
  line of your python scripts to reflect
  the location of YOUR python binary:
 
  #! /home/youraccount/yourlibs/python
 
  and you should be all set.
 

Go to the ReadME file after you unpack 
python.
Open  and look for   Installing. 
Read the section, it explains how to install 
on the entire system and how to install 
locally.
Make altinstall  is what you are looking 
for.

jim-on-linux
http:\\www.inqvista.com




 
  The build instructions for Python are:
  To start building right away (on UNIX):
  type ./configure in the current
  directory and when it finishes, type
  make. This creates an executable
  ./python; to install in usr/local,
  first do su root and then make
  install.
 
  The problem is, I don't have root access
  to the server so I can't do the make
  install. I have ubuntu on my computer,
  but from what I understand I can't
  compile it on that and upload it because
  the server runs Red Had and the
  ./configure would have made it
  incompatible right?
 
  So how can I build Python without root
  access?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Executing other python code

2008-01-29 Thread Martin Skou
Over-simplified yes, but it will work!

Python is beautiful :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Standardization: Wikipedia entry

2008-01-29 Thread Roy Smith
In article [EMAIL PROTECTED],
 Terry Reedy [EMAIL PROTECTED] wrote:

 Roy Smith [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 | But, surely Python has plenty of implementation defined aspects.
 | Especially in the libraries.
 
 I personally do not consider the libraries as part of the language (as 
 opposed to the distribution) and was not referring to them.

I realize that there is a difference between the core language and the 
libraries, but Python depends on the libraries more than a lot of other 
languages do.  They are the batteries included part.

Indeed, there is a lot of stuff in the Python Library Reference which in 
most languages would be considered part of the core.  The description of 
boolean operations (and, or, not), for example.  String, sequence, and 
dictionary methods.  Where do you draw the line and say, The core language 
ends here; the rest is just libraries?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Terse Syntax through External Methods

2008-01-29 Thread Jens
On Jan 25, 3:19 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 Jens schrieb:



  Hello Everyone

  I'm newbie to Zope and i have a few questions regarding external
  methods. What i wan't to do
  is provide a terse syntax for converting  urls to special tracking
  urls:

  dtml-var track('http://myurl/')

  turns the provided url into something like

 http://host/tracking?url=http%3A%2F%2Fmyurl%2F

  in the output.

  i've been trying to use a external procedure like this.

  ## Script (Python) track_link
  ##bind container=container
  ##bind context=context
  ##bind namespace=_
  ##bind script=script
  ##bind subpath=traverse_subpath
  ##parameters=self,url
  ##title=track link
  ##
  return %s%s % (self.tracking_prefix, url_quote(url))

  This doesn't work because because the method doesn't have access to
  the environment. Obviously I don't wan't to pass everything explicitly
  into the function as this would defeat the purpose of the exercise,
  namely to provide a terse syntax.

  I have a background in other languages so I might be missing something
  conceptually with regard Zope and DTML.. Is there a better was of
  doing this, perhaps without using external methods? Currently im doing
  the following which isn't very elegant:

  in content document
  a href=dtml-let exturl='http://www.mylink.com/;dtml-var
  tracking/dtml-letlink/a
  ...
  tracking:
  dtml-var tracking_prefixdtml-var name=exturl url_quote_plus

  Appreciate any input you might have on this-

 Is it really needed to use an external method for this, or isn't a
 normal python script enough already?

 If it has to be an External method, you can't access such a context
 AFAIK. But then you can create a python script that _has_ this context,
 and passese it to the external method. Not the nicest solution, but
 should work.

 Diez

Like I said i'm a newbie. I though the deal with Zope was that i
couldn't really do inline scripting (for security reasons)
like in php but had to use these external methods. how does one go
about creating a normal python script exactly and
how do I invoke it's functionality?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [HELP] SMTPlib not sending my mail

2008-01-29 Thread ashok raavi
i  checked it after your mail..

it is giving the following warning: no entropy for TLS key generation:
disabling TLS support

which was addressed here 
http://www.howtoforge.com/forums/showthread.php?t=781;

after adding the line tlsmgr unix - - n 1000? 1 tlsmgr  to
/etc/postfix/master.cf it started working.

Thank you.


On 1/29/08, Lars Johansen [EMAIL PROTECTED] wrote:

 have you checked your mail server logs ?

 tir, 29.01.2008 kl. 00.24 -0800, skrev ashok.raavi:
  Hi,
 
  I am also facing the same problem, smtplib used to send mail a while
  back but it stopped sending mails.
 
  when i run this in interpreter
   import smtplib
   s = smtplib.SMTP(localhost)
   s.sendmail(from, to, message)
  {}
  
 
  though it is not giving any error, it is not sending mail.
 
  Any help is appreciated.
 
  ornto wrote:
   Hi, I'm trying to create an application which checks a
   dynamic web site and on certain events sends an email to me.
   My problem though is with the email task. By now I made this
 simple test code:
  
   #prova invio email
   smtpserver = smtplib.SMTP(mailserver)
   messaggio= Messaggio di prova
   print mail
   print messaggio
   smtpresult=smtpserver.sendmail(Watcher,mail,messaggio)
   if smtpresult:
print smtpresult
   smtpserver.quit()
  
   mailserver and mail values are loaded from a ini file
   and they're correct.
   The call to smtpserver gives back no errors (smtpresult
   remains empty).
   The running enviroment gives no error.
   So, it looks like that the program works alloright, sending
   the mail- BUT, I receive no mail! I've tried to change the
   smtp server with another one which still works with my isp,
   with no luck. If I try a smtp which doesn't give me access,
   I correctly receive an error from the program.
   What might be the problem?




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

Extending the import mechanism - what is recommended?

2008-01-29 Thread dbr517
I need to extend the import mechanism to support another file type.
I've already written the necessary C library to read the file and
return a python code object.

I found one example which just sub-classed imputil.ImportManager like
this:

from myLib import pye_code as pye_code
class MyImporter(imputil.ImportManager):
def __init__(self):
imputil.ImportManager.__init__(self)
self.add_suffix('.pye', self.import_pye)
self.install()

def import_pye(self, filepath, fileinfo, filename):
data = pye_code(filepath)
return 0, data, {}

This actually works fine if the module is just a few lines of code,
but it won't chain to the built-in importers; if the module that I'm
importing does something as simple as 'import re', it fails.

It may be that my confusion here is because (even after reading the
code), I'm not clear on the purposes of imputil.ImportManager vs.
imputil.Importer :-(

What is the preferred way to do this type of extension?  One other
note; at this time, I just need to import individual module files with
this extension; I don't need to import packages.

Thanks!

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


Re: extending Python - passing nested lists

2008-01-29 Thread Arnaud Delobelle
On Jan 29, 12:48 pm, Christian Meesters [EMAIL PROTECTED] wrote:
 Think, that I'm still at the wrong track. Point is that I cannot find any
 examples and don't know where to start here.
 Perhaps my problem boils down to two questions:
 I'd like to pass lists (in some cases nested ones) from Python to C and
 convert those Python-lists to C-arrays (e. g. of doubles). My second wish
 is to return a C-array of longs to a Python list.

 My approach so far:

 static PyObject *_foo(PyObject *self, PyObject *args) {
   double *v;
   if (!PyArg_Parse(args, (d), v))
     return NULL;
   // then I can't access v like v[1] ...

I'm not a C API guru and I may not understand properly what info you
are looking for but from http://docs.python.org/api/sequence.html:

PyObject* PySequence_GetItem( PyObject *o, Py_ssize_t i)

Return value: New reference.
Return the ith element of o, or NULL on failure. This is the
equivalent of the Python expression o[i].


   snip
   // then return *v
   return with something like PyBuildValue (but didn't get so far)

This allows you to create a list (from 
http://docs.python.org/api/listObjects.html):

PyObject* PyList_New( Py_ssize_t len)

Return value: New reference.
Return a new list of length len on success, or NULL on failure. Note:
If length is greater than zero, the returned list object's items are
set to NULL. Thus you cannot use abstract API functions such as
PySequence_SetItem() or expose the object to Python code before
setting all items to a real object with PyList_SetItem().

...and this allows you to populate it (from 
http://docs.python.org/api/listObjects.html):

int PyList_Append( PyObject *list, PyObject *item)

Append the object item at the end of list list. Return 0 if
successful; return -1 and set an exception if unsuccessful. Analogous
to list.append(item).


 }

 Can somebody give me a hint here, please? Passing simple arguments to and
 fro (e. g. single integer values) is no problem, but lists of unknown size?

HTH

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


Re: Zipfile content reading via an iterator?

2008-01-29 Thread Tim Chase
 I'm dealing with several large items that have been zipped up to
 get quite impressive compression.  However, uncompressed, they're
 large enough to thrash my memory to swap and in general do bad
 performance-related things.  I'm trying to figure out how to
 produce a file-like iterator out of the contents of such an item.

 The Time Machine in action again - that's already done, but in SVN. You  
 want the new ZipFile.open(filename) method, which returns a file-like  
 object.
 
 Thanks!  I'll give the 2.6 version a try.

Just to follow up on this, I dropped the the 2.6 version of
zipfile.py in my project folder (where the machine is currently
running Python2.4), used the ZipFile.open() and it worked fine.
I was able to successfully extract a 960 meg MDB file from the
zip-file.  The one thing that did throw me off is that it
rejected specifying that the file be opened as binary:

  z = ZipFile('foo.zip')
  f = z.open('path/to/file.mdb', 'rb') #failed
  f = z.open('path/to/file.mdb') # worked

but just opening with no type specification did allow me to
extract the file successfully.  I don't know if I just struck it
lucky with newline/EOF translations, or if it really does do
binary file handling and you don't get a choice of non-binary
file handling.

Anyways, thanks to Gabriel (and all the authors of Python
zipfile.py library) for the solution.

-tkc

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


Re: Module/package hierarchy and its separation from file structure

2008-01-29 Thread Peter Schuller
 You can reassign the class's module:

 from org.lib.animal.monkey import Monkey
 Monkey.__module__ = 'org.lib.animal'


 (Which, I must admit, is not a bad idea in some cases.)

Is there a sense whether this is truly a supported way of doing this,
in terms of not running into various unintended side-effects? One
example would be sys.modules that I mentioned in the previous
post. Another, possibly related, might be interaction with the import
keyword and its implementation.

I will probably have to read up more on the semantics of __import__
and related machinery.

-- 
/ Peter Schuller

PGP userID: 0xE9758B7D or 'Peter Schuller [EMAIL PROTECTED]'
Key retrieval: Send an E-Mail to [EMAIL PROTECTED]
E-Mail: [EMAIL PROTECTED] Web: http://www.scode.org

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


Re: extending Python - passing nested lists

2008-01-29 Thread Christian Meesters
Think, that I'm still at the wrong track. Point is that I cannot find any
examples and don't know where to start here.
Perhaps my problem boils down to two questions:
I'd like to pass lists (in some cases nested ones) from Python to C and
convert those Python-lists to C-arrays (e. g. of doubles). My second wish
is to return a C-array of longs to a Python list.

My approach so far:

static PyObject *_foo(PyObject *self, PyObject *args) {
  double *v;
  if (!PyArg_Parse(args, (d), v))
return NULL;
  // then I can't access v like v[1] ...
  snip
  // then return *v
  return with something like PyBuildValue (but didn't get so far)
}

Can somebody give me a hint here, please? Passing simple arguments to and
fro (e. g. single integer values) is no problem, but lists of unknown size?

TIA
Christian

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


Re: REALLY simple xml reader

2008-01-29 Thread Ricardo Aráoz
Diez B. Roggisch wrote:
 Simon Pickles schrieb:
 Hi

 Can anyone suggest a really simple XML reader for python? I just want to 
 be able to do something like this:

 xmlDoc = xml.open(file.xml)
 element = xmlDoc.GetElement(foo/bar)

 ... to read the value of:

 foo
   bar42/bar
 /foo
 
 Since python2.5, the ElementTree module is available in the standard 
 lib. Before 2.5, you can of course install it.
 
 Your code then would look like this:
 
 import xml.etree.ElementTree  as et
 
 
 doc = 
 foo
bar42/bar
 /foo
 
 
 root = et.fromstring(doc)
 
 for bar in root.findall(bar):
  print bar.text
 
 
 
 Diez
 

What about :

doc = 
moo
   bar99/bar
/moo
foo
   bar42/bar
/foo



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


Re: Just for fun: Countdown numbers game solver

2008-01-29 Thread Arnaud Delobelle
On Jan 29, 9:02 am, [EMAIL PROTECTED] wrote:

Oops I sent too quickly...

 If you've found an efficient way to walk through the possible
 solutions only once, then
 -  I expect that yours will be faster
 -  and well done!

 I guess I should try to understand your code...

My code is quite naive and I suspect that combining your caching and
the tree pruning discussed in this thread would yield faster results.
Not sure if I'll have time to try this though...

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


Re: Trying to understand Python web-development

2008-01-29 Thread Joe Riopel
On Jan 29, 2008 12:11 PM, walterbyrd [EMAIL PROTECTED] wrote:
 I am not really sure about what wsgi is supposed to accomplish.

This will explain WSGI: http://www.python.org/dev/peps/pep-0333/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removal of element from list while traversing causes the next element to be skipped

2008-01-29 Thread Santiago Romero
 Look at this -- from Python 2.5.1:

  a = [1, 2, 3, 4, 5]
  for x in a:
 ... if x == 3:
 ... a.remove(x)
 ... print x

 Well ... you could use:

 for i in range(len(a)-1, -1, -1):
...print a[i]
...if a[i] == 3: del a[i]
...
5
4
3
2
1
 print a
[1, 2, 4, 5]


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


Re: Trying to understand Python web-development

2008-01-29 Thread Bruno Desthuilliers
walterbyrd a écrit :
 I don't know much php either, but running a php app seems straight
 forward enough.

Mmm... As long as the whole system is already installed and connfigured, 
*and* matches your app's expectations, kind of, yes.

 Python seems to always use some sort of development environment vs
 production environment scheme.

s/Python/some frameworks/

 For development, you are supposed to
 run a local browser and load 127.0.0.1:5000 - or something like that.
 Then to run the same thing in a development environment,

I suppose you meant in a production environment ?

 I have to
 configure some files, or touch all the files, restart the web-server,
 or something. Why is that?

Developping directly on a production server is defiinitively a no-no, 
whatever the language. So you *always* develop un a development 
environment. In PHP, this imply having a running HTTP server - usually 
Apache - correctly configured. Some Python frameworks, OTHO, ship with 
their own lightweight Python-based http server, which usually makes 
things far easier. Since quite a lot of web programmers already have 
Apache running on port 80, the framework's own server usually runs (by 
default) on another port. Also, most of the time, on the production 
server, you choose some other more appropriate deployement solution - 
which may or not include Apache - depending on the context. So the nice 
point here is that:
1/ you have way more freedom wrt/ possible deployment solutions
2/ you don't have to replicate the whole damn thing (if ever possible) 
on your local machine to develop the app.

Of course, the actions to be taken when updating your app on the 
production server greatly depends on the deployment solution.

 Python also seems to require some sort of long running processes I
 guess that the python interpretor has to running all of time.

s/Python/some frameworks/

You can write web apps in Python using plain cgi, you know. It's just 
very inefficient due to how cgi works - to make a long story short: the 
system has to launch a new process for each request calling your script, 
and you have to rebuild the whole damn world each time your script is 
called. Note that PHP suffers at least from the second problem, which 
can make it somewhat inefficient for some kind of applications.

The point of long running processes is that most of the world is only 
built at startup and stays here between requests.

 I am not really sure about what wsgi is supposed to accomplish.

First and mainly, allow Python-based web apps to be independant from the 
deployment solution, by adding an indirection level. Instead of having

[yourapp]--[http_server]

which only work for the http server you targeted, you have

[yourapp]--[wsgi]--[http_server.wsgi_adapter]--[http_server]

which works for any http server for which a specific wsg adapter exists.

There are also some other benefits since, the way wsgi works, the [wsgi] 
part of the above schema can include quite a lot of other things, 
sometimes without your application being aware of it (you may want to 
look for 'wsgi middleware' for more on this).


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


Re: regular expression negate a word (not character)

2008-01-29 Thread Greg Bacon
In article [EMAIL PROTECTED],
Dr.Ruud [EMAIL PROTECTED] wrote:

: I negated the test, to make the regex simpler: [...]

Yes, your approach is simpler. I assumed from the need it all
in one pattern constraint that the OP is feeding the regular
expression to some other program that is looking for matches.

I dunno. Maybe it was the familiar compulsion with Perl to
attempt to cram everything into a single pattern.

Greg
-- 
What light is to the eyes -- what air is to the lungs -- what love is to
the heart, liberty is to the soul of man. 
-- Robert Green Ingersoll
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python noob SOS (any [former?] Perlheads out there?)

2008-01-29 Thread Bruno Desthuilliers
kj a écrit :
 For many months now I've been trying to learn Python, but I guess
 I'm too old a dog trying to learn new tricks...  For better or
 worse, I'm so used to Perl when it comes to scripting, that I'm
 just having a very hard time getting a hang of The Python Way.
 
(snip)
 
 I'd written a Perl module to facilitate the writing of scripts.
 It contained all my boilerplate code for parsing and validating
 command-line options, generating of accessor functions for these
 options, printing of the help message and of the full documentation,
 testing, etc.
 
 Of course, for Python now I don't have any of this, so I must write
 it all from scratch,

Hem... What about the optparse module ? (nb: it's in the standard lib).

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


Re: MySQLdb

2008-01-29 Thread Tim Chase
 i have problem manipulating mySQL data. When i add values in a Table,
 i can recieve them instantly but when i check the table from another
 script, the new values dont exist.

Depending on your transaction settings (both on your mysql
connection object in code, and the engine used for the table(s)
in mysql's DB), you may have to commit your transaction to make
it visible in other connections.  This helps prevent partial
transactions from being visible when they're in inconsistent states.

-tkc


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


Re: Problem with Tkinter scrollbar callback

2008-01-29 Thread Ivan Van Laningham
Nope:

'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', '300', '300'),

And even after I set it, it looks funny:

'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', '300', '1000'),

And when I try it with the new repeatdelay (1000), the only thing that
has changed is that it waits 1000 milliseconds before exhibiting the
same uncontrolled growth as before.

Metta,
Ivan

On Jan 25, 2008 5:49 PM, Russell E. Owen [EMAIL PROTECTED] wrote:
 In article [EMAIL PROTECTED],
  Ivan Van Laningham [EMAIL PROTECTED] wrote:

  Hi All--
  That helps.  Doing a get() on the scrollbar before a set(0.0,0.0)
  returns a 4-tuple:  (0.0, 0.0, 0.0, 0.0)  !  I did the set(0.0,0.0)
  and now the callback gets the correct number of arguments.
 
  However, I'm still getting the weird behaviour when clicking the
  arrowheads--and the heads are all I want.  They act like they've been
  set to a keybounce timeout of about a millisecond. ...  The arrow
  click increments the number of cells in a table row (effectively), and
  it shoots up from 5 to 26 columns almost instantly (that's the
  internal max I set).

 Is the scroll bar's repeatinterval set to a reasonable value?

 -- Russell

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




-- 
Ivan Van Laningham
God N Locomotive Works
http://www.pauahtun.org/
http://www.python.org/workshops/1998-11/proceedings/papers/laningham/laningham.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: REALLY simple xml reader

2008-01-29 Thread Stefan Behnel
Hi,

Ricardo Aráoz wrote:
 I don't know zit about xml, but I might need to, and I am saving the
 thread for when I need it. So I looked around and found some 'real'
 XML document (see below). The question is, how to access amounts from
 debits (any category) but not deposits.
 
 doc = 
 ?xml version=1.0?
 checkbook balance-start=2460.62
 titleexpenses: january 2002/title
 
   debit category=clothes
 amount31.19/amount
 dateyear2002/yearmonth1/monthday3/day/date
 paytoWalking Store/payto
 descriptionshoes/description
   /debit
 
   deposit category=salary
 amount1549.58/amount
 dateyear2002/yearmonth1/monthday7/day/date
 payorBob's Bolts/payor
   /deposit
[...]
 /checkbook
 

Sure, no problem. Just use the XPath expression //debit/amount, or maybe
/checkbook/credit/amount, if you prefer. This is basically tree traversal,
so you can check the parents and the children as you see fit.

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


Re: extending Python - passing nested lists

2008-01-29 Thread Arnaud Delobelle
On Jan 29, 1:22 pm, Christian Meesters [EMAIL PROTECTED] wrote:
 Thanks. Point is that all such approaches would require lots(!) of calls to
 the Python API - a way by which I won't gain the desired speed.

You didn't mention speed in your original post.  What about using
array.array?  Unless I am mistaken, these are just a thin wrapper
around normal C arrays.  Anyway you could always convert your list
into a c array, do lots and lots of fast calculations, then convert it
back again to a list.

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


Re: Problem with Tkinter scrollbar callback

2008-01-29 Thread Ivan Van Laningham
No Joy.

Waits the 1 second, then clicks the button once per second until the
limit's reached.

Sigh.

Metta,
Ivan

On Jan 29, 2008 10:20 AM, Russell E Owen [EMAIL PROTECTED] wrote:
 Nope:
 
 'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', '300', '300'),
 
 And even after I set it, it looks funny:
 
 'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', '300', '1000'),
 
 And when I try it with the new repeatdelay (1000), the only thing that
 has changed is that it waits 1000 milliseconds before exhibiting the
 same uncontrolled growth as before.

 You need to change repeatinterval, not repeatdelay.

 As to looking funny: that is the standard output format for
 configure(). I think can get a more reasonable value using
 cget(repeatdelay).

 -- Russell


 
 Metta,
 Ivan
 
 On Jan 25, 2008 5:49 PM, Russell E. Owen [EMAIL PROTECTED] wrote:
   In article [EMAIL PROTECTED],
Ivan Van Laningham [EMAIL PROTECTED] wrote:
 
Hi All--
That helps.  Doing a get() on the scrollbar before a set(0.0,0.0)
returns a 4-tuple:  (0.0, 0.0, 0.0, 0.0)  !  I did the set(0.0,0.0)
and now the callback gets the correct number of arguments.
   
However, I'm still getting the weird behaviour when clicking the
arrowheads--and the heads are all I want.  They act like they've been
set to a keybounce timeout of about a millisecond. ...  The arrow
click increments the number of cells in a table row (effectively), and
it shoots up from 5 to 26 columns almost instantly (that's the
internal max I set).
 
   Is the scroll bar's repeatinterval set to a reasonable value?
 
   -- Russell
 
   --
   http://mail.python.org/mailman/listinfo/python-list
 
 
 
 
 --
 Ivan Van Laningham
 God N Locomotive Works
 http://www.pauahtun.org/
 http://www.python.org/workshops/1998-11/proceedings/papers/laningham/laningham.html
 Army Signal Corps:  Cu Chi, Class of '70
 Author:  Teach Yourself Python in 24 Hours





-- 
Ivan Van Laningham
God N Locomotive Works
http://www.pauahtun.org/
http://www.python.org/workshops/1998-11/proceedings/papers/laningham/laningham.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removal of element from list while traversing causes the next element to be skipped

2008-01-29 Thread Berteun Damman
On Tue, 29 Jan 2008 09:23:16 -0800 (PST), [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 If you're going to delete elements from
 a list while iterating over it, then do
 it in reverse order:

Why so hard? Reversing it that way creates a copy, so you might as
well do:
 a = [ 98, 99, 100 ]
 for i, x in enumerate(a[:]):
 ... if x == 99: del(a[i])
 ... print x

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


Re: refcount

2008-01-29 Thread Christian Heimes
Simon Pickles wrote:
 Hi,
 
 Is is possible to access the refcount for an object?
 
 Ideally, I am looking to see if I have a refcount of 1 before calling del

Help on built-in function getrefcount in module sys:

getrefcount(...)
getrefcount(object) - integer

Return the reference count of object.  The count returned is generally
one higher than you might expect, because it includes the (temporary)
reference as an argument to getrefcount().

Christian

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


Re: Python noob SOS (any [former?] Perlheads out there?)

2008-01-29 Thread Paddy
On Jan 29, 4:39 pm, kj [EMAIL PROTECTED] wrote:

 It's not the Python syntax that I'm having problems with, but rather
 with larger scale issues such as the structuring of packages,
 techniques for code reuse, test suites, the structure of
 distributions,...  Python and Perl seem to come from different
 galaxies altogether...

Maybe if someone could point Kynn at a suitable project where he could
look at the complete repository and see how its successfully done?
It would need I guess to employ:
  * Setuptools
  * modules/package(s)
  * Doctest/unit tests
And not be too large I guess. Anyone wish to put forward their
project?

- Paddy.


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


Re: Python noob SOS (any [former?] Perlheads out there?)

2008-01-29 Thread Rick Dooling
On Jan 29, 10:39 am, kj [EMAIL PROTECTED] wrote:

 I'd written a Perl module to facilitate the writing of scripts.
 It contained all my boilerplate code for parsing and validating
 command-line options, generating of accessor functions for these
 options, printing of the help message and of the full documentation,
 testing, etc.

http://docs.python.org/lib/optparse-tutorial.html

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


Re: Just for fun: Countdown numbers game solver

2008-01-29 Thread Arnaud Delobelle
On Jan 29, 9:02 am, [EMAIL PROTECTED] wrote:
 If you've found an efficient way to walk through the possible
 solutions only once

As discussed earlier in this thread, the definition of 'only once' is
not as clear cut as one would first think (see Terry's thoughts on
this).

--
Arnaud

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


Implementation of IBuyable or Interface?

2008-01-29 Thread Marcelo de Moraes Serpa
Hello!

It's more a design question than anything python specific. If anyone could
help me, I would be grateful. If it's not the right place for this subject,
please advise.

I've got a IBuyable interface. The app can sell both Products and Services
(Both Buyables). I'm not sure if Product and Service should also be
represented as interfaces (inherited from IBuyable) or if they are actually
directly implementations of IBuyable.

What do you think?

Thanks,

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

Re: Error in parsing XML for following test data

2008-01-29 Thread Paul McGuire
On Jan 29, 4:46 am, Stefan Behnel [EMAIL PROTECTED] wrote:

 How is this related to XML?

 Stefan

I guess that's what makes so **nasty**!

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


Re: Module/package hierarchy and its separation from file structure

2008-01-29 Thread Peter Schuller
 You can also put, in animal/__init__.py:
  from monkey import Monkey
 and now you can refer to it as org.lib.animal.Monkey, but keep the  
 implementation of Monkey class and all related stuff into  
 .../animal/monkey.py

The problem is that we are now back to the identity problem. The class
won't actually *BE* org.lib.animal.Monkey. Perhaps manipulating
__module__ is enough; perhaps not (for example, what about
sys.modules?). Looks like I'll just live with putting more than I
would like in the same file.

-- 
/ Peter Schuller

PGP userID: 0xE9758B7D or 'Peter Schuller [EMAIL PROTECTED]'
Key retrieval: Send an E-Mail to [EMAIL PROTECTED]
E-Mail: [EMAIL PROTECTED] Web: http://www.scode.org

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


Re: Executing other python code

2008-01-29 Thread Arnaud Delobelle
On Jan 29, 12:18 am, Tim Rau [EMAIL PROTECTED] wrote:
 I'm working on a game, and I'd like players to be able to define thier
 ships with scripts. Naturally, I don't want to give them the entire
 program as thier romping ground. I would like to invoke a seperate
 interpreter for these files, and give it a limited subset of the
 functions in my game. What is the best way to achieve this effect?

One simple solution would be to forbid import statements in the
scripts, to import the scripts as modules and inject whatever
functions you want them to be able to use in the module's namespace.

So:

== script.py ===

def play():
if enemy_is_near():
fire_gun()
else:
move_forward()

===

== Game engine 

scriptobjs = [enemy_is_near, fire_gun, move_forward, turn_left,
turn_right]

def getscript(scriptname):
script = __import__(scriptname)
for obj in scriptobjs:
setattr(script, obj.__name__, obj)
return script

def playscript(script):
script.play()

===

Something like this.  Obviously this is over simplified!

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


Re: REALLY simple xml reader

2008-01-29 Thread Ricardo Aráoz
 What about :

 doc = 
 moo
bar99/bar
 /moo
 foo
bar42/bar
 /foo
 

That's not an XML document, so what about it?

Stefan

--

Ok Stefan, I will pretend it was meant in good will.

I don't know zit about xml, but I might need to, and I am saving the
thread for when I need it. So I looked around and found some 'real'
XML document (see below). The question is, how to access amounts from
debits (any category) but not deposits.
Probably my previous example was not properly stated, what I meant to
convey is two substructures (namespaces, or whatever you call them in
XML) which have the same 'properties' moobar is not the same as
foobar as debitamount is not the same as depositamount.
The examples given by Diez and Mark, though useful, don't seem to
address the problem.
Thanks for your help.


doc = 
?xml version=1.0?
checkbook balance-start=2460.62
titleexpenses: january 2002/title

  debit category=clothes
amount31.19/amount
dateyear2002/yearmonth1/monthday3/day/date
paytoWalking Store/payto
descriptionshoes/description
  /debit

  deposit category=salary
amount1549.58/amount
dateyear2002/yearmonth1/monthday7/day/date
payorBob's Bolts/payor
  /deposit

  debit category=withdrawal
amount40/amount
dateyear2002/yearmonth1/monthday8/day/date
descriptionpocket money/description
  /debit

  debit category=savings
amount25/amount
dateyear2002/yearmonth1/monthday8/day/date
  /debit

  debit category=medical check=855
amount188.20/amount
dateyear2002/yearmonth1/monthday8/day/date
paytoBoston Endodontics/payto
descriptioncavity/description
  /debit

  debit category=supplies
amount10.58/amount
dateyear2002/yearmonth1/monthday10/day/date
paytoExxon Saugus/payto
descriptiongasoline/description
  /debit

  debit category=car
amount909.56/amount
dateyear2002/yearmonth1/monthday14/day/date
paytoHonda North/payto
descriptioncar repairs/description
  /debit

  debit category=food
amount24.30/amount
dateyear2002/yearmonth1/monthday15/day/date
paytoJohnny Rockets/payto
descriptionlunch/description
  /debit
/checkbook


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


Re: Executing other python code

2008-01-29 Thread Stefan Behnel
Hi,

Tim Rau wrote:
 I'm working on a game, and I'd like players to be able to define thier
 ships with scripts. Naturally, I don't want to give them the entire
 program as thier romping ground. I would like to invoke a seperate
 interpreter for these files, and give it a limited subset of the
 functions in my game. What is the best way to achieve this effect?

Depends. If you are concerned about security, this will be hard to achieve in
Python. I imagine that this could be related to cheating prevention.

If you are more concerned about namespace polution and making only a well
defined API available to the scripts, go the module-import way and hand some
API object over, either through an initialisation function or by injecting it
into the module namespace, as Arnaud suggested.

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


Re: Intra-package References?? (again)

2008-01-29 Thread Ron Adam


[EMAIL PROTECTED] wrote:
 Hi Python list,
 
 I have been struggleling with this before, but have never been able to
 find a good solution.
 The thing I dont understand is, I follow the guide here:
 http://docs.python.org/tut/node8.html#SECTION00842
 And have the same setup as the packages howto here:http://
 docs.python.org/tut/node8.html#SECTION00840
 
 But when I want to use Intra-package References, I need to put the
 path to the packages explicit like this:
 #sys.path.append('/path/to/pack/')
 Before I can make import like this:
 #from Sound.Effects import echo
 from within the karaoke.py (just to stay with the tut)
 If I print the sys.path from the same file, I can see that
 #/path/to/pack/Sound/Filters/
 is in the path.
 
 Is there something that I completely is missing or could someone
 please show me how, by example, how I use Intra-package References.
 
 Best regards
 
 Marc

If your package is in pythons path, all it should need is an empty 
__init__.py file in the package and also in the sub package Filters also.


If your program is a stand alone program that may be installed someplace 
not in pythons sys.path, then I've been using a some what different model. 
  I'm not sure what others think of it yet, but it's working well for me.

[karoki_program_dir]   (may not be in pythons sys.path)
karoki.py
[lib]
[tests]
__init__.py
(unit tests here)
[filters]
__init__.py
(various filters here)
(other local modules/packages here)

And in karoki.py add the local lib directory to the front of sys.path 
before your local module imports.

  lib = os.path.abspath(os.path.join(__file__, '..', 'lib'))
  sys.path.insert(0, lib)


This also makes sure it's the program location path, and not the current 
console directory.


For running tests, I use a command line option.

 python karoki.py --test


Cheers,
Ron









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


Re: extending Python - passing nested lists

2008-01-29 Thread Mel
Christian Meesters wrote:
 You didn't mention speed in your original post.
 Sorry, perhaps I considered this self-evident - which it is, of course, not.
 
 What about using 
 array.array?  Unless I am mistaken, these are just a thin wrapper
 around normal C arrays.
 The algorithm I want to implement requires several million floating point
 operations. Neither the array-modules nor numpy's thin layer seem thin
 enough for me. ;-)
 
 Anyway you could always convert your list 
 into a c array, do lots and lots of fast calculations, then convert it
 back again to a list.
 I guess I am too blind to see, but I couldn't discover a method description
 like double* PyList_toDouble. So, yes, my question is a C-API-newbie
 question: What is the way to say myCarray = SomePyMethod(InputPyList)? Or
 better, what should be here instead
 static PyObject *_foo(PyObject *self, PyObject *args) {
   double *v;
   if (!PyArg_Parse(args, (d), v))
 return NULL;
 to get a list as an array of doubles into 'v' (and back to Python)?
 
 I did read the API-description, but still am lost at this point. I presume,
 once I get to know the answer I'll bang my head on the table ... ;-)

I haven't strictly tried this, but PyArg_ParseTuple and Py_BuildValue 
seem to be the orthodox ways to do Python-C and C-Python conversions.
But if Numpy isn't fast enough, then any Python at all in the solution 
might be too much.  Perhaps keeping your values in a file and reading 
them into the C programs will work.

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


Removal of element from list while traversing causes the next element to be skipped

2008-01-29 Thread William McBrine
Look at this -- from Python 2.5.1:

 a = [1, 2, 3, 4, 5]
 for x in a:
... if x == 3:
... a.remove(x)
... print x
... 
1
2
3
5
 a
[1, 2, 4, 5]


Sure, the resulting list is correct. But 4 is never printed during the 
loop!

What I was really trying to do was this:

apps = [name for name in os.listdir(ROOT) if 
os.path.isdir(os.path.join(ROOT, name))]

apptitles = {}

for name in apps:
try:
app = __import__(name)
except:
apps.remove(name)
else:
apptitles[name] = getattr(app, 'TITLE', name.title())

which worked fine, until I actually had a directory with no module in it. 
Then that directory was correctly removed from the list, but the _next_ 
one was skipped, so its title was never assigned, which caused problems 
later in the program.

-- 
09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on
-- 
http://mail.python.org/mailman/listinfo/python-list


Python noob SOS (any [former?] Perlheads out there?)

2008-01-29 Thread kj


For many months now I've been trying to learn Python, but I guess
I'm too old a dog trying to learn new tricks...  For better or
worse, I'm so used to Perl when it comes to scripting, that I'm
just having a very hard time getting a hang of The Python Way.

It's not the Python syntax that I'm having problems with, but rather
with larger scale issues such as the structuring of packages,
techniques for code reuse, test suites, the structure of
distributions,...  Python and Perl seem to come from different
galaxies altogether...

Be that as it may, the activation barrier to using Python for my
scripting remains too high.

I'd written a Perl module to facilitate the writing of scripts.
It contained all my boilerplate code for parsing and validating
command-line options, generating of accessor functions for these
options, printing of the help message and of the full documentation,
testing, etc.

Of course, for Python now I don't have any of this, so I must write
it all from scratch, and the thing is *I don't even know where to
begin*!  And meanwhile works needs to get done, projects finished,
etc.  So naturally I revert to Perl, yadda-yadda-yadda, and the
Python project gets pushed back another week...

In a way it's the usual story with learning a new language, but
I've taught myself new languages before.  (After all, there was a
time when I didn't know Perl.)  It's harder this time, somehow...

Anyway, pardon the ramble.

Is there any good reading (to ease the transition) for Perl
programmers trying to learn Python?

Thanks!

kynn

-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removal of element from list while traversing causes the next element to be skipped

2008-01-29 Thread imageguy
On Jan 29, 12:34 pm, William McBrine [EMAIL PROTECTED] wrote:
 Look at this -- from Python 2.5.1:

  a = [1, 2, 3, 4, 5]
  for x in a:

 ...     if x == 3:
 ...         a.remove(x)
 ...     print x
 ...
 1
 2
 3
 5

  a
 [1, 2, 4, 5]

 Sure, the resulting list is correct. But 4 is never printed during the
 loop!

 What I was really trying to do was this:

 apps = [name for name in os.listdir(ROOT) if
         os.path.isdir(os.path.join(ROOT, name))]

 apptitles = {}

 for name in apps:
     try:
         app = __import__(name)
     except:
         apps.remove(name)
     else:
         apptitles[name] = getattr(app, 'TITLE', name.title())

 which worked fine, until I actually had a directory with no module in it.
 Then that directory was correctly removed from the list, but the _next_
 one was skipped, so its title was never assigned, which caused problems
 later in the program.

 --
 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on

You should not change/modify the original sequence iterating over.
In the list comprehension, try changing os.listdir(ROOT) to
os.listdir(ROOT)[:] so you are get a copy of the original list.

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


Trying to understand Python web-development

2008-01-29 Thread walterbyrd
I don't know much php either, but running a php app seems straight
forward enough.

Python seems to always use some sort of development environment vs
production environment scheme. For development, you are supposed to
run a local browser and load 127.0.0.1:5000 - or something like that.
Then to run the same thing in a development environment, I have to
configure some files, or touch all the files, restart the web-server,
or something. Why is that?

Python also seems to require some sort of long running processes I
guess that the python interpretor has to running all of time.

I am not really sure about what wsgi is supposed to accomplish.
-- 
http://mail.python.org/mailman/listinfo/python-list


Telnet Program

2008-01-29 Thread [EMAIL PROTECTED]
I am having some issues writing a telnet program, using telnetlib. I
am not sure if it is the telnet on the connections end or it is my
program.

A little background, when I log in straight from the Linux Command
prompt. The only thing I get is a blinking cursor. Then I type in my
command 'FOO' enter then screen on the very next line returns 'OK',
Then automatically puts the blinking cursor on the next line. Then
when I want to quit the telnet session I hit CTRL+Z that takes me to
telnet then i type quit.

My Program currently looks like it connects. Because the last string
that I get back that is not blank says: Logged in successfully.

So my problem is that when I issue the command through tn.write(FOO
\n). Then do a tn.read_until('OK\n', 10). It gets returned nothing. I
have also added tn.read_until('OK\n', 10).splitlines(). That is also
returned blank.

I have tried various different newlines \n \r \r\n. All the
documentation for telnet program that I am logging into says, use
Carriage Return after each command. Nothing seems to get back the
data. I am not sure if the Python telnet is looking for more of true
command line like telnet.

Any help would be great.
Thank You Very Much,
Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: object vs class oriented -- xotcl

2008-01-29 Thread William Pursell
On Jan 24, 9:16 pm, Guilherme Polo [EMAIL PROTECTED] wrote:
 2008/1/24, William Pursell [EMAIL PROTECTED]:
  referring to changing an objects class
  Can I do it in Python?


 class A(object): pass
 class B(object): pass

 a = A()
 a.__class__ = B

 That ? Maybe you meant something else.

That is what I was referring to, but it isn't the core
functionality that I'm after.  (My bad for a poor
description.)

I'm fairly excited at the idea of being able to
do per-object mixins in xotcl.  I guess it would
look like this in python:

BROKEN CODE:
a = object()
a.__class__.append( foo )
a.__class__.append( bar )

In python, if you want an object to me a member
of 2 classes, it seems that you have no choice but
to declare a new class that inherits from both.  eg:

class foobar( foo, bar):
  pass
a = foobar()

Is it possible to make an object be a member
of 2 classes without defining such a class?  I
believe per object mixin is the correct
term for such an animal.  The first several google
hits on that phrase all reference xotcl, so I'm
not sure if that is an xotcl inspired vocabulary
that isn't really standard.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ISO with timezone

2008-01-29 Thread nik
On Jan 29, 10:56 am, nik [EMAIL PROTECTED] wrote:
 Thanks,
 that does help and now I have:

  from datetime import datetime, tzinfo, timedelta
  import time
  class TZ(tzinfo):

 ...def utcoffset(self,dt): return timedelta(seconds=time.timezone)
 ... print datetime(2008,2,29,15,30,11,tzinfo=TZ()).isoformat()

 2008-02-29T15:30:11+8:00

 But what I want to know now it how to get the actual time into the
 expression instead of typing the 2008,2,29,15
 So something like:  print
 datetime(time.gmtime(),tzinfo=TZ()).isoformat(), but that doesn't
 work.

 I realize that I could do:

  t = time.localtime()
  print datetime(t[0],t[1],t[2],t[3],t[4],t[5],tzinfo=TZ()).isoformat()

 but I imagine there might be a cleaner way of doing this.

 Thanks,
 Nik

 On Jan 28, 9:10 pm, Nicholas F. Fabry [EMAIL PROTECTED]
 wrote:

  Hello, nik.

  On Jan 28, 2008, at 21:03, nik wrote:

   Hi,

   How does one express the time in ISO format with the timezone
   designator?

   what I want is -MM-DDThh:mm:ss.sTZD

   From the documentation I see:
   from datetime import tzinfo, timedelta, datetime
   class TZ(tzinfo):
   ... def utcoffset(self, dt): return timedelta(minutes=-399)
   ...
   datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
   '2002-12-25 00:00:00-06:39'

   and I've also figured out:
   datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3]
   '2008-01-23T11:22:54.130'

   But can't figure out how to fit them together.

  There is nothing there to 'fit together' - in the first example given,
  the datetime object has no time component specified, so it fills in
  default vaules of zero.  The following should make this clear:

your_time = datetime(2008, 2, 29, 15, 30, 11, tzinfo=TZ())
print your_time
  2008-02-29 15:30:11-05:00
print your_time.isoformat('T')
  2008-02-29T15:30:11-05:00

  If you wish to append the NAME of the tzinfo object instead of its
  offset, that requires a bit more playing around (along with a properly
  defined tzinfo object - check out dateutil or pytz for a concrete
  implementation of tzinfo subclasses (i.e. timezones)), but the
  following would work:

print your_time.strftime('%Y-%m-%dT%H:%M:%S %Z')
  2008-02-29T15:30:11 EST

  For details on how the .strftime method works, see Python Standard
  Library, Section 14.2.

  I hope this helps!

  Nick Fabry

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

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


Re: noob stuck on reading double

2008-01-29 Thread Joe Riopel
On Jan 29, 2008 1:35 PM, Hannah Drayson [EMAIL PROTECTED] wrote:
 It imports as a string of rubbish...
 i.e.

 open file 'data.bin', mode 'rb' at 0x5a2a8
  text = f.read()
  print text
 ?F?C??y???
 @[EMAIL PROTECTED]@???/???8[EMAIL PROTECTED]/[EMAIL 
 PROTECTED]@?Q???Q???Q???Q???Q??ǑR[???Q???
  unpack('d', text)
 Traceback (most recent call last):
   File stdin, line 1, in module
   File 
 /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/struct.py,
  line 87, in unpack
 return o.unpack(s)
 struct.error: unpack requires a string argument of length 8

When reading the file, try using
file = open('data.bin', 'rb')
file.seek(0)
raw = file.read()

Do the unpack on raw.
-- 
http://mail.python.org/mailman/listinfo/python-list

typename

2008-01-29 Thread Neal Becker
I want python code that given an instance of a type, prints the type name,
like:

typename (0) - 'int'

I know how to do this with the C-api, (o-tp_name), but how do I do it from
python?

type(0) prints type 'int', not really what I wanted.

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


Re: Error in parsing XML for following test data

2008-01-29 Thread John Machin
On Jan 29, 9:29 pm, abhishek [EMAIL PROTECTED] wrote:
 Hello group,

 I am having problem parsing following data set from XML. Please
 provide hints on how to rectify this problem.

You have provided no hints on what your problem is. What output do you
want? What have you tried? What output and/or error message(s) did you
get? What does from XML mean?


 I am using python2.4 version

 this is te test data that i am using --

 
 1!!!11
 2@@@22
[snip]
 33.
 Special Characters
 #!/bin/bash
 #start TG app
 cd $1
 exec ./start-infopsyM.py

 

 This is really a nasty data set.

It looks like
(a) easily parseable but totally uninteresting guff
followed by
(b) the start of a bash script

Is this some kind of joke? You are not trying to disassemble it, are
you?

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


Decision (if, else) routine is not working as intended with CGI module

2008-01-29 Thread epsilon
All:

I'm running into trouble figuring this one out.  It seems that my
decision routine is not working as intended.  Does anyone know why my
output continues to utilize the else portion of the routine.

Thank you,
Christopher

++

#!/usr/bin/python

import cgi

print Content-type: text/plain\n
tag_form = cgi.FieldStorage(keep_blank_values=True)

#if not tag_form.has_key(fse00):
if tag_form[fse00] == :
fse000 = {fse00: 0}
tag_form.update(fse000)
print Printing fse000: , tag_form[fse00]
else:
print Printing fse00: , tag_form[fse00]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: breaking out of outer loops

2008-01-29 Thread pataphor
On Tue, 29 Jan 2008 11:51:04 -0800 (PST)
[EMAIL PROTECTED] wrote:

 Any elegant way of breaking out of the outer for loop than below, I
 seem to have come across something, but it escapes me
 
 for i in outerLoop:
for j in innerLoop:
if condition:
   break
else:
continue
 break

Ha! Think outside the box to begin with ...

P.

def cross(args):
ans = [[]]
for arg in args:
ans = [x+[y] for x in ans for y in arg]
return ans

def test():
L = [[0,1,2]]*3
for a,b,c in cross(L):
print a,b,c

if __name__=='__main__':
test()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Help! - Invoke setup.py file

2008-01-29 Thread Gabriel Genellina
En Mon, 21 Jan 2008 07:38:15 -0200, Vikas Jadhav [EMAIL PROTECTED]  
escribi�:

 We have setup of SVGMath* 0.3.2 (Converter- Mathml 2.0 coding to SVG).  
 The
 setup folder contains setup.py file but we are not able to initiate this
 file. Kindly help us, resolution to this query will be appreciated.
 Python version: Installed on PC- 2.5.1 and OS- Windows 2000.

Unless the author provides more specific instructions to install the  
package, the usual way is:

- Unpack the archive in any temporary directory
- Open a console (CMD) and change to that temporary directory
- Execute this command:
   python setup.py install
- That's all

If you get any error, post the whole error message here, but for specific  
help on that package it would be better to contact the author directly.

-- 
Gabriel Genellina

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

Re: Reflection and aspect programming in Python

2008-01-29 Thread Gabriel Genellina
En Tue, 29 Jan 2008 14:42:55 -0200, Jean-François Houzard  
[EMAIL PROTECTED] escribi�:

 I'm a student at UCL Belgium and I have to write a paper about reflection
 and introspection in Python.

 It is somewhat difficult to find advanced information about reflection in
 Python, not only introspection but also the other sides of reflection.

I'm not familiar with what you mean by the other sides of reflection,  
perhaps you could explain what you mean exactly. But I'll try to give some  
examples of what can be made in Python:

Direct introspection: hasattr(obj, color) tells if obj has an attribute  
color. dir(obj) returns a list of obj's attributes.
Similarly, you can obtain an attribute by its name: getattr(obj, color)  
is a silly way of writing obj.color, but it's useful when color is  
replaced by a variable.
You can set an attribute: obj.width = 3, or setattr(obj, width, 3). You  
can add any attribute to any object - the set of attributes allowed for an  
individual object isn't defined by its class (in general).
Methods are attributes too, so all the above may be applied to testing,  
retrieving and setting methods too.
As classes usually live in modules, the above technique allows you to get  
a class given its name: cls=getattr(modulename, classname). And then  
create an instance: obj=cls(some,arguments)

You can query any object its type: type(obj). In some cases (including all  
user defined classes) you can change an object's class to another  
dynamically: obj.__class__ = NewClass, and it will behave as it were an  
instance of NewClass (but any missing attributes won't be created  
magically)
You can dynamically create new types/classes: if Bar and Baz are classes,  
type(Foo, (Bar, Baz), {}) returns a new class named Foo which inherits  
 from Bar and Baz. It's equivalent to this statement:
class Foo(Bar,Baz): pass

You can evaluate expressions at runtime: eval(2+2).  
eval(Foo(some,arguments)) returns an instance of Foo.
You can compile blocks of code into a code object, and execute them, using  
`compile` and `exec`.
Classes, its instances, functions, methods, code, execution frames,  
builtin types, all of them are first order objects in Python: you can  
create them, assign them to variables, pass them as arguments, query its  
properties, modify them when allowed, etc.

 I'm using the book: Programming Python, Thrid Edition but the chapter  
 only
 describes briefly some useful functions. The IBM site talks somewhat  
 about
 the concept of metaclass but is there more about reflection than only
 metaclass programming?
 I'm also looking for a class diagram of the hierachy of the python  
 classes
 metaclass, class, object but didn't find it nor did I find lots of
 information about that subject.

Read sections 3 (Data Model) and 4 (Execution Model) in the Python  
Language Reference.
The root of the class hierarchy is `object`; all other [new-style] classes  
inherit from object direct or indirectly.
metaclass is a generic name. Metaclasses are to classes as classes are  
to instances. The type of an instance is its class; the type of a class is  
its metaclass. I won't even try to explain metaclasses further here; see  
the links at http://www.python.org/doc/newstyle/
You may be interested in decorators too. Decorators allow for higher order  
functions: a decorator is a function which takes a function as a parameter  
and returns a (possibly different) function as a result.
http://wiki.python.org/moin/PythonDecorators

 I looked around on the site www.python.org and some others about what  
 could
 be a killer application using reflection in Python an maybe more  
 information
 about it. Like how does it use reflection to do the trick.

 Is there an advanced and completed Aspect Python plugin or are they all
 experimental?
 Are there some papers about that part of reflection or more detailed  
 sites
 that talks about it.

This thread from last year discusses why Aspect Programming isn't so  
relevant in Python
http://groups.google.com/group/comp.lang.python/browse_thread/thread/af82d7fa8fdf5a28/

-- 
Gabriel Genellina

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

Re: optional static typing for Python

2008-01-29 Thread Kay Schluehr
On 29 Jan., 17:00, Chris Mellon [EMAIL PROTECTED] wrote:

 Given the difficulty of statically analyzing Python, and the
 limitations you need to add for either static typing or type inference
 to be practical, I think that the real future for faster Python code
 is JIT, not static optimizations.

Python has a JIT right now - so why do you think it's Pythons real
future?

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


Re: Removal of element from list while traversing causes the next element to be skipped

2008-01-29 Thread Duncan Booth
Berteun Damman [EMAIL PROTECTED] wrote:

 On Tue, 29 Jan 2008 09:23:16 -0800 (PST), [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 If you're going to delete elements from
 a list while iterating over it, then do
 it in reverse order:
 
 Why so hard? Reversing it that way creates a copy, so you might as
 well do:
 a = [ 98, 99, 100 ]
 for i, x in enumerate(a[:]):
  ... if x == 99: del(a[i])
  ... print x

Why so hard?

 a = [ 98, 99, 100, 98, 99, 100 ]
 for i, x in enumerate(a[:]):
if x == 99: del(a[i])


 a
[98, 100, 98, 99]

oops! But:

 a = [ 98, 99, 100, 98, 99, 100 ]
 last_idx = len(a) - 1
 for i, x in enumerate(a[::-1]):
if x == 99: del(a[last_idx - i])


 a
[98, 100, 98, 100]

Reversing it works. Your code doesn't.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: runscript module, where are the docs...

2008-01-29 Thread Gabriel Genellina
En Tue, 29 Jan 2008 13:48:58 -0200, glomde [EMAIL PROTECTED] escribi�:

 I am going through some code and found
 import runscript

 BUT I cant find and information about this module. I searched Google
 did a grep in
 the /usr/lib/python directory.

 What is the purpose of this module and where can I find information
 about it. Or  the source.

It doesn't appear to be a standard module, look around the place where you  
found it.

-- 
Gabriel Genellina

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

Re: Zipfile content reading via an iterator?

2008-01-29 Thread Gabriel Genellina
En Tue, 29 Jan 2008 11:06:12 -0200, Tim Chase  
[EMAIL PROTECTED] escribi�:

 Just to follow up on this, I dropped the the 2.6 version of
 zipfile.py in my project folder (where the machine is currently
 running Python2.4), used the ZipFile.open() and it worked fine.
 [...]
 Anyways, thanks to Gabriel (and all the authors of Python
 zipfile.py library) for the solution.

I just bring attention to the upcoming feature. All credit should go to  
the patch author, Alan McIntyre.

-- 
Gabriel Genellina

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

Re: Module/package hierarchy and its separation from file structure

2008-01-29 Thread Robert Kern
Carl Banks wrote:
 On Jan 29, 7:48 am, Peter Schuller [EMAIL PROTECTED]
 wrote:
 You can also put, in animal/__init__.py:
  from monkey import Monkey
 and now you can refer to it as org.lib.animal.Monkey, but keep the
 implementation of Monkey class and all related stuff into
 .../animal/monkey.py
 The problem is that we are now back to the identity problem. The class
 won't actually *BE* org.lib.animal.Monkey.
 
 The usage is the same; it works in all cases once you redefine
 __module__.  Who cares what it really is?

The inspect module.

[animals]$ ls
animals
[animals]$ rm animals/*.pyc
[animals]$ ls
animals
[animals]$ ls animals
__init__.py  monkey.py
[animals]$ cat animals/monkey.py
class Monkey(object):
 pass
[animals]$ cat animals/__init__.py
from animals.monkey import Monkey
Monkey.__module__ = 'animals'
[animals]$ python
Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type help, copyright, credits or license for more information.
  from animals import Monkey
  import inspect
  inspect.getsource(Monkey)
Traceback (most recent call last):
   File stdin, line 1, in module
   File 
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/inspect.py, 
line 629, in getsource
 lines, lnum = getsourcelines(object)
   File 
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/inspect.py, 
line 618, in getsourcelines
 lines, lnum = findsource(object)
   File 
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/inspect.py, 
line 494, in findsource
 raise IOError('could not find class definition')
IOError: could not find class definition
 

-- 
Robert Kern

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

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


Re: Extending the import mechanism - what is recommended?

2008-01-29 Thread Steve Holden

[EMAIL PROTECTED] wrote:

I need to extend the import mechanism to support another file type.
I've already written the necessary C library to read the file and
return a python code object.

I found one example which just sub-classed imputil.ImportManager like
this:

from myLib import pye_code as pye_code
class MyImporter(imputil.ImportManager):
def __init__(self):
imputil.ImportManager.__init__(self)
self.add_suffix('.pye', self.import_pye)
self.install()

def import_pye(self, filepath, fileinfo, filename):
data = pye_code(filepath)
return 0, data, {}

This actually works fine if the module is just a few lines of code,
but it won't chain to the built-in importers; if the module that I'm
importing does something as simple as 'import re', it fails.

It may be that my confusion here is because (even after reading the
code), I'm not clear on the purposes of imputil.ImportManager vs.
imputil.Importer :-(

What is the preferred way to do this type of extension?  One other
note; at this time, I just need to import individual module files with
this extension; I don't need to import packages.

Here's an importer I wrote some time ago to bring modules in from a 
relational database. I won't trouble you with the code to compile the 
modules/packages and add them into the database, but perhaps the 
attached code will be enough to show you what you are doing that's not 
working.


regards
 Steve
--
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/
#
# Import modules from a database
#
# NOTE: could use sys version info to select appropriate module version
#   - could ask whether to install if absent ... heh, heh :-)
#
import sys, db, marshal
VER = sys.hexversion

debug = 0

conn = db.conn()
curs = conn.cursor()

curs.execute(select modName from module where modPyVersion=%s, 
(sys.hexversion, ))
impdict = {}
for n in [x[0] for x in curs.fetchall()]:
impdict[n] = 1

class DBmodule(type(sys)):
def __repr__(self):
return DBmodule '%s' originally from '%s' % (self.__name__, 
self.__file__)

class dbimporter(object):

def __init__(self, item, *args, **kw):
if item != *db*:
raise ImportError
if debug:
print dbimporter: item:, id(self), item, args:, args, 
keywords:, kw
print Accepted, item

def find_module(self, fullname, path=None):
if debug:
print %x: find_module: %s from %s % (id(self), fullname, path)
if fullname not in impdict:
if debug:
print Bailed on, fullname
return None
else:
if debug:
print found, fullname, in db
return self

def load_module(self, modname):
if debug:
print %x: load_module: %s % (id(self), modname)
if modname in sys.modules:
return sys.modules[modname]
curs.execute(select modCode, modPackage, modFilePath from module where 
modName=%s and modPyVersion=%s, (modname, VER))
row = curs.fetchone() # should only BE one ...S
if not row:
if debug:
print modname, not found in db
raise ImportError, DB module %s not found in modules
code, package, path = row
code = marshal.loads(code)
module = DBmodule(modname)
sys.modules[modname] = module
module.__name__ = modname
module.__file__ = path # was db:%s % modname
module.__loader__ = self
if package:
module.__path__ = [*db*]
exec code in module.__dict__
if debug:
print modname, loaded:, module, pkg:, package

return module


def install():
sys.path_hooks.append(dbimporter)
sys.path_importer_cache.clear() # probably not necessary
sys.path.insert(0, *db*) # probably not needed with a metea-path hook?


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

Re: Telnet Program

2008-01-29 Thread Rob Wolfe
[EMAIL PROTECTED] [EMAIL PROTECTED] writes:

 I am having some issues writing a telnet program, using telnetlib. I
 am not sure if it is the telnet on the connections end or it is my
 program.

 A little background, when I log in straight from the Linux Command
 prompt. The only thing I get is a blinking cursor. Then I type in my
 command 'FOO' enter then screen on the very next line returns 'OK',
 Then automatically puts the blinking cursor on the next line. Then
 when I want to quit the telnet session I hit CTRL+Z that takes me to
 telnet then i type quit.

 My Program currently looks like it connects. Because the last string
 that I get back that is not blank says: Logged in successfully.

 So my problem is that when I issue the command through tn.write(FOO
 \n). Then do a tn.read_until('OK\n', 10). It gets returned nothing. I
 have also added tn.read_until('OK\n', 10).splitlines(). That is also
 returned blank.

 I have tried various different newlines \n \r \r\n. All the
 documentation for telnet program that I am logging into says, use
 Carriage Return after each command. Nothing seems to get back the
 data. I am not sure if the Python telnet is looking for more of true
 command line like telnet.

Have you tried: tn.set_debuglevel(1) ?

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


Re: Python noob SOS (any [former?] Perlheads out there?)

2008-01-29 Thread Wildemar Wildenburger
kj wrote:
 Is there any good reading (to ease the transition) for Perl
 programmers trying to learn Python?
 

www.diveintopython.org

While it is a bit dated by now (Python 2.2), that thing worked wonders 
for me. Shows you Python in action and presents a fair amount of its 
philosophy along the way.

Maybe(!) that helps a bit.

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


Re: Mx.ODBC insert error

2008-01-29 Thread John Machin
On Jan 30, 3:27 am, Greg Corradini [EMAIL PROTECTED] wrote:
 Hello,
 I've never gotten this traceback error before using mx.ODBC.

traceback error?? I see no problem with the traceback.

 Any ideas about
 resolving this issue? The statement and the error it generates are listed
 below.

The error was generated by you. The error message was generated by
[Microsoft][ODBC Microsoft Access Driver]


 curse.execute(Insert into FHWA_StandSamp_2008(LRS_ID_NEW)
 values('040210') where LRS_ID = '0403700010')

 Traceback (most recent call last):
 File pyshell#37, line 1, in ?
   curse.execute(Insert into FHWA_StandSamp_2008(LRS_ID_NEW) values
 ('040210') where LRS_ID = '0403700010')
 ProgrammingError: ('37000', -3516, '[Microsoft][ODBC Microsoft Access
 Driver] Missing semicolon (;) at end of SQL statement.', 4612)


Like it says, ProgrammingError.

Try
INSERT INTO table (columns) VALUES (values)
or
INSERT INTO table (columns)
SELECT stuff FROM somewhere [WHERE boolean_expression] 
or perhaps even
UPDATE table SET column = expression WHERE boolean_expression

Perhaps you could consider avoiding combining random fragments of SQL
or English and hoping for tolerant fuzzy parsing by the recipient :-)

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


Re: extending Python - passing nested lists

2008-01-29 Thread Arnaud Delobelle
On Jan 29, 4:00 pm, Christian Meesters [EMAIL PROTECTED] wrote:
  You didn't mention speed in your original post.

 Sorry, perhaps I considered this self-evident - which it is, of course, not.

  What about using
  array.array?  Unless I am mistaken, these are just a thin wrapper
  around normal C arrays.

 The algorithm I want to implement requires several million floating point
 operations. Neither the array-modules nor numpy's thin layer seem thin
 enough for me. ;-)

I'm not sure I understand.  Here, taken from Modules/arraymodule.c, is
the definition of an arrayobject:

typedef struct arrayobject {
PyObject_VAR_HEAD
char *ob_item;
Py_ssize_t allocated;
struct arraydescr *ob_descr;
PyObject *weakreflist; /* List of weak references */
} arrayobject;

Now here is the function that gets an item from an array of floats:

static PyObject *
f_getitem(arrayobject *ap, Py_ssize_t i)
{
return PyFloat_FromDouble((double) ((float *)ap-ob_item)[i]);
}

This means that if you define an array of floats, call the arrayobject
'ap', then (float *)ap-ob_item seems to meexactly what you want: a c
array of floats.  In what way is this not suitable?

  Anyway you could always convert your list
  into a c array, do lots and lots of fast calculations, then convert it
  back again to a list.

 I guess I am too blind to see, but I couldn't discover a method description
 like double* PyList_toDouble. So, yes, my question is a C-API-newbie
 question: What is the way to say myCarray = SomePyMethod(InputPyList)? Or
 better, what should be here instead
 static PyObject *_foo(PyObject *self, PyObject *args) {
   double *v;
   if (!PyArg_Parse(args, (d), v))
     return NULL;
 to get a list as an array of doubles into 'v' (and back to Python)?

You can always iterate over the elements of the list an fill your c
array with the results.  Look at the array_fromlist() function in
arraymodule.c, this function does exactly this.

HTH

--
Arnaud

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


noob stuck on reading double

2008-01-29 Thread Hannah Drayson
Hi all,

I have a .bin file which python just won't play ball with-
Does anyone know what I'm doing wrong- is it simply incompatible?

I've read it fine using a C program - its 113 doubleword fields- apparently its 
possible to handle these in python in a very similar way to C.
I can provide the c code and have attached .bin if anyone is interested...

Thank you all.



It imports as a string of rubbish...
i.e.

open file 'data.bin', mode 'rb' at 0x5a2a8
 text = f.read()
 print text
?F?C??y???
@[EMAIL PROTECTED]@???/???8[EMAIL PROTECTED]/[EMAIL 
PROTECTED]@?Q???Q???Q???Q???Q??ǑR[???Q???




It won't unpack using struct...

 unpack('d', text)
Traceback (most recent call last):
  File stdin, line 1, in module
  File 
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/struct.py,
 line 87, in unpack
return o.unpack(s)
struct.error: unpack requires a string argument of length 8





Using  str and repr gets me something that looks like unicode...

 str(text)
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
\xa0F\xa2C\xc0\xd2y\xf9\xf8[EMAIL PROTECTED]@\x00\x00\x00\x
00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00g[\xa0?B8~\xd4\x00\x00\x00
\x00\x00\x00\xf8\xff\x00\x00\x00\x00\x00\x00\xf8\xff\x00\x00\x00\x00\x00\x00\x0
0\x00\x00\x00\x00\x00\x00\x00\
etc.




Tried formatting it...

 str(text) % ('Python', 'g')
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: not all arguments converted during string formatting





Tried converting it to unicode...


 unicode(text, 'utf8', 'strict')
Traceback (most recent call last):
  File stdin, line 1, in module
  File 
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/encodings/utf_8.py,
 line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa0 in position 19: 
unexpected code byte





I even tried chopping it up into 8 character pieces and then converting it into 
a float, but I think I'm just being stupid by this point...


 the_list=[]
 index = 0
 second_dig = 7
 while index  (len(bum))/8:
... new_bit = bum[index:second_dig]
... the_list.append(new_bit)
... index += 8
... second_dig += 8
...
 print the_list
[u'\x00\x00\x00\x00\x00\x00\x00', u'\x00\x00\x00\x00\x00\x00\x00', 
u'\x00\x00\x00\ufffdF\ufffdC', u'[EMAIL PROTECTED]', u'[EMAIL PROTECTED]', 
u'\x00\x00\x00\x01\x00\x00\x00', u'\x00\x00g[\ufffd?B', 
u'~\ufffd\x00\x00\x00\x00\x00', u'\x00\x00\x00\ufffd\x00\x00\x00', 
u'\x00\x00\x00\x00\x00\x00\x00', u'\x00\x00\x00\x00\x00\x00\x00', 
u'\x00\x00\x00\x00\x00\x00\x00', u'\x00\x00\x00\x00\x00\x00\x00']
 the_list[1]
u'\x00\x00\x00\x00\x00\x00\x00'
 float(the_list[1])
Traceback (most recent call last):
  File stdin, line 1, in module
UnicodeEncodeError: 'decimal' codec can't encode character u'\x00' in position 
0: invalid decimal Unicode string


Any ideas?


data.bin
Description: data.bin
-- 
http://mail.python.org/mailman/listinfo/python-list

  1   2   >