Using python to extend a python app

2005-03-24 Thread dataangel
I'm writing a python app that works as a replacement for the menu that 
comes with most minimalist wms when you right click the root window. 
It's prettier and written completely in python.

I'd like to provide hooks or some system so that people can write their 
own extensions to the app, for example adding fluxbox options, and then 
fluxbox users can choose to use that extension. But I'm not sure how to 
implement it.

Right now the best idea I have is to have all desired extensions in a 
folder, import each .py file in that folder as a module using 
__import__, and then call some predetermined method, say start, and 
pass it the menu as it exists so far so they can add to it, start(menu). 
This seems kind of hackish.

I looked at how gdesklets handles this, but its solution looks way more 
complex than I'd prefer to have to dive into for this tiny app.

What's the most pythonic way to do this? How do apps that extend 
themselves with python usually do this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Sending hex number as is

2005-03-24 Thread Antoon Pardon
Op 2005-03-21, [EMAIL PROTECTED] schreef [EMAIL PROTECTED]:
 This question may be ased before, but I couldn't find the answer
 searching the archive.

 Basically, I just want to send a hex number from one machine to the
 next:

Hex numbers don't exist. You have just numbers. Those numbers can
be represented in different ways, but that doesn't make it a different
(kind of) number.

 for example

 msg = Length is 
 n = '\x81'
 msg += n
 sock.send(msg)

You are not sending a number, you are sending a string. What you
seem to want is to represent this number in hexadecimal format
on this machine within a string and send that string to an other
machine.

 The problem is n's value is not fixed. For example,

 msg = Length is 
 n = len(somestring)
 msg += n  # This won't work of course, since n is int

 How do I send this msg + n?

Use string formatting:

  msg = Length is 0x%x % n

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


Re: IronPython 0.7 released!

2005-03-24 Thread Robin Becker
Thomas Heller wrote:

well that's nice, but I don't do blogs and certainly don't do M$
Passport logins which it seems the gotdotnet site requires.

Robin - we're too old for blogs ;-)
But I could download the thingie with Mozilla without logging in into
somewhere - although the bug tracker seems to require login.
Thomas
yes, but the simple download is a bit bare, I was hoping to find out 
more and then the passport login seems to come into play. Is there no 
other homepage somewhere? I assumed wsa www.ironpython.com, but that 
seems a bit out of date now. The mailing list seems to go to end of 
February so was looking for some recent back and forth.
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Re: IronPython 0.7 released!

2005-03-24 Thread Robin Becker
Luis M. Gonzalez wrote:
James wrote:
http://www.gotdotnet.com/workspaces/workspace.aspx?id=ad7acff7-ab1e-4bcb-99c0-57ac5a3a9742
This is what I get when I follow this link:
Operational Troubleshooting in Progress
I've been visiting ironpython's site all day long searching for news
but nothing...
Has anyone managed to download the new release?
If so please, would you email it to me at luismgz at gmail.com ??
I managed by clicking on the gotdotnet link and got a zip file OK.
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Re: IronPython 0.7 released!

2005-03-24 Thread Robert Kern
Robin Becker wrote:
yes, but the simple download is a bit bare, I was hoping to find out 
more and then the passport login seems to come into play. Is there no 
other homepage somewhere? I assumed wsa www.ironpython.com, but that 
seems a bit out of date now. The mailing list seems to go to end of 
February so was looking for some recent back and forth.
Jim has a predilection towards keeping mum for a while so he can make 
big announcements at his conference talks. Once you know that about his 
character, the rest falls into place.

--
Robert Kern
[EMAIL PROTECTED]
In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die.
  -- Richard Harter
--
http://mail.python.org/mailman/listinfo/python-list


Suggestions for a Java programmer

2005-03-24 Thread Ray
Hello there,

I've been programming in Java for about 8 years now, but lately I've
been hearing a lot about Python and I'm really interested in learning
more about it. I've read the tutorial, and some books (core python
programming is one), but there's one thing that's still missing: how to
use Python the Python way.

I found learning C# was a breeze for me because the language shares a
lot of concepts and notions with Java--I can always say: I do X this
way in Java, I should be able to do X this way too in C#, and usually
I'm not far off the mark.

But Python is different enough that, even though some basic concepts do
translate easily, idioms and effective usage of it don't come easy. I
can't help thinking that when I'm writing Python, I'm actually writing
Java in Python. Not Python in Python.

Can you point me to Python for Java Programmers resources? I found
one blog, but that only touched the tip of the iceberg, I feel. I know
that as I use Python more and read more books and read how experienced
Python programmers code, eventually I'll find it out. But I'd like to
expedite that process if possible. What are your suggestions?

Thank you!
Ray

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


Re: IronPython 0.7 released!

2005-03-24 Thread Robin Becker
Robert Kern wrote:
Robin Becker wrote:
yes, but the simple download is a bit bare, I was hoping to find out 
more and then the passport login seems to come into play. Is there no 
other homepage somewhere? I assumed wsa www.ironpython.com, but that 
seems a bit out of date now. The mailing list seems to go to end of 
February so was looking for some recent back and forth.

Jim has a predilection towards keeping mum for a while so he can make 
big announcements at his conference talks. Once you know that about his 
character, the rest falls into place.

apparently he announced at 1800 PST on the list, but I note he's 
directing bug reports to the gotdotnet site :(

I just have this thing about M$ and passport etc etc
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python for a 10-14 years old?

2005-03-24 Thread MyHaz
Well i don't know of any tutorials but i thought of a cool little
assignment that might interest someone of that age assuming english
is her first language. Its a neat little trick with english and the way
that we proccess letter combinations (or should i say permuations). But
a program that turned proper english into this, might be neat.


Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it deosn't mttaer in
waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is taht
the frist and lsat ltteer be at the rghit pclae. The rset can be a
toatl mses and you can sitll raed it wouthit porbelm. Tihs is bcuseae
the huamn mnid deos not raed ervey lteter by istlef, but the wrod as a
wlohe.



the algo whold be something like

openfile
for word in file
   tmp=word[0]
   tmp+=permut(tmp[1:-2])
   tmp+=word[-1]
   print word


She could enjoy sending letters like this, neat secrete codes for a
nine year old ;)


Linky http://www.mrc-cbu.cam.ac.uk/personal/matt.davis/Cmabrigde/

G'Luck
- Haz

P.S. I just had my friend read it and his native tongue is chinese, so
might work for other languages too.

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


Re: looking for programmer

2005-03-24 Thread MyHaz
Well your welcolme to send me the specs, im always up for making a few
pennys.

As for the yahoo account, i have me a spam catcher account and seems to
work rather well.

Hope To Here From You
- Haz

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


Re: Simple account program

2005-03-24 Thread Igorati
ah thank you again. Anyone know of a good place to get information about TK
inter. I am gonna try and make this program somewhat of a GUI. Thank you
again.

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


Re: IronPython 0.7 released!

2005-03-24 Thread Josef Meile
well that's nice, but I don't do blogs and certainly don't do M$ 
Passport logins which it seems the gotdotnet site requires.
I agree, even for reading the FAQ and the Readme you need a password :-(
--
http://mail.python.org/mailman/listinfo/python-list


execfile() on file subclass or string

2005-03-24 Thread Brano Zarnovican
Hi !

I have a python script represented by a string.
I need to execute it in a context. 'exec' does
the job, but doesn't display the filename in
tracebacks. 'execfile' is displaying the filename
but it can only exec a script in a filesystem.

I have tried:
- to give exec a filename, like:

  exec script_content in dict({'__file__':'bla.py'})

  = didn't work (neighter with __name__)

- create an in-memory file subclassing 'file'

  class memfile(file):
..
def read(self)..

  = also pointless as 'execfile' doesn't accept a file
only a filename

Can you help me ?
The only problem I need to resolve is that I don't see
the script name in tracebacks.

Thanks,

BranoZ

PS: The script didn't came from the filesystem, but I know
  it's content and a name.

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


Re: Anonymus functions revisited

2005-03-24 Thread bruno modulix
George Sakkis wrote:
bruno modulix [EMAIL PROTECTED] wrote: in message news:[EMAIL PROTECTED]
(snip)
Note that you don't have anything like
list unpacking, now tuple unpacking is pretty common in Python (swap,
multiple return values, formatted strings and outputs, ...).

All the following are possible:

(x,y,z) = (1,2,3)
(x,y,z) = [1,2,3]
[x,y,z] = (1,2,3)
[x,y,z] = [1,2,3]

What exactly do you mean by don't have anything like list unpacking ?
A stupidity :(
--
bruno desthuilliers
ruby -e print '[EMAIL PROTECTED]'.split('@').collect{|p| 
p.split('.').collect{|w| w.reverse}.join('.')}.join('@')
--
http://mail.python.org/mailman/listinfo/python-list


Re: Anonymus functions revisited

2005-03-24 Thread Duncan Booth
Ron wrote:

 A working makeVars seems not to be different from
 
 def makeVars(**nameVals):
globals().update(nameVals)

Not quite. If Ron can come up with a working makeVars it would update
the caller's globals whereas what you just posted updates makeVar's
globals so there is a difference (when the makeVars and the calling
function are in different modules), just not a very useful one.
 
 How about this one?   The only reliable way I found to do it is to
 pass locals() to the function.

Yes, but you are still missing the fundamental point. The locals() 
dictionary is not guaranteed to do anything useful if you update it. The 
current C implementation will reflect changes in the locals dictionary if 
you call locals() from global scope or in a few other circumstances, but 
this is simply an implementation detail.

If you want to update global variables then use globals() or setattr on the 
module. Only use locals() to access local variables indirectly, never to 
try and set them.
-- 
http://mail.python.org/mailman/listinfo/python-list


The Running Time of += on Char Strings ?

2005-03-24 Thread Edg Bamyasi
This Is A Late Cross Post from comp.lang.python. It seems the mistery
is deeper then i expected.

What is the running time of conactination on character strings.

i.e.

 joe=123
 joe+=9

is it Amortized Constant time? I don't think it would be O((number of
chars)^2) but i really don't know.

Teach me how to fish, where would i find out more about the

internal
representations of data types in python (and guarenteed run times, im
think of something like sgi.com 's info on the STL) . I have looked
through the docs but i don't seem to see these types of specifications.

thanks * 100
- Haz

P.S.
- Should Note that i am famliure with timeit, but understanding the
underly data structures and representations is an important thing to
know.

P.P.S

This a bit of what i think relevent discourse i have been having via a
email responder of my usenet posting.

 Haz i should have mentioned that i am familure with the timeit
 Haz function, but shurly there must be a specification in the language
 Haz of the running time (number of flops).

 Nope.  I can't think of an instance where it would be appropriate to specify
 runtime properties of various algorithms in the language.  For example, if
 you were to specify that sorting of lists was O(n log n) that would
 potentially preclude the choice of quicksort as an algorithm because its
 worst case behavior is O(n * n) even though it is generally faster than most
 other sorting algorithms.

The answere here is to use omega(n log n) or specify average and worst
cases. I truely do think that there can be a complexity specification
for the language. I mean all algorithms have a complexity and surely
data structures are choosen with the size/speed tradeoffs in mind.

For instance in the STL has a sorting algorithm and it specifies a
running time the latter way (why they can do assure this is by using
coding with concepts, but i think in the base language it could be
simpler because the data structures are known.) i.e. Its know what
data types += works on and thus it should be know what algoritms are
to be used (that is the highly optimal ones)

From SGI STL Page:
sort
snip
Complexity
O(N log(N)) comparisons (both average and worst-case), where N is last
- first. [2]
snip

source : http://www.sgi.com/tech/stl/sort.html


 Haz Without knowing these specifications its hard to optimize.

 No, you still need to see where your program runs slow and figure out ways
 to make it run faster.

Well basically my point is that it is hard to know why a code section
is running slow unless you understand the underlying data
represenations and algorithms

For instance

matlab code:

A=[]
for i=1:N
 A=[A;'a']
end

is O(N^2) operation

C code:

vectorchar A;
for(i=0; iN; i++){
 A.push_back('a');
}

is Amortized O(N)   [note that this isn't the correct wording exactly,
but in general is O(N)]

Python Code:

A=
for i in range(N):
  A+='a'

running time : ???

So if you are looking through your code in matlab or C and see this
concatination loop you know that it is a problem in the former and not
in the latter. But in python ???
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please help for Python programming

2005-03-24 Thread bruno modulix
[EMAIL PROTECTED] wrote:
I am sorry that i forgot to see the working example. Base on your
example, i can show the value without missing but got the other
problem. I would like to culmulate the value by users. 
This is (almost) exactly the same.
I was rewrite
your example but cannot not work.
##
import sys
import pprint
try:
f = open('data.txt', 'r')
except IOError, e:
print  sys.stderr, Cannot open file data.txt for reading : %s
%e
sys.exit(1)
users = {}
cumdata2 = 0
cumdata3 = 0
for line in f:
try:
user, data1, data2 = line.strip().split('\t')
except ValueError:
print  sys.stderr, wrong file format
f.close()
sys.exit(1)
try:
users[user].append(%s : %s % (data1, data2))
cumdata2 = int(data2) + cumdata2
Q1 : What do you think this will do ?
except KeyError:
users[user] = [%s : %s % (data1, data2)]
cumdata3 = int(data2) + cumdata3
Q2 : What do you think this will do ?
f.close()
print collected data:;
pprint.pprint(users)
print cumdata2
print cumdata3
##
The above example can run but the total num are wrong. 
First, please post your test data set, the expected result and the 
actual result. Saying 'the total num is wrong' doesn't give a clue.

Would you mind
to figure out where is my problem?
I may be wrong (pun intended), but I think you don't really understand 
what this code is doing, specially this part :

try:
  users[user].append(something)
except KeyError:
  users[user] = [something]
In fact I think your problem is that you still have not read the fine 
manual, specially the part about dicts.

Read the manual, understand the above snippet - which is a pretty common 
idiom in Python -, try to answer Q1 and Q2, and you should be able to 
work it out by yourself.

--
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for 
p in '[EMAIL PROTECTED]'.split('@')])
--
http://mail.python.org/mailman/listinfo/python-list


Re: Submission for Python Limmerick Contest

2005-03-24 Thread Raseliarison nirinA
a penguin, a gnu and a snake
and an X animal participate in
a poem contest. who will win?

Ellipsis

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


Re: Suggestions for a Java programmer

2005-03-24 Thread TZOTZIOY
On 24 Mar 2005 00:22:09 -0800, rumours say that Ray
[EMAIL PROTECTED] might have written:

Can you point me to Python for Java Programmers resources? I found
one blog, but that only touched the tip of the iceberg, I feel. I know
that as I use Python more and read more books and read how experienced
Python programmers code, eventually I'll find it out. But I'd like to
expedite that process if possible. What are your suggestions?

Searching google for python for java programmers (without the quotes)
produces:

Python for Java programmers - Irmen's Python wiki
Python  Java: Side by Side Comparison
Jython Home Page (which you might like a lot)
dirtSimple.org: Python Is Not Java (some useful pointers)

among others.  You didn't specify which blog you found, so HTH.
-- 
TZOTZIOY, I speak England very best.
Be strict when sending and tolerant when receiving. (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anonymus functions revisited : tuple actions

2005-03-24 Thread Kay Schluehr
Ron wrote:
 On Wed, 23 Mar 2005 06:21:30 +0100, Kay Schluehr [EMAIL PROTECTED]
 wrote:

 I think my proposal was more in mind of Rons modified exec than
 Pythons lambda.
 
 When George proposed his unpacking behavoir for list-comps as a pack
of
 suggar:
 
 1. [x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]
 
 I interpreted it in a subsequent posting in lambda fashion:
 
 2. [(lambda x,y,z=0:x*y-z)(*v) for v in (1,2,3), (4,5), (6,7,8)]

 Thank you Kay,  All of this is really intersting and I'm learning a
 lot about the language through these discussions.

Thanks, Ron !

 The following is an experiment I did this morning. :-)

 I was surprised it worked as well as it did, although I don't think
it
 should be used in any real production code.  Not in it's present form
 anyway.

 The idea is to have a container class like a tuple for program code
 that can be moved around and used when needed.  Very flexable, maybe
 if it could be done without the strings and the exec/eval() functions
 in it?

I personally don't like using exec and eval for stuff different from
evaluating user input.

You rely much on evaluate statement on the line by adapting
conventional Python syntax. I think one can go a bit further breaking
the syntactical prejudices and apply tuple-actions :)

Playing a bit with tuple-actions shows that the concept is quite
powerfull and can be used to create simple statements.

First of all the semantics has to be patched:

We have

   (x,y,z=0) - (x,y,z)

as a tuple assignment

   ((x,y,z=0)-(x,y,z))(a,b,c) = (x=a,y=b,z=c)

But it is not clear what

   (x,y,z=0) - x*y-z

actually means?


Proposal:

  (x,y=0) - x*y   = ((x,y=0)-x*y)  (a,b) - (x=a,y=b),a*b
  (x,y=0) - (x*y) = ((x,y=0)-(x*y))(a,b) - (x=a*b,y=b)

So (x,y=0) - x*y is appending the result to the argument tuple.

Remark: this is isomorph to

 (x,y=0,res=None) - ((x,y),x*y)

but it becomes harder now to identify

 (x,y,res=None) - ((x,y),x*y)
with
 x*y

Provide a compiler-hint:

(x,y,()) - x*y

Now we are ready for a few examples:


default value:
   (i) - (0)   # i = 0

inplace increment:
   (i) - i+1   # i = i+1

conditional expression:
   (i) - i3   # i,res = i,i3

simple transformation:
   (res) - (res+i**2)  # res = res+i**2


Define a While loop as a function:

def While( par, cond, change, action):
par(None) # create default
res = 0
while cond(par)[1]:
action(res)
change(par)
return res

Let's apply it to some tuple actions:

While((i)-(0), (i)-i3, (i)-(i+1), (res)-(res+i**2))

and evaluate While stepwise:

1. par(None) = (i)-(0)(None) # (i)   = (0)
2. cond(par)[1]  = (i)-i3(0)# (i,c) = (0,True)
3. action(res)   = (res) - (res+i**2)(0) # (res) = (0)
4. change(par)   = (i)-(i+1)(0)  # (i)   = (1)
5. cond(par)[1]  = (i)-i3(1)# (1,c) = (0,True)
6. action(res)   = (res) - (res+i**2)(0) # (res) = (1)
7. change(par)   = (i)-(i+1)(1)  # (i)   = (2)
5. cond(par)[1]  = (i)-i3(2)# (2,c) = (0,True)
6. action(res)   = (res) - (res+i**2)(1) # (res) = (5)
7. change(par)   = (i)-(i+1)(2)  # (i)   = (3)
5. cond(par)[1]  = (i)-i3(2)# (2,c) = (0,False)
break

=  res = 5


If we customize the other control flow primitives For and If it should
be possible to create a little language only by using this primitives.

It is obvious by definition of our While that we can replace arguments
on the fly:

conds = [(i)-i3, (i)-i+27, (i)-i=0]

[ While((i)-(0), cond, (i)-(i+1), (res)-(res+i**2)) for cond in
conds]

= [5,29,0]


Wouldn't it be fun to use in Python?

Only drawback: does not look like executable pseudo-code anymore :(


Regards Kay

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


Re: Suggestions for a Java programmer

2005-03-24 Thread bruno modulix
Ray wrote:
Hello there,
I've been programming in Java for about 8 years now, but lately I've
been hearing a lot about Python and I'm really interested in learning
more about it. I've read the tutorial, and some books (core python
programming is one), but there's one thing that's still missing: how to
use Python the Python way.
I found learning C# was a breeze for me because the language shares a
lot of concepts and notions with Java--I can always say: I do X this
way in Java, I should be able to do X this way too in C#, and usually
I'm not far off the mark.
But Python is different enough that, even though some basic concepts do
translate easily, idioms and effective usage of it don't come easy. I
can't help thinking that when I'm writing Python, I'm actually writing
Java in Python. Not Python in Python.
Can you point me to Python for Java Programmers resources? I found
one blog, but that only touched the tip of the iceberg, I feel. I know
that as I use Python more and read more books and read how experienced
Python programmers code, eventually I'll find it out. But I'd like to
expedite that process if possible. What are your suggestions?
These two books should help you to get a grasp of Pythonic idioms:
http://www.mindview.net/Books/TIPython
http://diveintopython.org/

--
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for 
p in '[EMAIL PROTECTED]'.split('@')])
--
http://mail.python.org/mailman/listinfo/python-list


the problem of embedding python

2005-03-24 Thread
hi,python-chinese!

environment: FreeBSD4.11, gcc2.953.4, python2.2ports.


source code
#include Python.h

int main()
{
Py_Initialize();
PyRun_SimpleString(from time import time, ctime\n
   print 'Today is', ctime( time() )\n);
Py_Finalize();
return 0;
}







document
5.6 Linking Requirements 
While the configure script shipped with the Python sources will correctly build 
Python to export the symbols needed by dynamically linked extensions, this is 
not automatically inherited by applications which embed the Python library 
statically, at least on Unix. This is an issue when the application is linked 
to the static runtime library (libpython.a) and needs to load dynamic 
extensions (implemented as .so files). 

The problem is that some entry points are defined by the Python runtime solely 
for extension modules to use. If the embedding application does not use any of 
these entry points, some linkers will not include those entries in the symbol 
table of the finished executable. Some additional options are needed to inform 
the linker not to remove these symbols. 

Determining the right options to use for any given platform can be quite 
difficult, but fortunately the Python configuration already has those values. 
To retrieve them from an installed Python interpreter, start an interactive 
interpreter and have a short session like this: 


 import distutils.sysconfig
 distutils.sysconfig.get_config_var('LINKFORSHARED')
'-Xlinker -export-dynamic'

The contents of the string presented will be the options that should be used. 
If the string is empty, there's no need to add any additional options. The 
LINKFORSHARED definition corresponds to the variable of the same name in 
Python's top-level Makefile. 






result when compile
[EMAIL PROTECTED] gcc34 test_python.cpp -o test_python 
-L/usr/local/lib/python2.2/config -lpython2.2 -I/usr/local/include/python2.2
 
/usr/local/lib/python2.2/config/libpython2.2.a(posixmodule.o): In function 
`posix_tmpnam':
posixmodule.o(.text+0x297a): warning: tmpnam() possibly used unsafely; consider 
using mkstemp()
/usr/local/lib/python2.2/config/libpython2.2.a(posixmodule.o): In function 
`posix_tempnam':
posixmodule.o(.text+0x28b6): warning: tempnam() possibly used unsafely; 
consider using mkstemp()
/var/tmp//ccw3igF6.o(.eh_frame+0x11): undefined reference to 
`__gxx_personality_v0'
/usr/local/lib/python2.2/config/libpython2.2.a(floatobject.o): In function 
`float_rem':
floatobject.o(.text+0xf69): undefined reference to `fmod'
/usr/local/lib/python2.2/config/libpython2.2.a(floatobject.o): In function 
`float_divmod':
floatobject.o(.text+0x): undefined reference to `fmod'
floatobject.o(.text+0x11a9): undefined reference to `floor'
/usr/local/lib/python2.2/config/libpython2.2.a(floatobject.o): In function 
`float_pow':
floatobject.o(.text+0x13e2): undefined reference to `fmod'
floatobject.o(.text+0x14b5): undefined reference to `floor'
floatobject.o(.text+0x1541): undefined reference to `pow'
/usr/local/lib/python2.2/config/libpython2.2.a(bltinmodule.o): In function 
`builtin_round':
bltinmodule.o(.text+0x1e1d): undefined reference to `floor'
bltinmodule.o(.text+0x1e37): undefined reference to `ceil'
/usr/local/lib/python2.2/config/libpython2.2.a(thread.o): In function 
`PyThread_start_new_thread':
thread.o(.text+0x46): undefined reference to `pthread_attr_init'
thread.o(.text+0x57): undefined reference to `pthread_attr_setstacksize'
thread.o(.text+0x8b): undefined reference to `pthread_create'
thread.o(.text+0xa9): undefined reference to `pthread_attr_destroy'
thread.o(.text+0xbb): undefined reference to `pthread_detach'
/usr/local/lib/python2.2/config/libpython2.2.a(thread.o): In function 
`PyThread_get_thread_ident':
thread.o(.text+0xe5): undefined reference to `pthread_self'
/usr/local/lib/python2.2/config/libpython2.2.a(thread.o): In function 
`PyThread_allocate_lock':
thread.o(.text+0x198): undefined reference to `pthread_mutex_init'
thread.o(.text+0x1c2): undefined reference to `pthread_cond_init'
/usr/local/lib/python2.2/config/libpython2.2.a(thread.o): In function 
`PyThread_free_lock':
thread.o(.text+0x20e): undefined reference to `pthread_mutex_destroy'
thread.o(.text+0x231): undefined reference to `pthread_cond_destroy'
/usr/local/lib/python2.2/config/libpython2.2.a(thread.o): In function 
`PyThread_acquire_lock':
thread.o(.text+0x272): undefined reference to `pthread_mutex_lock'
thread.o(.text+0x2b6): undefined reference to `pthread_cond_wait'
thread.o(.text+0x2ec): undefined reference to `pthread_mutex_unlock'
/usr/local/lib/python2.2/config/libpython2.2.a(thread.o): In function 
`PyThread_release_lock':
thread.o(.text+0x32e): undefined reference to `pthread_mutex_lock'
thread.o(.text+0x354): undefined reference to `pthread_mutex_unlock'
thread.o(.text+0x377): undefined reference to `pthread_cond_signal'
/usr/local/lib/python2.2/config/libpython2.2.a(thread.o): In function 
`PyThread_allocate_sema':

Re: The Running Time of += on Char Strings ?

2005-03-24 Thread Daniel Dittmar
Edg Bamyasi wrote:
What is the running time of conactination on character strings.
i.e.

joe=123
joe+=9

is it Amortized Constant time? I don't think it would be O((number of
chars)^2) but i really don't know.
Strings are immutable, so
joe+=9
is executed as
joe = joe + 9
This means that there is
- one allocation
- two memcpy
- one deallocation (old value of joe)
My guess is that the allocations play a rather large part in the actual 
timing.

Creating a large string by multiple concatenations is slow, instead you 
should:
- use module cStringIO
- or add all the strings to a list and do .join (listvariable)

How are you supposed to know? It's mostly Python folklore, some of which 
has been written down in the Python Cookbook 
(http://aspn.activestate.com/ASPN/Python/Cookbook/)

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


Re: Python for a 10-14 years old?

2005-03-24 Thread Michele Simionato
Your post and the following answers made me think.

It is widely held that the intellectual capabilities of children
are inferior to the capabilities of adultes. Nevertheless,
I wonder to which extent this is true.

There is no doubt that the critical sense is much less developed
in children than in adults: for instance, as a child, I would never
had thought of questioning the existence of Santa Klaus ;)

But here I am discussing other kind of intellectual capabilities,
in particular the ability to learn a programming language.

I think the problem most kids face is *not* lack of intellectual
capability, but lack of concentration. Most kids cannot keep
their concentration focused on a single topic for a long period
of time, so they start one thing and never finish it, since
they have a thousand other little things to do in the mean time.

Becoming older, the ability to discipline themselves increases,
so it is probably easier to learn a programming language for a
15 year old than for 9 year old.

This as a general rule. There are, of course, exceptions. Many
people will never have the needed discipline to learn a programming
language. On the other hand, some people are able to maintain their
concentration focused for a long period of time even in early age.

When I was 2-3 years old I was able to spend whole *days* working
on my Lego construction set. The problem was to keep me out of
my work and explain me that it was time to eat! ;)

I am pretty much convinced I could have mastered Python at the age
of nine. Of course, I cannot prove it, since when I was nine
I had no computer, I did not know English, and Python was not
yet invented. But apart for this minor circumstances, I don't
thing I was dumber as a child than as an adult.

Actually, one could even make the case that children are much better
than adults at learning new things. Adults are better at understand
things, seing the correlations between them, and the inconsistencies
(if any).

The problem teachers face when explaining computers to kids, is
to keep them interested, so they prepare courses about graphics,
videogames, etc. But if you get the right kid, he/she will be
interested even on IBM Fortran IV with WATFOR and WATFIV ;)

Personally, at that age I knew everything about the solar system
planets, distances from the Sun, masses, diameters, albedos, etc.
Fortunately, now I have forgot nearly everything ;)


Michele Simionato

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


Re: Suggestions for a Java programmer

2005-03-24 Thread Ville Vainio
 bruno == bruno modulix [EMAIL PROTECTED] writes:

bruno These two books should help you to get a grasp of Pythonic idioms:

...

Regarding a Java programmer moving to Python, a lot of the mindset
change is about the abundant use of built in data types of Python. So
a Java programmer, when confronted with a problem, should think how
can I solve this using lists, dicts and tuples? (and perhaps also my
new favourite, sets). Class-based solution should be chosen only after
seeing that the problem can't be trivially solved with built-in types.

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


unittest help

2005-03-24 Thread Qiangning Hong
I want to apply TDD (test driven development) on my project.  I am
working on a class like this (in plan):

# file: myclass.py
import _extmod

class MyClass(object):
def __init__(self):
self.handle = _extmod.open()

def __del__(self):
_extmod.close(self.handle)

def some_stuff(self):
_extmod.foobar(self.handle)

...

As you see, it is an OO wrapper on _extmod, which is a pyrex extension
module.  The question is: how to unittest this class?  As the _extmod
is hardware-dependent, I want to use a mock class to replace it in unit
test.  But how can I let myclass in unittest to import the mock class?
Like the following:

class MyClassTest(unittest.TestCase):
def setUp(self):
import myclass
import mocklib
myclass.change_extmod(mocklib.MockExtMod())
self.testobj = myclass.MyClass()  # here MyClass.__init__ will
call the open
  # method of MockExtMod class
instead of
  # _extmod.open()
...

How to implement the change_extmod?  (Or maybe my idea is totally
wrong?)

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


Re: The Running Time of += on Char Strings ?

2005-03-24 Thread Stefan Behnel
Edg Bamyasi schrieb:
What is the running time of conactination on character strings.
i.e.
.joe=123
.joe+=9
is it Amortized Constant time? I don't think it would be O((number of
chars)^2) but i really don't know.
First of all, this idiom is generally avoided in loops (where it actually 
matters). Use ''.join() which the documentation describes as optimized for 
your case and as preferable over creating a larger number of immutable 
strings. Note that it does not specify the run-time complexity there.

That said, Python is a dynamic, high-level language. CPython is an 
implementation. IronPython and Jython are different implementations. There are 
others. Many of the internal complexities are implementation specific. Some 
have good reasons for this. Also, IronPython and Jython heavily rely on the 
performance of the underlying run-time environment for their own performance. 
The differences between the various implementations and their run-time 
environments can be big enough to render performance specifications useless in 
many (though possibly not all) cases.

If you need to know the exact complexity of algorithms, read them. Download 
the source distribution of the Python version you want to investigate and read 
the source. But remember that there is no actual specification. Do not expect 
your code to run at the same speed in all Python versions and implementations.

There are examples for basic algorithms that were exchanged during the long 
evolution of the CPython implementation. One is the sort algorithm. Recent 2.4 
changes in the handling of lists made some common operations considerably faster.

It is a pragmatically sane approach to accept the high programming level of 
Python and to not rely on the specific performance of a specific 
implementation. Just use the tool that is made for your task. The information 
for choosing the right tool can already be found in the documentation.

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


Re: unittest help

2005-03-24 Thread André Malo
* Qiangning Hong [EMAIL PROTECTED] wrote:

 I want to apply TDD (test driven development) on my project.  I am
 working on a class like this (in plan):
 
 # file: myclass.py
 import _extmod
 
 class MyClass(object):
 def __init__(self):
 self.handle = _extmod.open()
 
 def __del__(self):
 _extmod.close(self.handle)
 
 def some_stuff(self):
 _extmod.foobar(self.handle)
 
 ...
 
 As you see, it is an OO wrapper on _extmod, which is a pyrex extension
 module.  The question is: how to unittest this class?  As the _extmod
 is hardware-dependent, I want to use a mock class to replace it in unit
 test.  But how can I let myclass in unittest to import the mock class?

You need to design for testability, meaning in this case, that your class could
to do something like this:

class MyClass(object):
def __init__(self):
self._loadExtmod()
self.handle = self._extmod.open()

def __del__(self):
self._extmod.close(self.handle)

def _loadExtmod(self):
import _extmod
self._extmod = extmod

def some_stuff(self):
self._extmod.foobar(self.handle)

Now just overload _loadExtmod and provide the mock class there.

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


What are the required modules for ScientificPython?

2005-03-24 Thread HYUN-CHUL KIM



Hi, all
I need "multiarray" package which is required for "ScientificPython".
However, I couldn't find multiarray in Python Package index site.
Where is this?

currently, when executing example script in "Scientific Python", there are 
importing error for "multiarray"

Sincerely,
Hyun-Chul Kim

Biomatics Lab. Department of BiosystemsKorea Advanced Institute of 
Science and TechnologyYusung-Gu, Taejon 305-333Republic of 
Korea
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: unittest help

2005-03-24 Thread Duncan Booth
Qiangning Hong wrote:

 As you see, it is an OO wrapper on _extmod, which is a pyrex extension
 module.  The question is: how to unittest this class?  As the _extmod
 is hardware-dependent, I want to use a mock class to replace it in unit
 test.  But how can I let myclass in unittest to import the mock class?
 Like the following:
 
 class MyClassTest(unittest.TestCase):
 def setUp(self):
 import myclass
 import mocklib
 myclass.change_extmod(mocklib.MockExtMod())
 self.testobj = myclass.MyClass()  # here MyClass.__init__ will
 call the open
   # method of MockExtMod class
 instead of
   # _extmod.open()
 ...
 
 How to implement the change_extmod?  (Or maybe my idea is totally
 wrong?)
 

One way is simply to do:

def setUp(self):
import myclass
self.real_extmod = myclass._extmod
myclass._extmod = mocklib.MockExtMod()
self.testobj = myclass.MyClass()

def tearDown(self):
import myclass
if hasattr(self, testobj):
del self.testobj
myclass._extmod = self.real_extmod

This can be less intrusive than passing the mock object to a constructor, 
but it depends very much on the way the objects are used: changing global 
state for a unit test is a risky business, for example if an exception is 
thrown then tearDown would be called *before* your __del__ method is 
invoked. You can work round this by ensuring that the _extmod value is 
saved in your instance but that takes you pretty much back to André Malo's 
suggestion.

BTW, accessing a global variable from a __del__ method is a bad idea 
generally: there is no guarantee that the global variable will still be set 
if __del__ is called during program exit.

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


What are the required modules for ScientificPython?

2005-03-24 Thread HYUN-CHUL KIM




Hi, all
I need "multiarray" package which is required for "ScientificPython".
However, I couldn't find multiarray in Python Package index site.
Where is this?

currently, when executing example script in "Scientific Python", there are 
importing error for "multiarray"

Sincerely,
Hyun-Chul Kim
Biomatics Lab. Department of BiosystemsKorea Advanced 
Institute of Science and TechnologyYusung-Gu, Taejon 305-333Republic of 
Korea
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: scrollbar dependencies

2005-03-24 Thread Marion
Next mystery :
a picture drawn in the canvas c1 is scrollable.
a picture-containing canvas grided in the canvas c1 is not.

so why ???
Marion
---
from tkinter import *
from PIL import *

class Main:
def __init__(self):
## Main window
self.root = Tk()
self.root.grid_rowconfigure(0, weight=1)
self.root.grid_rowconfigure(1, weight=1)
self.root.grid_columnconfigure(0, weight=1)
## datas : 
self.PIC=[]
self.ANN=[]

## First canvas (picture)
self.c1 = Canvas(
self.root,
width=500,
height=100,
bd=2,
relief=SUNKEN,
scrollregion=(0, 0, 100, 100))

self.c1.grid(
row=0,rowspan=2,
column=1,
sticky='nswe')

#---#
# this is scrollable :
#---#
image  =Image.new(RGB,(100,100))
dessin = ImageDraw.Draw(image)
dessin.rectangle([(10,10),(50,50)],fill=rgb(255,0,0))
photo=ImageTk.PhotoImage(image)
item = self.c1.create_image(0,0,anchor=NW,image=photo)

#---#
# this is not ! :
#---#
canvas=Canvas(self.c1,background=WHITE)
image  =Image.new(RGB,(100,100))
dessin = ImageDraw.Draw(image)
dessin.rectangle([(10,10),(50,50)],fill=rgb(255,0,0))
photo=ImageTk.PhotoImage(image)
item = canvas.create_image(0,0,anchor=NW,image=photo)
canvas.grid()


## Second canvas (annot)
c2 = Canvas(
self.root,
width=500,
height=100,
bd=2,
relief=SUNKEN,
scrollregion=(0, 0, 1000, 1000))
c2.grid(
row=2,rowspan=2,
column=1,
sticky='nswe')

## Special function scroll both canvases horizontally
def xscrollboth(a,*args):
self.c1.xview(a,*args)
c2.xview(a,*args)

## Horizontal scrollbar for both canvases
hScroll = Scrollbar(self.root, orient=HORIZONTAL, command=xscrollboth)
hScroll.grid(
row=4,rowspan=1,
column=1,
sticky='we')

## Vertical scrollbars
vScroll1 = Scrollbar(orient=VERTICAL, command=self.c1.yview)
vScroll1.grid(
row=0,rowspan=2,
column=2,
sticky='ns')
self.c1.config(yscrollcommand=vScroll1.set,xscrollcommand=hScroll.set)

vScroll2 = Scrollbar(orient=VERTICAL, command=c2.yview)
vScroll2.grid(
row=2,rowspan=2,
column=2,
sticky='ns')
c2.config(yscrollcommand=vScroll2.set,xscrollcommand=hScroll.set)
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for a 10-14 years old?

2005-03-24 Thread MyHaz
Michele Simionato:
Actually, one could even make the case that children are much
 better than adults at learning new things.

In the case of natural languge it has been pretty much proven that
children are (much) better/faster at learning then adults. Now it is
left to be shown if this carries over to programing languages.


- Haz

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


Re: scrollbar dependencies

2005-03-24 Thread Eric Brunel
On 24 Mar 2005 03:24:34 -0800, Marion [EMAIL PROTECTED] wrote:
Next mystery :
a picture drawn in the canvas c1 is scrollable.
a picture-containing canvas grided in the canvas c1 is not.
so why ???
Marion
---
[snip]
#---#
# this is not ! :
#---#
canvas=Canvas(self.c1,background=WHITE)
image  =Image.new(RGB,(100,100))
dessin = ImageDraw.Draw(image)
dessin.rectangle([(10,10),(50,50)],fill=rgb(255,0,0))
photo=ImageTk.PhotoImage(image)
item = canvas.create_image(0,0,anchor=NW,image=photo)
canvas.grid()
You don't want to do that. Canvases are not meant to be containers where 
you can pack or grid items. They strangely accept it, but it will never do what 
you want. If you want to pack or grid items in a container, use a Frame. If you 
want to include a widget in a Canvas, use a canvas window:
c1 = Canvas(root)
c1.pack()
c2 = Canvas(c1, bd=2, relief=SUNKEN, width=50, height=50)
c1.create_window(20, 20, window=c2, anchor=NW)
Canvas windows are scollable; widgets packed or gridded in Canvases are 
not. So this really seems to be your problem here.
HTH
--
python -c 'print .join([chr(154 - ord(c)) for c in 
U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: The Running Time of += on Char Strings ?

2005-03-24 Thread MyHaz
Thanks Guys It Was Great Help and I have began to mark my code for the
''.join() string conatination optimization. Upon regoogling (when you
know the right thing to google it can make a big diffrence, having not
know how to google +=, hehe). I found this commentary and set of tests.
I find it a good conclustion to this question.

http://www.skymind.com/~ocrow/python_string/


''.join(['Thank ','you])

- Haz

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


Re: looking for programmer

2005-03-24 Thread Fuzzyman
I'd also be interested...

Regards,


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

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


Re: Python for a 10-14 years old?

2005-03-24 Thread TZOTZIOY
On 24 Mar 2005 02:35:34 -0800, rumours say that Michele Simionato
[EMAIL PROTECTED] might have written:

snip

I am pretty much convinced I could have mastered Python at the age
of nine. Of course, I cannot prove it, since when I was nine
I had no computer, I did not know English, and Python was not
yet invented. But apart for this minor circumstances, I don't
thing I was dumber as a child than as an adult.

At the age of nine at school, two guys from a French computer-making
company named as Loup (in french) or Lupo (in Italian), can't
remember which --if either is correct--, came and gave us a demo of one
of their models.  They wrote a simple BASIC program on the blackboard
and proceeded in explaining what the program did, and then asked for a
kid to type it.  I was chosen randomly, and I managed to do that, but I
*didn't* understand a thing.  See, I didn't either know English (we had
French at school), and I had no contact with computers earlier.  I had a
good knowledge of how things work in the surrounding world, even knew a
lot about electricity and how it works (I had played a lot with
batteries, buttons, wires and lights in order to make some amazing
devices to use with my friends when we were playing Galactica or
Space 1999 or Star Trek...), but *this* I couldn't grok.

This was the challenge that marked my life, I can say.  Next year I
managed to get my parents into buying me a ZX Spectrum 16K, the year
after that I managed to get them into buying me the 32K RAM upgrade
(first hw upgrade I ever did!), and one year and a half later, I managed
to get the Sinclair QL, with better BASIC, multitasking capabilities,
and something more like an OS than any other home computer till then.
And man, wasn't 68k assembly a joy :)

snip

The problem teachers face when explaining computers to kids, is
to keep them interested, so they prepare courses about graphics,
videogames, etc. But if you get the right kid, he/she will be
interested even on IBM Fortran IV with WATFOR and WATFIV ;)

The second book on computers I *bought* was Artificial Intelligence on
the Sinclair QL (age 12 --I bought the book *before* I got the QL :).
The first was 1001 Games for the ZX Spectrum (age 11).  We had lots of
computer magazines though, with lots of source code in them to keep a
kid interested then (the age of home computers)...

Personally, at that age I knew everything about the solar system
planets, distances from the Sun, masses, diameters, albedos, etc.
Fortunately, now I have forgot nearly everything ;)

Unless you play trivial pursuit with friends, in which case such
knowledge is very useful (and doesn't get forgotten :)
-- 
TZOTZIOY, I speak England very best.
Be strict when sending and tolerant when receiving. (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for a 10-14 years old?

2005-03-24 Thread Ville Vainio
 Christos == TZOTZIOY  Christos writes:

Christos (first hw upgrade I ever did!), and one year and a half
Christos later, I managed to get the Sinclair QL, with better
Christos BASIC, multitasking capabilities, and something more
Christos like an OS than any other home computer till then.  And
Christos man, wasn't 68k assembly a joy :)

Linus Torvalds also bought Sinclair Ql back in the day - I was
quite surprised to find out that it had a 32bit CPU (according to his
autobiography).

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: execfile() on file subclass or string

2005-03-24 Thread Do Re Mi chel La Si Do
Hi !


little idea :
You can save the string, in temp-directory (see tempfile module), then, 
use execfile


Michel Claveau 


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


Re: Python for a 10-14 years old?

2005-03-24 Thread TZOTZIOY
On 24 Mar 2005 14:50:39 +0200, rumours say that Ville Vainio
[EMAIL PROTECTED] might have written:

 Christos == TZOTZIOY  Christos writes:

Christos (first hw upgrade I ever did!), and one year and a half
Christos later, I managed to get the Sinclair QL, with better
Christos BASIC, multitasking capabilities, and something more
Christos like an OS than any other home computer till then.  And
Christos man, wasn't 68k assembly a joy :)

Linus Torvalds also bought Sinclair Ql back in the day - I was
quite surprised to find out that it had a 32bit CPU (according to his
autobiography).

68008 at 8 MHz with 32bit architecture, 16bit ALU (long operations took
2 cycles), 8bit external bus (to communicate with cheap memory and other
ICs), 20bit max address space, but with complete compatibility with
68000 machine code.  For example, one could issue the following *single*
instruction:

MOVE.L ($18000), ($18004)

to copy the long from address 98304 to address 98308.  Intel provided
such functionality much later; I am not sure if even the 386 could use
memory indirect on both operands...

If only IBM had chosen Motorola for its new PC, 64KiB memory segments
would be something to laugh at, not something to remember and cry
about...
-- 
TZOTZIOY, I speak England very best.
Be strict when sending and tolerant when receiving. (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scrollbar dependencies

2005-03-24 Thread Marion
ok, we must redefine each canvas scroll individually ... but what a ()
strange language... !!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for a 10-14 years old?

2005-03-24 Thread Reinout van Schouwen
Hi,
On Thu, 23 Mar 2005 [EMAIL PROTECTED] wrote:
I am blessed with a *very* gifted nine-years old daughter for whom I
have recently installed an old GNU/Linux Mandrake 7.2 on an equally old
Pentium Pro box.
FWIW. Given a reasonable amount of RAM (256MB should suffice), newer 
Mandrakelinux versions (the latest being 10.1 with 10.2 almost out) will 
run nicely on that Pentium Pro. The advantage would be a much more 
modern user interface, security updates (important if it's connected to 
the internet) and of course, a recent Python package out of the box.

regards,
--
Reinout van Schouwenstudent of Artifical Intelligence
email: [EMAIL PROTECTED]mobile phone: +31-6-44360778
--
http://mail.python.org/mailman/listinfo/python-list


need help with nullmailer-inject in python cgi script to send attachements ?

2005-03-24 Thread tvmaly
Due to the restrictions I have at my host, I cannot use smtplib in my
email cgi script.  They gave me a script they use that calls
nullmailer-inject.   I am trying to figure out how to add the ability
to send attachments via the nullmailer-inject call.  I could not find
much documentation on google about nullmailer.  Has anyone used it
before to send attachments?   Here is function  I have so far that
sends a regular email.  The variables like recipient are set from a cgi
in another part of the script.

 thanks

 Ty

def genmail(reql):
  if nosend: return
  recip=recipient
  cap=form.keys()
  cap.sort()
  mailfl=os.popen('/usr/bin/nullmailer-inject -f '+fromaddr,'w')
  mailfl.write('To: '+recipient+nl)
  if fromaddr: mailfl.write('From: '+fromaddr+nl)
  mailfl.write('Subject: %s%s\n\n'%(subject,uri))
  mailfl.write(intro)
  rx=0
  prev=''
  for x in cap:
while (rxlen(reql) and reql[rx]x):
  if reql[rx]prev:
putln(reql[rx],mailfl)
  rx=rx+1
putln(x,mailfl)
prev=x

  for x in envl:
mailfl.write('%s: %s\n'%(x,env[x]))
  mailfl.close()

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


English to a bit of code

2005-03-24 Thread bearophileHUGS
It's still a toy, but it looks interesting. It converts in Python,
Lisp and Java, and the shown image looks like Python:

http://www.trnmag.com/Stories/2005/032305/Tool_turns_English_to_code_032305.html

Google cache for a draft about it:
http://www.google.com/search?q=http%3A%2F%2Fweb.media.mit.edu%2F%7Ehugo%2Fpublications%2Fdrafts%2FProg-Nat-Lang7.doc

I think for this purpose Python is probably among the best languages
:-)

Bye,
Bearophile

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


Re: Pattern matching from a text document

2005-03-24 Thread Larry Bates
Ben,

Others have answered your specific questions, but I thought
I'd use this opportunity to make a general statement.  Unlike
other programming languages, Python doesn't make its built-in
functions keywords.  You should never, ever, ever name a
variable 'list' (the same is true of dict, tuple, str, ...).
When you do you mask the built-in Python function with your
variables.  If this hasn't bitten you before, it will at some
point.

It really doesn't sound like you require regular expression
complexity to just read in some data.  You might want to
investigate CSV module (for reading comma delimited files)
or you might just be able to use simple .split() method (for
tab delimited files).

Hope info helps.

Regards,
Larry Bates


Ben wrote:
 I'm currently trying to develop a demonstrator in python for an
 ontology of a football team. At present all the fit players are
 exported to a text document.
 
 The program reads the document in and splits each line into a string
 (since each fit player and their attributes is entered line by line in
 the text document) using list = target.splitlines()
 
 The program then performs a loop like so:
 
 while foo  0:
 if len(list) == 0:
 break
 else:
 pat =
 ([a-z]+)(\s+)([a-z]+)(\s+)([a-z]+)(\s+)(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})([a-z]+)
 ph = re.compile(pat,re.IGNORECASE)
 
 match = ph.match(list[1])
 
 forename = match.group(1)
 surname = match.group(3)
 attacking = match.group(7)
 defending = match.group(8)
 fitness = match.group(9)
 
 print forename
 print len(list)
 del list[0]
 
 The two main problems I'm having are that the first and entry in the
 list is not printing. Once I have overcome this problem I then need
 each player and there related variables to be stored seperately. This
 is not happening at present because each time the loop runs it
 overwrites the value in each variable.
 
 Any help would be greatly appreciated.
 
 Ben.
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for a 10-14 years old?

2005-03-24 Thread Jim

My kids like
  http://www.alice.org
(although they run it under Windows).

Jim Hefferon

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


Re: Python for a 10-14 years old?

2005-03-24 Thread moma
 Well i don't know of any tutorials but i thought of a cool little
 assignment that might interest someone of that age assuming english
 is her first language.
Good idea.
1) Have u noticed that whn yu raed that srcamled text luodly, it sounds 
like spoken by a deaf person. (because severe loss of hearing makes it 
hard to learn correct pronunciation).

2) Is this the same fennomena like in the (ancient Hebrew language?) 
that in written form uses consonant letters only.  The reader then fills 
in the missing vowels (aeioyäö). Like: kck th bll nt wall nd ctch t bck.

hmm, maybe not!
3) Anyway, gnna love that srcmbled format simply because rerrors do not 
appear, show up ;-). (having English as a foreign language)


// moma
   http://www.futuredesktop.org/AsteriskPBX.html  -
   http://www.futuredesktop.org/hpc_linux.html
   Why run one PC obi  when you can hvae a cluster ?

MyHaz wrote:
Its a neat little trick with english and the way
that we proccess letter combinations (or should i say permuations). But
a program that turned proper english into this, might be neat.

Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it deosn't mttaer in
waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is taht
the frist and lsat ltteer be at the rghit pclae. The rset can be a
toatl mses and you can sitll raed it wouthit porbelm. Tihs is bcuseae
the huamn mnid deos not raed ervey lteter by istlef, but the wrod as a
wlohe.

the algo whold be something like
openfile
for word in file
   tmp=word[0]
   tmp+=permut(tmp[1:-2])
   tmp+=word[-1]
   print word
She could enjoy sending letters like this, neat secrete codes for a
nine year old ;)
Linky http://www.mrc-cbu.cam.ac.uk/personal/matt.davis/Cmabrigde/
G'Luck
- Haz
P.S. I just had my friend read it and his native tongue is chinese, so
might work for other languages too.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python for a 10-14 years old?

2005-03-24 Thread Fred Pacquier
Christos TZOTZIOY Georgiou [EMAIL PROTECTED] said :

 At the age of nine at school, two guys from a French computer-making
 company named as Loup (in french) or Lupo (in Italian), can't
 remember which --if either is correct--, came and gave us a demo of one
 of their models.

OT/trivia : if it was between mid-eighties and early nineties, the company 
could be Goupil (ancien french for Fox).

-- 
YAFAP : http://www.multimania.com/fredp/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: execfile() on file subclass or string

2005-03-24 Thread Fredrik Lundh
Brano Zarnovican wrote:

 I have a python script represented by a string.
 I need to execute it in a context. 'exec' does
 the job, but doesn't display the filename in
 tracebacks. 'execfile' is displaying the filename
 but it can only exec a script in a filesystem.

 I have tried:
 - to give exec a filename, like:

  exec script_content in dict({'__file__':'bla.py'})

  = didn't work (neighter with __name__)

compile the script first, and execute the resulting code object:

 exec compile(code, filename, exec)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File filename, line 1, in ?
NameError: name 'code' is not defined

/F 



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


DBAPI Paramstyle

2005-03-24 Thread Bob Parnes
The following script is a one person's  comparison of three methods for
accessing a postgresql database using psycopg on a debian computer
running python2.3. Following it are the results of running it six
times.

===
from time import time, clock
import psycopg

MAX_COUNT = 5

def pyMethod():
for n in range(MAX_COUNT):
curs.execute('''SELECT %s;''' % n)

def formatMethod():
for n in range(MAX_COUNT):
curs.execute('''SELECT %s;''', [n])

def pyformatMethod():
for n in range(MAX_COUNT):
curs.execute('''SELECT %(n)s;''', {'n':n})

conn = psycopg.connect(host='localhost', database='template1')
curs = conn.cursor()

for method, func in (('Python method: %f, %f', pyMethod),
 ('Format method: %f, %f', formatMethod),
 ('Pyformat method: %f, %f', pyformatMethod)):
startTime = time()
startClock = clock()
func()
print method % ((time() - startTime), (clock() - startClock))
===

[EMAIL PROTECTED]:~/demo$ ./pyformatTst.py
Python method: 9.288770, 3.55000
Format method: 9.457663, 3.82
Pyformat method: 9.446390, 3.70

[EMAIL PROTECTED]:~/demo$ ./pyformatTst.py
Python method: 9.152173, 3.40
Format method: 9.314743, 3.76
Pyformat method: 9.329343, 3.84

[EMAIL PROTECTED]:~/demo$ ./pyformatTst.py
Python method: 9.262013, 3.49
Format method: 9.344197, 3.57
Pyformat method: 9.402157, 3.50

[EMAIL PROTECTED]:~/demo$ ./pyformatTst.py
Python method: 9.170817, 3.86
Format method: 9.509313, 3.26
Pyformat method: 9.380756, 3.77

[EMAIL PROTECTED]:~/demo$ ./pyformatTst.py
Python method: 9.271831, 3.54
Format method: 9.375170, 3.65
Pyformat method: 9.426898, 3.78

[EMAIL PROTECTED]:~/demo$ ./pyformatTst.py
Python method: 9.192097, 3.72
Format method: 9.244554, 3.69
Pyformat method: 9.368582, 3.76

Similar results occurred with an actual database table. 

I must be missing something, so perhaps someone can explain
the benefit of a paramstyle over the usual Python formatting
style and maybe suggest a test to show it. Thanks.

Bob Parnes

-- 
Bob Parnes
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Archives and magic bytes

2005-03-24 Thread andrea
Chris Rebert (cybercobra) wrote:
Have you tried the tarfile or zipfile modules? You might need to ugrade
your python if you don't have them. They look pretty easy and should
make this a snap.
You can grab the output from the *nix file command using the new
subprocess module.
Good Luck
- Chris
===
PYTHON POWERs all!
All your code are belong to Python!
 

I've got them (I'm still using python 2.3 because I use gentoo) but they 
are not very easy to use as they seem...
I'll try again, thanks!
--
http://mail.python.org/mailman/listinfo/python-list


Re: looking for programmer

2005-03-24 Thread beliavsky
Peter Tyler wrote:
 Hi There,
I'm looking for someone to write some wx/python code on a small
job, but want
 to avoid a spam invasion.
 I was thinking of setting up a temp yahoo account for people to
respond to.
 Is this the right way of going about this, or is there somewhere else
I should
 be looking?
  Thanks
Peter.

If the work can be done off-site, you can solicit bids on a site such
as RentACoder.com . It is possible to specify Python as the language to
be used, and many Python projects have been arranged there.

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


Re: unittest help

2005-03-24 Thread Scott David Daniels
Duncan Booth wrote:
Qiangning Hong wrote:

As you see, it is an OO wrapper on _extmod, which is a pyrex extension
module.  The question is: how to unittest this class?  As the _extmod
is hardware-dependent, I want to use a mock class to replace it in unit
test.  But how can I let myclass in unittest to import the mock class?
Like the following:
Given:
  # file: myclass.py
  import _extmod
  class MyClass(object):
  def __init__(self):
  self.handle = _extmod.open()
  ...
One other way to do your unit test stuff is:
# file: test_myclass.py
import sys, bogus_extmod # First, get the fake hardware
sys.modules['_extmod'] = bogus_extmod # then make that active
import myclass, unittest  # and now do all you normally would do
...
class SimplestTests(unittest.TestCase):
...
Note that the module switch must happen very early (probably at
the top of the main program).
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Dr. Dobb's Python-URL! - weekly Python news and links (Mar 24)

2005-03-24 Thread Cameron Laird
QOTW:  [Must be seen to be believed]
http://groups-beta.google.com/group/comp.lang.python/msg/7613422265cdc010 

If you don't read answers, don't post questions :-/ -- bruno desthuilliers


News from PyCon2005 emerges almost continuously.  See, for
example, this blog startpoint:
http://pycon.blogspot.com/

Want productivity?  Get Python:
http://mail.python.org/pipermail/python-dev/2005-March/052246.html

Pythoneers produce side-splitting doggerel:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d7a780beaff2e88a/

'Suspect that essentially all computing problems have been solved,
and all programs already written?  The Python Poets put the lie to
*that* proposition, and spectacularly:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2825cf318cb63a81/

Florent Guillaume, Fazal Majid, and others significantly advance
the state of threading:
http://mail.python.org/pipermail/python-dev/2005-March/051856.html

Getting passwords right is ... a lot more challenging than the many
inviting ways to do it wrong:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/91e4c114c5114e92/

Understand Python scoping, even in the presence of generators:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/460bdb4e14db8428/



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.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

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

Brett Cannon continues the marvelous tradition established by 
Andrew Kuchling and Michael Hudson 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/

The Python Business Forum further[s] the interests of companies
that base their business on ... Python.
http://www.python-in-business.org

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

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

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch
   
Cetus collects Python hyperlinks.
http://www.cetus-links.org/oo_python.html

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

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://aspn.activestate.com/ASPN/Cookbook/Python

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

leave

2005-03-24 Thread Jaco Smuts




I will be out of the office starting  2005/03/20 and will not return until
2005/04/02.

I will respond to your message when I return.
This email and all contents are subject to the following disclaimer:
http://www.clover.co.za/disclaimer;

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


Re: DBAPI Paramstyle

2005-03-24 Thread Fredrik Lundh
Bob Parnes wrote:

 I must be missing something, so perhaps someone can explain
 the benefit of a paramstyle over the usual Python formatting
 style and maybe suggest a test to show it. Thanks.

set the parameter to 0; DROP DATABASE template1; and see what
happens.

or set it to os.urandom(1000) and run your test a couple of times to see
what happens.

/F 



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


Re: Suggestions for a Java programmer

2005-03-24 Thread Ray
Hi Christos,

Christos TZOTZIOY Georgiou wrote:
 On 24 Mar 2005 00:22:09 -0800, rumours say that Ray
 [EMAIL PROTECTED] might have written:

 Searching google for python for java programmers (without the
quotes)
 produces:

 Python for Java programmers - Irmen's Python wiki

Yes, I feel that this wiki touches more on how Java compares to Python
(as opposed to how to *think* in Python). Maybe I should get the Python
Cookbook to  absorb more of the Python way of thinking, you think?

 Python  Java: Side by Side Comparison

This also compares Java  Python, the differences of which I am already
aware of.

 Jython Home Page (which you might like a lot)

Thanks, I've used it before, but I feel that I was using it to write
Java in Python

 dirtSimple.org: Python Is Not Java (some useful pointers)

This is the one I was referring to. I'm looking for something like this
(how some common idioms in Java is not the best way to do it in Python,
and how to do things the Python way).

Thanks!
Ray

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


Re: Suggestions for a Java programmer

2005-03-24 Thread Ray

bruno modulix wrote:
 These two books should help you to get a grasp of Pythonic idioms:

 http://www.mindview.net/Books/TIPython

Will read this later.

 http://diveintopython.org/

I just downloaded this one and am reading it now. Thanks bruno!




 --
 bruno desthuilliers
 python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')])
for 
 p in '[EMAIL PROTECTED]'.split('@')])

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


Re: Suggestions for a Java programmer

2005-03-24 Thread Ray

Ville Vainio wrote:
 Regarding a Java programmer moving to Python, a lot of the mindset
 change is about the abundant use of built in data types of Python. So
 a Java programmer, when confronted with a problem, should think how
 can I solve this using lists, dicts and tuples? (and perhaps also my
 new favourite, sets). Class-based solution should be chosen only
after
 seeing that the problem can't be trivially solved with built-in
types.

Hmmm, but isn't it the same as a Java programmer who's familiar with
the Collection Framework? (Which has list, dict (map), and set)?

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


Re: need help with nullmailer-inject in python cgi script to send attachements ?

2005-03-24 Thread Denis S. Otkidach
On 24 Mar 2005 05:20:06 -0800 [EMAIL PROTECTED] wrote:

TC Due to the restrictions I have at my host, I cannot use smtplib in
TC my email cgi script.  They gave me a script they use that calls
TC nullmailer-inject.   I am trying to figure out how to add the
TC ability to send attachments via the nullmailer-inject call.  I could
TC not find much documentation on google about nullmailer.  Has anyone
TC used it before to send attachments?   Here is function  I have so
TC far that sends a regular email.  The variables like recipient are
TC set from a cgi in another part of the script.
[...]
TC   mailfl=os.popen('/usr/bin/nullmailer-inject -f '+fromaddr,'w')
TC   mailfl.write('To: '+recipient+nl)
TC   if fromaddr: mailfl.write('From: '+fromaddr+nl)
TC   mailfl.write('Subject: %s%s\n\n'%(subject,uri))
TC   mailfl.write(intro)
TC   rx=0
TC   prev=''
TC   for x in cap:
TC while (rxlen(reql) and reql[rx]x):
TC   if reql[rx]prev:
TC putln(reql[rx],mailfl)
TC   rx=rx+1
TC putln(x,mailfl)
TC prev=x
TC 
TC   for x in envl:
TC mailfl.write('%s: %s\n'%(x,env[x]))
TC   mailfl.close()

Use email package. Something like the following (untested):

from email.MIMEText import MIMEText
msg = MIMEText(body)
msg['Subject'] = ...
msg['From'] = ...
msg['To'] = ...

from email.MIMEBase import MIMEBase
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(open(filename, 'rb').read())
attachment.add_header('Content-Disposition', 'attachment', 
  filename=filename)
from email.Encoders import encode_base64
encode_base64(attachment)
msg.attach(attachment)

# using popen is unsafe if we can't trust fromaddr, using subprocess
from subprocess import Popen, PIPE
mailfl = Popen(['/usr/bin/nullmailer-inject',  '-f', fromaddr],
   stdin=PIPE)
mailfl.stdin.write(msg.as_string())
mailfl.stdin.close()
mailfl.wait()

-- 
Denis S. Otkidach
http://www.python.ru/  [ru]
-- 
http://mail.python.org/mailman/listinfo/python-list


Convert the contents of a string into name of variable

2005-03-24 Thread Erwan VITIERE
Hello,
I want to convert the contents of a string into name of variable.
For example:

var1=toto
...
toto=5
print toto 


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


Re: need help with nullmailer-inject in python cgi script to send attachements ?

2005-03-24 Thread tvmaly
Thank you Denis

  Ty

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


Re: Python for a 10-14 years old?

2005-03-24 Thread Simon Brunning
On 23 Mar 2005 21:03:04 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Is there something out there like Python for kids which would explain
 *basic* programming concepts in a way which is accessible and
 entertaining for kids aged 10-14 (that about where her brain is right
 now) and which would allow them to play around and have fun solving
 small problems?

I don't know about kid's tutorials, but I can recommend that you try
the turtle module. It's great for kids. It gives really good immediate
feedback, You can start out using it interactively:

 import turtle
 turtle.forward(100)
 turtle.left(90)
 turtle.forward(100)
 turtle.left(90)
 turtle.forward(100)
 turtle.left(90)
 turtle.forward(100)
 turtle.left(90)

Then you can put this into a script, and run that. Then you might
introduce loops:

import turtle

for i in range(4):
turtle.forward(100)
turtle.left(90)

Then build some simple functions, like 'square':

def square():
for i in range(4):
turtle.forward(100)
turtle.left(90)

square()

Then add arguments to your functions:

def square(size):
for i in range(4):
turtle.forward(size)
turtle.left(90)

square(100)
square(50)

And so on. At each stage, you can see what's happening.

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedded python example: PyString_FromString doesnt work?

2005-03-24 Thread Brano Zarnovican
Hi David !

I cannot see anything wrong on your code. So, I'm posting my working
example.

Hint: try to determine, why it is returning NULL (the PyErr_Print()
call)

BranoZ


#include Python.h

int
main(int argc, char *argv[]) {
PyObject *s;
int ret;

if (argc  2)
return -1;

Py_Initialize();

s = PyString_FromString(argv[1]);
if (s == NULL) {
PyErr_Print();
return -1;
}
ret = PyObject_Print(s, stdout, 0);
Py_XDECREF(s);
if (ret  0) {
PyErr_Print();
return -1;
}

return 0;
}

$ cc test_String.c -o test_String -I /usr/include/python2.3 -lpython2.3
$ ./test_String
$ ./test_String hello
'hello'

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


Re: Simple account program

2005-03-24 Thread Kent Johnson
Igorati wrote:
ah thank you again. Anyone know of a good place to get information about TK
inter. I am gonna try and make this program somewhat of a GUI. Thank you
again.
http://docs.python.org/lib/module-Tkinter.html
http://www.pythonware.com/library/tkinter/introduction/index.htm
http://infohost.nmt.edu/tcc/help/pubs/tkinter/
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pattern matching from a text document

2005-03-24 Thread Ben

George Sakkis wrote:
 B
 Ben [EMAIL PROTECTED] wrote in message
 news:[EMAIL PROTECTED]
  I'm currently trying to develop a demonstrator in python for an
  ontology of a football team. At present all the fit players are
  exported to a text document.
 
  The program reads the document in and splits each line into a
string
  (since each fit player and their attributes is entered line by line
in
  the text document) using list = target.splitlines()
 
  [snipped]
 
  The program then performs a loop like so:
 
  The two main problems I'm having are that the first and entry in
the
  list is not printing. Once I have overcome this problem I then need
  each player and there related variables to be stored seperately.
This
  is not happening at present because each time the loop runs it
  overwrites the value in each variable.
 
  Any help would be greatly appreciated.
 
  Ben.


 Ben, can you post a sample line from the document and indicate the
fields you want to extract? I'm
 sure it will be easier to help you this way.

 George


 ~
 If a slave say to his master: You are not my master, if they
convict
 him his master shall cut off his ear.

 Hammurabi's Code of Laws
 ~

Below is a few sample lines. There is the name followed by the class
(not important) followed by 5 digits each of which can range 1-9 and
each detail a different ability, such as fitness, attacking ability
etc. Finally the preferred foot is stated.

Freddie Ljungberg   Player  02808right
Dennis Bergkamp Player  90705either
Thierry Henry   Player  90906either
Ashley Cole Player  17705left


Thanks for your help

ben

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


Re: Pattern matching from a text document

2005-03-24 Thread F. Petitjean
Le 24 Mar 2005 06:16:12 -0800, Ben a écrit :
 
 Below is a few sample lines. There is the name followed by the class
 (not important) followed by 5 digits each of which can range 1-9 and
 each detail a different ability, such as fitness, attacking ability
 etc. Finally the preferred foot is stated.
 
 Freddie Ljungberg Player  02808right
 Dennis Bergkamp   Player  90705either
 Thierry Henry Player  90906either
 Ashley Cole   Player  17705left
filename = 'players' # to adapt
players = {}  # mapping of name to abilities
fin = open(filename)
for line in fin:
firstname, lastname, type_, ability = line.split()
players[(lastname, firstname)] = Ability(ability)
fin.close()

where Ability can be e simple function which return processed the
information in the last word(string) of each line, or a class which
stores/manages such information
class Ability(object):
def __init__(self, ability):
digits = ability[:5]
self.details = map(int, list(digits)) # list of details
self.preferred_foot = ability[5:]
#  and so on 
 
 
 Thanks for your help
 
 ben
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exec src in {}, {} strangeness

2005-03-24 Thread Brano Zarnovican
As Greg pointed..

g = {}
exec open('t.py').read() in g, g

is what you want.

But you can write it also this way:
exec open('t.py').read() in {}

because if you specify only globals, the same
dictionary is also used for locals. (locals() is
used as a default only if you don't specify globals)

OR

explicitly move class Foo to globals

t.py contains:
globals Foo
class Foo: pass
class Bar:
 f = Foo 

(Should work. I haven't tried it, though)

BranoZ

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


escape single and double quotes

2005-03-24 Thread Leif B. Kristensen
I'm working with a Python program to insert / update textual data into a
PostgreSQL database. The text has single and double quotes in it, and I
wonder: What is the easiest way to escape quotes in Python, similar to
the Perlism $str =~ s/(['])/\\$1/g;?

I tried the re.escape() method, but it escapes far too much, including
spaces and accented characters. I only want to escape single and double
quotes, everything else should be acceptable to the database.
-- 
Leif Biberg Kristensen
http://solumslekt.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert the contents of a string into name of variable

2005-03-24 Thread Fredrik Lundh
Erwan VITIERE wrote:

 I want to convert the contents of a string into name of variable.
 For example:

 var1=toto
 ...
 toto=5
 print toto

why?

Python works better if you use it to write Python code.  the Python
solution is to use a dictionary:

key1 = toto

data = {}
data[toto] = 5

print data[key1]

/F 



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


Re: execfile() on file subclass or string

2005-03-24 Thread Brano Zarnovican
 exec compile(code, filename, exec)

Thanks for the tip!
Works great!

BranoZ

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


Re: Save passwords in scripts

2005-03-24 Thread beaststwo
I had a similar problem a few years ago and decided that if I really
had to store passwords, I could at least make them a bit harder to get
at.

I was using a the ConfigParser module to store other info in a config
file, so I added entries for the UserID and password to the config
file, as well as an indicator entry (yes/no).

Then I took all other values in the config file, put their info in a
delimited string (padded on both ends with a random number of
characters) and cleared the entries in the config file.  I used the old
Rotor module to encrypt the string, UUencoded the result and stored the
Rotor encrypted, UUencoded result in a special config entry.
UUencoding makes the encrypted entry usable converts unpritable
characters, rendering the entry usable in a config file.

The uptake was that if the indicator entry was no, the program read
the config file normally.  If the indicator entry was yes, the
program UUDecoded the special config entry, decrypted using the Rotor
module, parsed the string and used the results for config entries.

I also wrote a separate program to encrypt/decrypt the config file
entries so it could be modified in the clear and then reencrypted
afterward.

The system worked for me.  While the security is arguable, it was
certainly better than storing them in the clear.  I'm sure an astute
individual could figure out what I did and break it by analyzing the
source code, but it was quite effective for hiding info from the casual
observer.

While the Rotor module is been deprecated, I'm sure the same thing
could be done with any encryption module that can use file-like
objects.  I used Rotor because it was in the basic Python distribution,
and I didn't want to relay on external modules.

Hope it helps!

Tim Sharpe


Florian Lindner wrote:
 Peter Hansen wrote:

  Florian Lindner wrote:
  I've a scripts that allows limited manipulation of a database to
users.
  This script of course needs to save a password for the database
  connection. The users, on the other hand need read permission on
the
  script in order to execute it but should not be able to read out
the
  password. What is the common way to solve this problem?
 
  The common way is to do something ill-conceived and insecure.
 
  The correct approach is to use a secure technique that
  does not involve storing the passwords themselves, but
  instead storing a hash version of them (e.g. MD5 or SHA),
  or by requiring the users to enter their passwords at
  the time the information is required.

 Hashes could not work, since I need to give the password to a DB
server. My
 script is the client, not the server. It does not check passwords
supplied
 by the users, just use the hard-coded password to connect to the DB
server.

  My current way is to allow the users to execute the script with
sudo
  while not having read permission when acting as a ordinary user.
But I
  don't like this solutions and consider it very ugly.
 
  Storing passwords in the clear is always ugly and
  insecure.  Think about the situation where a user
  (unwisely) picks a password that he also uses for,
  say, his online banking.  If the password is stored
  in the clear, then anyone with root access can see
  it and even if you trust all your administrators,
  or are the only admin yourself, it's still not a
  good idea to let an admin see a user's password.

 It's not a users password. It's a password of a db user which owns
several
 system tables and the users should be able to manipulate them in a
 constrained manner.

 I fully agree with you. That's why I'm looking for a better, more
secure
 solution.
 
 Florian

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


Re: Getting the word to conventional programmers

2005-03-24 Thread beliavsky
Terry Reedy wrote:
 Cameron Laird [EMAIL PROTECTED] wrote in message

news:[EMAIL PROTECTED]
  *DevSource* profiles The State of the Scripting Universe in
  URL: http://www.devsource.com/article2/0,1759,1778141,00.asp .

 Interesting quote from Guido: If the same effort were poured into
speeding
 up Python as Sun devoted to Java, Python would be better than Java in
every
 respect.

Maybe companies such as Intel, IBM, and Sun would devote resources to
optimizing Python on their hardware if the language had an ISO
standard, as do C, C++, and Fortran, and were less of a moving target.
OTOH, that could slow the development of the language.

I have wondered why the dynamic languages such as Perl and Python
tend not to have ISO standards.

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


Re: Python for a 10-14 years old?

2005-03-24 Thread El Pitonero
Lucas Raab wrote:
 [EMAIL PROTECTED] wrote:
  I am blessed with a *very* gifted nine-years old daughter...
  Now, I would like to teach her programming basics using Python

 Let her mess around with it on her own. I'm 15 and have been using
 Python for 2-3 years and had nothing to really go on. Give her Dive
Into
 Python or How to Think Like a Computer Scientist and let her ask
 questions if she needs help.

In the chess world, people have long learnt to take young prodigies
seriously. Most of the grandmasters start to play chess at age 4 or
earlier. Bobby Fisher became the US chess champion at age 14, and a
grandmaster at 15. And that's considered old by modern standard: Sergei
Karjakin became grandmaster at age 12.

http://www.chessbase.com/newsdetail.asp?newsid=310
http://members.lycos.co.uk/csarchive/gilbert.htm

Sure, programming's skill set is a bit broader than chess playing or
ice-skating, but young hackers have plenty of contacts and resources
through internet, and many of them live (will be living) in Brazil,
Russia, India and China (the so-called BRIC countries.) So, a thorny
question for matured programmers is: what's your value in face of this
competition? :)

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


Re: escape single and double quotes

2005-03-24 Thread Damjan
 I'm working with a Python program to insert / update textual data into a
 PostgreSQL database. The text has single and double quotes in it, and I
 wonder: What is the easiest way to escape quotes in Python, similar to
 the Perlism $str =~ s/(['])/\\$1/g;?
 
 I tried the re.escape() method, but it escapes far too much, including
 spaces and accented characters. I only want to escape single and double
 quotes, everything else should be acceptable to the database.

You don't need to escape text when using the Python DB-API. 
DB-API will do everything for you.
For example:
 SQL = 'INSERT into TEMP data = %s'
 c.execute(SQL,  text containing ' and ` and all other stuff we might 
  read from the network)

You see, the SQL string contains a %s placeholder, but insetad of executing
the simple string expansion SQL % , I call the execute method
with the text as a second *parametar*. Everything else is magic :).





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


Re: IronPython 0.7 released!

2005-03-24 Thread Benjamin Niemann
Ville Vainio wrote:

 Robin == Robin Becker [EMAIL PROTECTED]
 writes:
 
 Robin well that's nice, but I don't do blogs and certainly don't
 
 You don't need to do much - just go to planetpython.org
 
Or check out the Daily Python URL (http://www.pythonware.com/daily/) which
has a pretty high signal to noise ratio.

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


Re: escape single and double quotes

2005-03-24 Thread Jiri Barton
Hey there,

str.replace('', '\\').replace(', \\')

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


Re: string join() method

2005-03-24 Thread Damjan
 but perhaps the webserver sanitizes the output of CGI script and converts
 plain \n into \r\n 

Yes apache does this, since it adds its own headers anyway it will replace
all '\n' in the headers with '\r\n' and '\n\n' with '\r\n\r\n'.


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


Why is a JIT compiler faster than a byte-compiler

2005-03-24 Thread RickMuller
I was talking to a friend of mine about the speed of Python code. One
of the questions that came up was why is a JIT compiler like Psyco
faster than the Python byte-compiler? I understand why languages like
Pyrex are faster, since they set static types that the compiler can use
to optimize. But why is Psyco faster? I would think that any
optimizations that Psyco makes could just as easily be made by the
byte-compiler, but obviously this is not the case, since Psyco runs
something like 4x faster, and I also understand that similar speedups
are seen by Java JIT compilers. What am I missing? Thanks in advance.

Rick

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


Re: escape single and double quotes

2005-03-24 Thread Leif B. Kristensen
Damjan skrev:

 You don't need to escape text when using the Python DB-API.
 DB-API will do everything for you.
 For example:
  SQL = 'INSERT into TEMP data = %s'
  c.execute(SQL,  text containing ' and ` and all other stuff we
  might
   read from the network)
 
 You see, the SQL string contains a %s placeholder, but insetad of
 executing the simple string expansion SQL % , I call the
 execute method with the text as a second *parametar*. Everything else
 is magic :).

Sure, but does this work if you need more than one placeholder? FWIW,
here's the whole script. It will fetch data from the table name_parts
and pump them into the denormalized table names ( a real SQL guru
would probably do the same thing with one single monster query):

import psycopg
from re import escape

connection = psycopg.connect(dbname=slekta, serialize=0)
sql = connection.cursor()

sql.execute(select * from name_parts)
result = sql.fetchall()
for row in result:
if row[2] == 1: # name part = 'prefix'
query = (update names set prefix='%s' where name_id=%s % \ 
   (escape(row[4]), row[1]))
elif row[2] == 2: # name part = 'given'
query = (update names set given='%s' where name_id=%s % \
   (escape(row[4]), row[1]))
elif row[2] == 3: # name part = 'surname'
query = (update names set surname='%s' where name_id=%s % \ 
   (escape(row[4]), row[1]))
elif row[2] == 4: # name part = 'suffix'
query = (update names set suffix='%s' where name_id=%s % \
   (escape(row[4]), row[1]))
elif row[2] == 5: # name part = 'patronym'
query = (update names set patronym='%s' where name_id=%s % \
   (escape(row[4]), row[1]))
elif row[2] == 6: # name part = 'toponym'
query = (update names set toponym='%s' where name_id=%s % \
   (escape(row[4]), row[1]))
sql.execute(query)
sql.commit()
connection.close()
-- 
Leif Biberg Kristensen
http://solumslekt.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


(no subject)

2005-03-24 Thread python-list-bounces+archive=mail-archive . com
#! rnews 2393
Newsgroups: comp.lang.python
Path: 
news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp
From: Harry George [EMAIL PROTECTED]
Subject: Re: Getting the word to conventional programmers
X-Nntp-Posting-Host: cola2.ca.boeing.com
Content-Type: text/plain; charset=us-ascii
Message-ID: [EMAIL PROTECTED]
User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.3
Lines: 43
Sender: [EMAIL PROTECTED]
Organization: The Boeing Company
References: [EMAIL PROTECTED] [EMAIL PROTECTED] [EMAIL PROTECTED] [EMAIL 
PROTECTED]
Mime-Version: 1.0
Date: Thu, 24 Mar 2005 15:58:17 GMT
Xref: news.xs4all.nl comp.lang.python:368964

Roose [EMAIL PROTECTED] writes:

  Except from a the standard, powerful,
  looks-good-everywhere-and-has-a-tree-widget GUI toolkit? :)
 
  Seriously, I think this is *very* important.
 
 Yes, and a modern toolset/IDE.  Generators and decorators and all that are
 nice, but their usefulness pales in comparison to having a decent IDE or GUI
 toolkit.
 
 Though I might disagree that Java has a good GUI toolkit, it has better
 tools than any language out there IMO.  And I don't really like Java
 personally.
 
 

Modern toolset/IDE?  Them's fightin' words. 

Since Babbage figured out stored programs and the transistor made them
viable, we have learned a crucial lesson: Whatever you want to think
about, make sure it can be programmed.  Do NOT require
human-in-the-loop.

From this perspective a mouse-driven GUI for generating code or GUI
designs is a horse-and-buggy concept.  Instead, a programmer uses
dynamic programming and (as needed) static code generation.  He/she
captures rules needed to generate appropriate GUIs and only
hand-tweaks the results when the rules cannot be fully understood
(artistic stylings).

Now, what is the best way to capture rules and algorithms?  It is a
powerful-yet-succinct language in an editor which supports a fast
think-edit-run cycle.  IDEs do a lot of things but generally don't win
this contest; text editors do.  Give me python in emacs any day.  Let
my Extreme Programming partner use whatever editor he/she likes, and
we'll refresh our editor buffers when we change chairs.  IDEs just gum
up the works.

-- 
[EMAIL PROTECTED]
6-6M21 BCA CompArch Design Engineering
Phone: (425) 294-4718
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Win 32 - VB, Ruby, Perl VS Python with fireEvent

2005-03-24 Thread calfdog
Roger,

Thank you so much! I have been pulling my hair out over this!

Rob.



Roger Upole wrote:
 I don't know why case would make a difference, but if I change
 the fireevent call to FireEvent, it works on XP sp2.
 It also works if you generate the makepy wrappers (probably
 because that forces case-sensitivity)

  hth
  Roger

 [EMAIL PROTECTED] wrote in message
 news:[EMAIL PROTECTED]
  Hello,
 
  I was wondering if anyone could tell me why fireEvent works in
every
  language but Python with the latest Internet Explorer?
 
  I tried this page that has two listboxes if you select  Listbox A
the
  Listbox B should change.
 
  The code status:
  Works fine with Python 2.3, 2.4 in Windows XPsp1
  DOES not work  Python 2.3, 2.4 XP Sp2 or the lastest IE
  Works fine with RUBY on Win 2000, XP sp1 and XP sp2
  Work fine with PERL on on Win 2000, XP sp1 and XP sp2
 
  Luckily I know both Ruby, VB and Perl so I could prove there was a
  problem.
 
  Here is the example code in both Python and Ruby:
 
  Python:
  from win32com.client import DispatchEx
  import time
 
 
 
 
  def wait(ie):
 while ie.Busy: time.sleep(0.1)
 
 doc = ie.Document
 while doc.ReadyState != 'complete': time.sleep(0.1)
 
  ie = DispatchEx('InternetExplorer.Application')
  ie.Visible = 1
  ie.Navigate( 'https://enroll.ou.edu/' )
  wait(ie)
  ie.Document.forms[0].campus.value='200'
  ie.Document.forms[0].campus.fireevent('onchange')
 
  Results:
  Traceback (most recent call last):
   File
 
C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py,
  line 310, in RunScript
 exec codeObject in __main__.__dict__
   File C:\automation\poScript1.py, line 18, in ?
 ie.Document.forms[0].campus.fireevent('onchange')
   File C:\Python23\lib\site-packages\win32com\client\dynamic.py,
line
  154, in __call__
 return
 
self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
  com_error: (-2147024891, 'Access is denied.', None, None)
 
 
 
 
 
  Ruby:
  # OU Registration  Enrollment Online
  require 'win32ole'
  ie = WIN32OLE.new('InternetExplorer.Application')
  ie.visible = true
  ie.gohome
  ie.navigate('https://enroll.ou.edu/')
  while ie.busy
  end
 
  READYSTATE_COMPLETE = 4
  until
   ie.readyState == READYSTATE_COMPLETE
  end
  form = ie.document.forms(0)
  form.campus.value = '200'
  form.campus.fireevent('onchange')
 
  Results: fireEvent was successful and the second listbox was
changed
 




 == Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet
News==
 http://www.newsfeeds.com The #1 Newsgroup Service in the World!
100,000 Newsgroups
 ---= East/West-Coast Server Farms - Total Privacy via Encryption =---

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


Re: possible bug?

2005-03-24 Thread Earl Eiland
There may be different ways to code it.  This works.  The problem is
that occasionally somehow, WinRK terminates without terminating the
process, or at least Python doesn't pick up the return code. It turns
out that using poll() instead of wait() only reduces the error
frequency, and allows me to recover from the failure.  It doesn't
eliminate it.

Earl

 On Thu, 2005-03-24 at 00:16, Tim Roberts wrote:
 Earl Eiland [EMAIL PROTECTED] wrote:
 
 I'm running the following code on Windows 2000, 5.00.2195:
 
 for x in Files:
  Command_String = 'C:\Program Files\WinRK\WinRK.exe -create ' +
 
 That can't be right.  You need either
   Command_String = 'C:\\Program Files\\WinRK\\WinRK.exe -create ' +
 or
   Command_String = r'C:\Program Files\WinRK\WinRK.exe -create ' +
 -- 
 - Tim Roberts, [EMAIL PROTECTED]
   Providenza  Boekelheide, Inc.

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


An Abridged Python Tutorial

2005-03-24 Thread Michael Spencer
An Abridged Python Tutorial
There are tips for the novice and tricks
that will add to your programming kicks.
But the cardinal rule
that you must learn at school
is that spaces and tabs never mix.
If there's syntax you don't understand,
assistance is always at hand:
a glance at the cookbook,
or even a quick look
at the manual should meet the demand.
If you code without reading this doc,
you may find yourself in for a shock,
due to Python's aversion
to boundless recursion
or the global interpreter lock.
The immutable types, such as int,
can be subclassed, but follow this hint:
you must override __new__
'cause __init__ does not do -
if you try it you'll find that it didn't.
Now that functional style is passe,
filter, map and reduce go away.
Better use comprehensions
to convey your intentions
(or itertools.chain is OK).
If today's Python code doesn't suit ya,
don't despair or attack your computer.
If the time machine's on,
then your problem's soon gone:
just import what you need from the __future__.
When you harbour a yen to invent,
then a PEP should ideally be sent.
But know this in advance
your idea has no chance
should the BDFL not consent
If you find this account is amiss,
please avoid the temptation to hiss.
Simply offer a patch,
to apply with dispatch
and if you seek Zen, import this!
Michael
--
http://mail.python.org/mailman/listinfo/python-list


ANN: Twisted version 2.0

2005-03-24 Thread Christopher Armstrong
http://twistedmatrix.com/

TASMANIA (DP) -- Found on the Internet on 2005-03-22 by an anonymous
programmer, Twisted 2.0 was obtained by local authorities and kept
isolated for public safety and further study.  On 2005-03-25, however,
nano-probes were released from the package's surface and propagated
the software to the public.

Version 2.0 is said to have originated from ancient underground ruins
somewhere in Australia, but their existence has not yet been verified.
Christopher Armstrong, enslaved release archaeologist, was only able
to say Aieeya!  Release??  What release?  I just found this here
tablet under some sand.  Ia!  Project lead Glyph Lefkowitz was not
available for comment, as he has fled the planet in fear of the
repercussions of the software's new release.

Record-keeper Mary Gardiner said It will be interesting to see if the
Twisted Sumo distribution collapses into a singularity.  I guess
there's a potential that Earth will be destroyed.

As of this release, radix's soul, which has been included in Twisted
since version 0.8.0, has been split off from the main project and
given back to him to maintain in a separate sub-project.



Twisted 2.0 is a major upgrade, changing many things not only in the
code but also in the structure of the project.  As of 2.0, Twisted was
split up into many sub-projects which you can read about in the
Twisted Split FAQ[1].

2.0 also marks the first release including the migration to the Zope
Interface framework as opposed to Twisted's own built-in
interface/adapter system.  Another FAQ was made available[2] for those
curious about the change.

Many, tons, and lots of other changes have been made in this release.
The NEWS[3] file contains a high-level overview of most of these
changes.  Changes in now-split subprojects are available on their
individual project pages[4].

Tarballs are currently available at the twistedmatrix.com site, and
packages for win32, Debian, and other OSes are currently on the way.

1: http://twistedmatrix.com/projects/core/documentation/upgrades/2.0/split.html
2: 
http://twistedmatrix.com/projects/core/documentation/upgrades/2.0/components.html
3: http://twistedmatrix.com/projects/core/NEWS.txt
4: http://twistedmatrix.com/projects/


WHAT IS TWISTED?

Twisted is an event-based framework for internet applications which
works on Python 2.2.X and 2.3.X.  The following are the (important)
modules included with Twisted:

  - twisted.application
A Service system that allows you to organize your application in
hierarchies with well-defined startup and dependency semantics,
  - twisted.cred
A general credentials and authentication system that facilitates
pluggable authentication backends,
  - twisted.enterprise
Asynchronous database access, compatible with any Python DBAPI2.0
modules,
  - twisted.internet
Low-level asynchronous networking APIs that allow you to define
your own protocols that run over certain transports,
  - twisted.manhole
A tool for remote debugging of your services which gives you a
Python interactive interpreter,
  - twisted.protocols
Basic protocol implementations and helpers for your own protocol
implementations,
  - twisted.python
A large set of utilities for Python tricks, reflection, text
processing, and anything else,
  - twisted.spread
A secure, fast remote object system,
  - twisted.trial
A unit testing framework that integrates well with Twisted-based code.


Twisted supports integration of the Tk, GTK+, GTK+ 2, Qt, Mac OS X, or
wxPython event loop with its main event loop. The Win32 event loop is
also supported.

For more information, visit http://www.twistedmatrix.com, or join the
list at
http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python

There are many official Twisted subprojects, including clients and
servers for web, mail, DNS, and more. You can find out more about
these projects at http://twistedmatrix.com/projects/



-- 
  Twisted   |  Christopher Armstrong: International Man of Twistery
   Radix|-- http://radix.twistedmatrix.com
|  Release Manager, Twisted Project
  \\\V///   |-- http://twistedmatrix.com
   |o O||  Founding Member, Hobart Hacking Society
wvw-+-- http://hackingsociety.org/chapters/hash
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert the contents of a string into name of variable

2005-03-24 Thread Erwan VITIERE
Because i don't want to use this syntax because it is too long, I want a 
direct access :

Not :
DicoUser['TOTO'].DicoTable.['MY_TABLE'].DicoLabel.['MY_LABEL']  =  for 
exemple

Finally, i want to use :
TOTO.MY_TABLE.MY_LABEL = for exemple

Fredrik Lundh [EMAIL PROTECTED] a écrit dans le message de news: 
[EMAIL PROTECTED]
 Erwan VITIERE wrote:

 I want to convert the contents of a string into name of variable.
 For example:

 var1=toto
 ...
 toto=5
 print toto

 why?

 Python works better if you use it to write Python code.  the Python
 solution is to use a dictionary:

key1 = toto

data = {}
data[toto] = 5

print data[key1]

 /F

 


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


Re: Why is a JIT compiler faster than a byte-compiler

2005-03-24 Thread dodoo
http://www-900.ibm.com/developerworks/cn/linux/sdk/python/charm-28/index_eng.shtml

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


Re: Why is a JIT compiler faster than a byte-compiler

2005-03-24 Thread RickMuller
Thanks for the link. That completely answers my question.

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


Re: Anonymus functions revisited : tuple actions

2005-03-24 Thread George Sakkis
Kay Schluehr [EMAIL PROTECTED] wrote:
 [snipped]

 Wouldn't it be fun to use in Python?

 Only drawback: does not look like executable pseudo-code anymore :(


 Regards Kay

I don't know if it would be fun, but it certainly doesn't look accessible to 
mere mortals :-) I'm
not sure if the mind boggling is more due to the syntax with the '-' and all 
or the semantics, but
it goes in the oppposite direction from my initial proposal (having defaults in 
for loops) with
respect to readability.

Regards,
George


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


Re: Python limericks (was Re: Text-to-speech)

2005-03-24 Thread smitty_one_each

Michael Spencer wrote:
 How about a category for executable limericks?

 Here's one to get the ball rolling:


 # voice only the alphanumeric tokens

 from itertools import repeat
 for feet in [3,3,2,2,3]:
  print  .join(DA-DA-DUM
  for dummy in [None]
 for foot in repeat(metric, feet))



 Michael


 P.S. I know 'three' doesn't rhyme.

Well, don't be so harsh on yourself.
You get a weak correlation between the 'ee' in 3 and the ('eat','eet')
tuple, based on assonance.  
Good work.

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


Re: possible bug?

2005-03-24 Thread Peter Hansen
Earl Eiland wrote:
There may be different ways to code it.  This works.  
You're right about that, *as the code now stands*.
The danger is that you are using single backslashes.
The *only* reason this works right now is because none
of the characters you have following those backslashes
happen to be part of reserved escape sequences.  See
http://docs.python.org/ref/strings.html to learn why
Tim is basically right, even though in this case you
are getting away with it...
(Yes, I know this doesn't solve the real problem.)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: An Abridged Python Tutorial

2005-03-24 Thread George Sakkis
Michael Spencer [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 An Abridged Python Tutorial

 There are tips for the novice and tricks
 that will add to your programming kicks.
  But the cardinal rule
  that you must learn at school
 is that spaces and tabs never mix.

 If there's syntax you don't understand,
 assistance is always at hand:
  a glance at the cookbook,
  or even a quick look
 at the manual should meet the demand.

 If you code without reading this doc,
 you may find yourself in for a shock,
  due to Python's aversion
  to boundless recursion
 or the global interpreter lock.

 The immutable types, such as int,
 can be subclassed, but follow this hint:
  you must override __new__
  'cause __init__ does not do -
 if you try it you'll find that it didn't.

 Now that functional style is passe,
 filter, map and reduce go away.
  Better use comprehensions
  to convey your intentions
 (or itertools.chain is OK).

 If today's Python code doesn't suit ya,
 don't despair or attack your computer.
  If the time machine's on,
  then your problem's soon gone:
 just import what you need from the __future__.

 When you harbour a yen to invent,
 then a PEP should ideally be sent.
  But know this in advance
  your idea has no chance
 should the BDFL not consent

 If you find this account is amiss,
 please avoid the temptation to hiss.
  Simply offer a patch,
  to apply with dispatch
 and if you seek Zen, import this!


 Michael


Outstanding ! Great piece Michael :-)

George


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


Bug in threading.Thread.join() ?

2005-03-24 Thread Peter Hansen
I'm still trying to understand the behaviour that I'm
seeing but I'm already pretty sure that it's either
a bug, or something that would be considered a bug if
it didn't perhaps avoid even worse behaviour.
Inside the join() method of threading.Thread objects,
a Condition named self.__block is acquired, and then
the wait logic is executed.  After the wait() finishes,
self.__block is released and the method returns.
If you hit Ctrl-C while the join's wait() is occurring,
you'll raise a KeyboardInterrupt and bypass the
release() call.  (I'm observing this on Win XP with
Python 2.4 but have no reason to think it wouldn't
work the same on other platforms, given the docs
on signals and such.)  If you do this, the thread
you were waiting for will never be able to complete
its cleanup because __bootstrap() calls __stop()
and that tries to acquire the same Condition object,
which has never been released.  (I suspect this will
happen only if its the MainThread that is doing
the join() call since KeyboardInterrupts only occur
in the main thread.)
A simple try/finally in join() appears to solve the
problem, but I'm unsure that this is a good idea,
partly because I'm a little surprised nobody else has
found this problem before and I lack confidence that
I've really found a bug.
Anyone have thoughts on this?  I'll file a bug
report shortly unless someone can point out the
error in my reasoning or a reason why this must be
the way it is.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: escape single and double quotes

2005-03-24 Thread Scott David Daniels
Leif B. Kristensen wrote:
Damjan skrev:
For example:
SQL = 'INSERT into TEMP data = %s'
c.execute(SQL,  text containing ' and ` and all other stuff we
might read from the network)

Sure, but does this work if you need more than one placeholder? 
Yup.
FWIW,
here's the whole script. It will fetch data from the table name_parts
and pump them into the denormalized table names ( a real SQL guru
would probably do the same thing with one single monster query):
import psycopg
from re import escape
connection = psycopg.connect(dbname=slekta, serialize=0)
cursor = connection.cursor()
cursor.execute(select * from name_parts)
result = cursor.fetchall()
kind = 'prefix', 'given', 'surname', 'suffix', 'patronym', 'toponym'
for row in result:
if 0  row[2] = 6:
 cursor.execute(update names set  + kind[row[2] - 1] +
  = %s where name_id = %s,
 (row[4], row[1]))
cursor.commit()
connection.close()
1) I would prefer SELECT name_id, part, name FROM name_parts, rather
   than relying on * to return the field names in an expected order
   and size as your database evolves.  I generally do SQL keywords in
   all-caps as documentation for those reading the code later.
2) I suspect that last line of the second execute might need to be:
 [(row[4], row[1])])
   I don't really remember; I'd just try both and see which works.
3) It is not really clear to when you want to do the commits.
   I might be tempted to do the first query with ORDER BY name_id
   and do a commit after each distinct name_id is finished.  This
   strategy would keep data for individuals coherent.
4) In fact, I'd leave the data in the database.  Perhaps more like a
   set of queries like:
UPDATE names
   SET names.prefix = name_parts.name
   FROM name_parts
   WHERE names.name_id = name_parts.name_id
 AND name_parts.name_kind = 1
You really need to think about commits when you adopt this strategy.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python for a 10-14 years old?

2005-03-24 Thread Scott David Daniels
Christos TZOTZIOY Georgiou wrote:
For example, one could issue the following *single* instruction:
MOVE.L ($18000), ($18004)
But the cost of that design is that the machine state becomes more
complicated -- the instruction has to have two distinct memory ops.
Usually this means there is a secret register for the moving data,
and a first part done part of executing the opcode.
Modern RISC-structured machines have at most one memory operation,
so the instruction is simply completed or not, and can safely be
re-executed if it is not complete.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Data types

2005-03-24 Thread waqar
What are the user defined types in Python? Can we call lists, tuples 
dictionaries user-defined data types?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anonymus functions revisited

2005-03-24 Thread Ron
On 24 Mar 2005 09:20:52 GMT, Duncan Booth
[EMAIL PROTECTED] wrote:

Ron wrote:

 A working makeVars seems not to be different from
 
 def makeVars(**nameVals):
globals().update(nameVals)

Not quite. If Ron can come up with a working makeVars it would update
the caller's globals whereas what you just posted updates makeVar's
globals so there is a difference (when the makeVars and the calling
function are in different modules), just not a very useful one.
 
 How about this one?   The only reliable way I found to do it is to
 pass locals() to the function.

Yes, but you are still missing the fundamental point. The locals() 
dictionary is not guaranteed to do anything useful if you update it. The 
current C implementation will reflect changes in the locals dictionary if 
you call locals() from global scope or in a few other circumstances, but 
this is simply an implementation detail.

Nope, Didn't miss the point.  The functions return a value, not create
it from within.

If you want to update global variables then use globals() or setattr on the 
module. Only use locals() to access local variables indirectly, never to 
try and set them.

Good advise. :)

One of pythons weak points is it is sometimes difficult to 'monitor
and confirm' what is happening leading to confusing try/except
constructions.

Having the function is_defined() and if_not_defined() have the
advantage that they can be use in expressions where try/except can't.
And the source code could be more compact and more readable. 

The disadvantage is the functions are quite a bit slower than
try/except, probably due to the function call over head.

If they were built in, they may be as fast as the try/except and there
wouldn't be issues with having to passing locals() or globals() name
dictionaries.


It's interesting that there is a whole is_type_() group of functions
in the inspect module, but not a is_defined().  Maybe I just haven't
found it yet.


#

def if_not_defined(v, dv=None, lv=locals()):
if lv.has_key(v):
return lv[v]
return dv

def is_defined(v, lv=locals()):
if lv.has_key(v):
return True
False

# Shorten names and pass locals() with lambas for 
# convenience.   (This needs to be in the function 
# where they are used or it will break.  
# Another use for lamba!   ;)

ifnd = lambda v, dv, lv=locals(): if_not_defined(v,dv,lv)
isa = lambda v, lv=locals(): is_defined(v, lv)

# Totally useless routine. ;)
import random
for n in range(10):

# Delete a random x,y,z coordinate to
# simulate an unreliable data source. 
d = random.choice([1,2,3])
if d==1:
if isa('x'): del x
elif d==2:
if isa('y'): del y
else:
if isa('z'): del z

# Replace the missing variable with a random number.
r = int(random.random()*100)
x, y, z = ifnd('x',r), ifnd('y',r), ifnd('z',r)
print x, y, z 

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


Re: string join() method

2005-03-24 Thread Kent Johnson
Derek Basch wrote:
Can anyone tell me why this CGI code outputs a blank page?
Maybe because it needs a blank line between the header and the body?

self.output = []
self.setContentType(text/plain)
ascii_temp.seek(0)
self.output.extend(ascii_temp.read())
self.output.append() is probably what you mean. Try this:
self.output.append('\r\n')
self.output.append(ascii_temp.read())
print ''.join(self.output)
def setContentType(self, type=text/xml):
self.output.extend([Content-type: , type, \n\r])
-
but this code works?:
-
self.output = []
self.setContentType(text/plain)
print ''.join(self.output)
The above line will create a blank line because of the extra newline from print.
Kent
ascii_temp.seek(0)
print ascii_temp.read()
def setContentType(self, type=text/xml):
self.output.extend([Content-type: , type, \n\r])
-
ascii_temp is just some tab seperated data:
-
Allele  Seq:Start-End   Length  SequenceScore
A01 1: 1-8  8   1410538.0
A01 1: 2-9  8   1410538.0
-
Thanks everyone.
Derek Basch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting the word to conventional programmers

2005-03-24 Thread Cameron Laird
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:
.
.
.
Maybe companies such as Intel, IBM, and Sun would devote resources to
optimizing Python on their hardware if the language had an ISO
standard, as do C, C++, and Fortran, and were less of a moving target.
OTOH, that could slow the development of the language.

I have wondered why the dynamic languages such as Perl and Python
tend not to have ISO standards.


There's a LOT to say on the subjects you raise.  It might be a while
before anyone with a background in the appropriate areas tackles them.
Perhaps we'll return to this ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: escape single and double quotes

2005-03-24 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Leif B. Kristensen wrote:

 Damjan skrev:
 
 You don't need to escape text when using the Python DB-API.
 DB-API will do everything for you.
 For example:
  SQL = 'INSERT into TEMP data = %s'
  c.execute(SQL,  text containing ' and ` and all other stuff we
  might
   read from the network)
 
 You see, the SQL string contains a %s placeholder, but insetad of
 executing the simple string expansion SQL % , I call the
 execute method with the text as a second *parametar*. Everything else
 is magic :).
 
 Sure, but does this work if you need more than one placeholder?

Yes it works with more than one placeholder.

 FWIW,
 here's the whole script. It will fetch data from the table name_parts
 and pump them into the denormalized table names ( a real SQL guru
 would probably do the same thing with one single monster query):
 
 import psycopg
 from re import escape
 
 connection = psycopg.connect(dbname=slekta, serialize=0)
 sql = connection.cursor()
 
 sql.execute(select * from name_parts)
 result = sql.fetchall()
 for row in result:
 if row[2] == 1: # name part = 'prefix'
 query = (update names set prefix='%s' where name_id=%s % \ 
(escape(row[4]), row[1]))
 elif row[2] == 2: # name part = 'given'
 query = (update names set given='%s' where name_id=%s % \
(escape(row[4]), row[1]))
 elif row[2] == 3: # name part = 'surname'
 query = (update names set surname='%s' where name_id=%s % \ 
(escape(row[4]), row[1]))
 elif row[2] == 4: # name part = 'suffix'
 query = (update names set suffix='%s' where name_id=%s % \
(escape(row[4]), row[1]))
 elif row[2] == 5: # name part = 'patronym'
 query = (update names set patronym='%s' where name_id=%s % \
(escape(row[4]), row[1]))
 elif row[2] == 6: # name part = 'toponym'
 query = (update names set toponym='%s' where name_id=%s % \
(escape(row[4]), row[1]))
 sql.execute(query)
 sql.commit()
 connection.close()

A lot of redundant code.  Try something like the following instead of the
``elif`` sequence::

name_part = ['prefix', 'given', 'surname', 'suffix', 'patronym', 'toponym']
for row in result:
query = 'update names set %s=%%s where name_id=%%s' % name_part[row[2]-1]
sql.execute(query, (row[4], row[1]))
sql.commit()

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


Re: Data types

2005-03-24 Thread Lonnie Princehouse
Lists, tuples, and dictionaries are built-in types.
Classes are the mechanism for user-defined types in Python.

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


  1   2   >