py lib 0.9.0: py.test, distributed execution, microthreads ...

2007-02-14 Thread holger krekel
py lib 0.9.0: py.test, distributed execution, greenlets and more
==

Welcome to the 0.9.0 py lib release - a library aiming to 
support agile and test-driven python development on various levels. 

Main API/Tool Features: 

* py.test: cross-project testing tool with many advanced features
* py.execnet: ad-hoc code distribution to SSH, Socket and local sub processes
* py.magic.greenlet: micro-threads on standard CPython (stackless-light)
* py.path: path abstractions over local and subversion files 
* rich documentation of py's exported API 
* tested against Linux, OSX and partly against Win32, python 2.3-2.5

All these features and their API have extensive documentation,
generated with the new apigen, which we intend to make accessible
for other python projects as well.  

Download/Install:   http://codespeak.net/py/0.9.0/download.html
Documentation/API:  http://codespeak.net/py/0.9.0/index.html

Work on the py lib has been partially funded by the 
European Union IST programme and by http://merlinux.de 
within the PyPy project. 

best, have fun and let us know what you think!

Holger Krekel, Maciej Fijalkowski, 
Guido Wesdorp, Carl Friedrich Bolz

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

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


Re: calling php function from python

2007-02-14 Thread Rob Wolfe

mark wrote:
 is it possible to call a php function from python and use a class from
 php in python? i want to use mmslib which creates mms messages and the
 only implementation is a php mmslib implementation.

You can consider to use some kind of RPC (remote procedure call)
for example XML-RPC. This is a platform and language independent
solution.
Here you have some information:
http://www.faqs.org/docs/Linux-HOWTO/XML-RPC-HOWTO.html
http://groups.google.pl/group/comp.lang.python/msg/5a6ae6290593fc97

--
HTH,
Rob

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


Re: python not returning true

2007-02-14 Thread Terry Reedy

John Machin [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

| On Feb 14, 5:45 pm, agent-s [EMAIL PROTECTED] wrote:
|  btw Steven you are so witty I hope to one day pwn noobs on newsgroups
|  too.

Sorry, but you are 'pwning' yourself here ;-)

| Wit has nothing to do with it. The fact that you are a Python noob is
| also irrelevant. Your problem statement was unintelligible, as is your
| response. What does pwn mean?

I believe that it is a misspelling of 'own' used by pvp (person versus 
person, as opposed to person versus monster) gamers to demonstrate their 
in-ness.  But perhaps agent-s can enlightenment us further.

Terry Jan Reedy (occasional, non-elite gamer) 



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


Re: python not returning true

2007-02-14 Thread Paul Rubin
John Machin [EMAIL PROTECTED] writes:
 What does pwn mean?

http://en.wikipedia.org/wiki/Pwn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fast constant functions for Py2.5's defaultdict()

2007-02-14 Thread Raymond Hettinger
On Feb 13, 5:09 pm, Giovanni Bajo [EMAIL PROTECTED] wrote:
  The itertools.repeat(const).next approach wins on speed and
  flexibility.

 But it's the most unreadable too.

Not really.  It's unusual but plenty readable (no surprise that
repeat(0) repeatedly gives you zero).  I think it more surprising that
int() with no arguments gives you a zero.

 I'm surprised that defaultdict(int) is
 slower than the lambda one though. What's the reason?

All that comes to mind is that int() has to call
PyArg_ParseTupleAndKeywords() while the lambda is unburdened by
argument passing.


Raymond


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


Re: Recursive calls and stack

2007-02-14 Thread Gabriel Genellina
En Wed, 14 Feb 2007 04:23:46 -0300, [EMAIL PROTECTED]  
[EMAIL PROTECTED] escribió:

 I am OK with calls being stacked, but I wondering will the local
 variables be stacked given that return statement is followed by the
 function call?

 def test():
   x = 22
   y = 33
   z = x+y
   return anotherFunction(z)

 In this function will all the local variables (x,y,z) be pushed into
 the stack before calling anotherFunction(z) or Python will find out
 that the locals are no longer needed as anotherFunction(z) is just
 returned?

Not exactly like pushed into the stack, but there exists a frame object,  
and it contains references to its local variables, and will be alive until  
anotherFunction returns. From inside anotherFunction you can even inspect  
those variables:

py def test():
...   x = 22
...   y = 33
...   z = x+y
...   return anotherFunction(z)
...
py def anotherFunction(z):
...   print previous frame:, sys._getframe(1).f_locals
...
py test()
previous frame: {'y': 33, 'x': 22, 'z': 55}

So x,y,z will still be there until anotherFunction actually returns to  
test, and the frame object is disposed. For a highly recursive function,  
that's bad news. For debugging normal programs, that's good news; the  
cgitb module, by example, is able to show the values for local variables  
in all previous frames when an exception is raised.

-- 
Gabriel Genellina

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


Re: Recursive calls and stack

2007-02-14 Thread [EMAIL PROTECTED]
On Feb 14, 11:09 am, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 Hi,
  I have a program which literately finds the object that overlapping a
 point. The horizontal and vertical search are called recursively from
 inside each other.
  Is this way of implementation fill thestackspace with the local
 variables inside eachcall. If this is not good, is there a better way
 to implement? Orpythonitself will understand that the calls happen
 in the last line, so local variables need not be pushed into thestack?

 def find_point(pt):
 return _hor_search(pt, random_obj)

 def _hor_search(pt, obj):
 ...
 object = ...
 ...
 if object meets some condition:
 return object
 else:
 return _ver_search(pt, object)

 def _ver_search(pt, obj):
 ...
 object = ...
 ...
 if object meets some condition:
 return object
 else:
 return _hor_search(pt, object)

 -
 Suresh

I found a simpler solution: get rid of recursive calls; using while
loops.

-
Suresh

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


Re: Recursive calls and stack

2007-02-14 Thread Terry Reedy

[EMAIL PROTECTED] [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
I am OK with calls being stacked, but I wondering will the local
variables be stacked given that return statement is followed by the
function call?

def test():
  x = 22
  y = 33
  z = x+y
  return anotherFunction(z)

In this function will all the local variables (x,y,z) be pushed into
the stack before calling anotherFunction(z) or Python will find out
that the locals are no longer needed as anotherFunction(z) is just
returned?
=
To add to Gabriel's answer:

Questions of this sort are implementation specific.  CPython will allocate 
the objects on the heap.  But I believe at present something will go on the 
C stack with each function call.  I suspect that the C array that typically 
implements the local namespace is included but don't specifically know. 
The local names are deleted, and the associated heap objects released if 
that make the reference count 0, as part of the return process.  No 
optimization of the sort you indicate is done.  Indeed, the heap objects 
could have other references, and the namespace array is fixed size, so I am 
not sure there is anything that could, in general, be done.  In any case, 
Python never deletes without at least implicit instruction to do so.

The maximun recursion depth CPython will attempt is governed by an internal 
variable that you can get and set to adjust to your problem and hardware:

 sys.getrecursionlimit()
1000
 sys.setrecursionlimit(500)
 sys.getrecursionlimit()
500

Terry Jan Reedy




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


Re: _ssl.pyd is buggy?

2007-02-14 Thread Giles Brown
On 14 Feb, 00:17, Giles Brown [EMAIL PROTECTED] wrote:
 Something I always found useful is to use the win32traceutil to set up
 the trace debugging tool.
 You can then see the output in the pythonwin trace collector tool.
 This is very useful for
 Python services and COM servers.

 Best of luck,
 Giles

Eh?  Wrong thread. Damn the new google groups interface!

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


Re: Fast constant functions for Py2.5's defaultdict()

2007-02-14 Thread Michele Simionato
On Feb 14, 9:11 am, Raymond Hettinger [EMAIL PROTECTED] wrote:
 On Feb 13, 5:09 pm, Giovanni Bajo [EMAIL PROTECTED] wrote:

   The itertools.repeat(const).next approach wins on speed and
   flexibility.

  But it's the most unreadable too.

 Not really.  It's unusual but plenty readable (no surprise that
 repeat(0) repeatedly gives you zero).  I think it more surprising that
 int() with no arguments gives you a zero.

Well, if I was doing code review of some of my coworkers I would ask
them
to use them int if the constant was zero and lambda otherwise. If they
wanted
to use itertools.repeat(const).next they should prove me that the
speed
increase is absolutely significant in their actual use case and
they should put a big comment in the code explaining why they
preferred
the cryptic defaultdict(itertools.repeat(0).next) over the obvious
defaultdict(int).

 Michele Simionato

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


Re: calling php function from python

2007-02-14 Thread Benjamin Niemann
Rob Wolfe wrote:

 
 mark wrote:
 is it possible to call a php function from python and use a class from
 php in python? i want to use mmslib which creates mms messages and the
 only implementation is a php mmslib implementation.
 
 You can consider to use some kind of RPC (remote procedure call)
 for example XML-RPC. This is a platform and language independent
 solution.
 Here you have some information:
 http://www.faqs.org/docs/Linux-HOWTO/XML-RPC-HOWTO.html
 http://groups.google.pl/group/comp.lang.python/msg/5a6ae6290593fc97

For a quickstart it's probably easier to run the PHP code using the CGI
version of the PHP interpreter. E.g.
os.system('/usr/bin/php mms.php')
or using the subprocess module, if you want to pass some data to the script
(using stdin/out).

As long as no remote PHP server is involved this is easier and perhaps even
faster than the RPC approach...

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


Re: python not returning true

2007-02-14 Thread John Machin
On Feb 14, 7:02 pm, Terry Reedy [EMAIL PROTECTED] wrote:
 John Machin [EMAIL PROTECTED] wrote in message

 news:[EMAIL PROTECTED]

 | On Feb 14, 5:45 pm, agent-s [EMAIL PROTECTED] wrote:
 |  btw Steven you are so witty I hope to one day pwn noobs on newsgroups
 |  too.

 Sorry, but you are 'pwning' yourself here ;-)

And the referent of you would be .?


 | Wit has nothing to do with it. The fact that you are a Python noob is
 | also irrelevant. Your problem statement was unintelligible, as is your
 | response. What does pwn mean?

 I believe that it is a misspelling of 'own' used by pvp (person versus
 person, as opposed to person versus monster) gamers to demonstrate their
 in-ness.  But perhaps agent-s can enlightenment us further.

So enlightenment has been verbed, has it? I didn't realise that the
language had been transitioned so far :-)

Cheers,
John

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


Re: python not returning true

2007-02-14 Thread Michael Bentley

On Feb 14, 2007, at 3:08 AM, John Machin wrote:

 So enlightenment has been verbed, has it? I didn't realise that the
 language had been transitioned so far :-)

*ALL* nouns may be verbed ;-)

-michael
---
# Something just doesn't seem right in those
# Every kiss begins with 'K' commercials.

  'Every Kiss'.startswith('K')
False




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


Re: c++ for python programmers

2007-02-14 Thread Anders Arnholm
Sam [EMAIL PROTECTED] skriver:
 On 13 Feb 2007 17:51:00 GMT, Jorgen Grahn
[EMAIL PROTECTED] wrote:
 Well, C++ is a better language than C in many ways. So, if he needs to learn
 one of them, why does it have to be C?

 Another reason some people choose C++ over Python for some tasks is that
 they feel that larger programs benefit from strong, static type checking.
 I like both ways, but depending on the task, one or the other is better.

 C++ is -not- strongly typed. You can cast anything to void *, and
 manipulate it in ways unimaginable. Plus there's the whole mess that
 is pointer arithmetic and a weak typesystem...


C++ can be both, The type systenm is as fragila as you like it to be.
I mainlty use c++ when i the need stronger typing that Python och C
can't give me. In some ways it's even stronger types than languanges
as Java and ObjectiveC. C++ it however at least four different
languanges, in one ball of soupe.

And yes you can do it, that doesn't mean you have to dio it. As
_functions in python or __, you can use them from anyware, you don't
have to.

/ Balp


-- 
http://anders.arnholm.nu/Keep on Balping
-- 
http://mail.python.org/mailman/listinfo/python-list


[no subject]

2007-02-14 Thread 3174965380
(dancing stripper on your dekstop free) 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Segmentation faults using threads

2007-02-14 Thread Mathias
 
 What module are you using for SSH?
 
 What's in your program that isn't pure Python?
 The problem is probably in some non-Python component; you shouldn't
 be able to force a memory protection error from within Python code.
 

It looks like the error could be in scipy/Numeric, when a large array's 
type is changed, like this:

  from scipy import *
  a=zeros(1,'b') #100 MiB
  b=a.copy().astype('d')  #800 MiB, ok
  a=zeros(10,'b')#1GiB
  b=a.copy().astype('d')  #8GiB, fails with sf
Segmentation fault

if I use zeros directly for allocation of the doubles it works as expected:

  from scipy import *
  a=zeros(10,'d')#8GiB, fails with python exception
Traceback (most recent call last):
   File stdin, line 1, in ?
MemoryError: can't allocate memory for array
 

I use python 2.4, but my scipy and Numeric aren't quite up-to-date: 
scipy version 0.3.2, Numeric v 24.2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: searching a list of lists as a two-dimensional array?

2007-02-14 Thread Gerard Flanagan
On Feb 12, 1:27 am, agent-s [EMAIL PROTECTED] wrote:
 Basically I'm programming a board game and I have to use a list of
 lists to represent the board (a list of 8 lists with 8 elements each).
 I have to search the adjacent cells for existing pieces and I was
 wondering how I would go about doing this efficiently. Thanks

def iter_grid(cols):
i=0
while True:
yield divmod(i,cols)
i += 1

def iter_adjacents(row, col):
gen = iter_grid(3)
for i in range(9):
x, y = gen.next()
if x == 1 and y ==1:
continue
else:
yield row - x + 1, col - y + 1

def make_grid_dict(rows, cols):
return dict( zip(iter_grid(cols), ['#'] * (rows*cols)) )

def make_adjacent_list(row, col, row_length, col_length):
ret = []
for x, y in iter_adjacents(row, col):
if x  -1 and y  -1 and x  row_length and y  col_length:
ret.append((x,y))
return ret

grid = make_grid_dict(8, 8)
adjacents = dict(grid)
for x,y in sorted(adjacents.keys()):
adjacents[x,y] = make_adjacent_list(x, y, 8, 8)
print '(%s, %s) - %s ' % (x, y, adjacents[x,y]


(0, 0) - [(1, 1), (1, 0), (0, 1)]
(0, 1) - [(1, 2), (1, 1), (1, 0), (0, 2), (0, 0)]
(0, 2) - [(1, 3), (1, 2), (1, 1), (0, 3), (0, 1)]
(0, 3) - [(1, 4), (1, 3), (1, 2), (0, 4), (0, 2)]
(0, 4) - [(1, 5), (1, 4), (1, 3), (0, 5), (0, 3)]
(0, 5) - [(1, 6), (1, 5), (1, 4), (0, 6), (0, 4)]
(0, 6) - [(1, 7), (1, 6), (1, 5), (0, 7), (0, 5)]
(0, 7) - [(1, 7), (1, 6), (0, 6)]
(1, 0) - [(2, 1), (2, 0), (1, 1), (0, 1), (0, 0)]
(1, 1) - [(2, 2), (2, 1), (2, 0), (1, 2), (1, 0), (0, 2), (0, 1), (0,
0)]
(1, 2) - [(2, 3), (2, 2), (2, 1), (1, 3), (1, 1), (0, 3), (0, 2), (0,
1)]
(1, 3) - [(2, 4), (2, 3), (2, 2), (1, 4), (1, 2), (0, 4), (0, 3), (0,
2)]
(1, 4) - [(2, 5), (2, 4), (2, 3), (1, 5), (1, 3), (0, 5), (0, 4), (0,
3)]
(1, 5) - [(2, 6), (2, 5), (2, 4), (1, 6), (1, 4), (0, 6), (0, 5), (0,
4)]
(1, 6) - [(2, 7), (2, 6), (2, 5), (1, 7), (1, 5), (0, 7), (0, 6), (0,
5)]
(1, 7) - [(2, 7), (2, 6), (1, 6), (0, 7), (0, 6)]
(2, 0) - [(3, 1), (3, 0), (2, 1), (1, 1), (1, 0)]
(2, 1) - [(3, 2), (3, 1), (3, 0), (2, 2), (2, 0), (1, 2), (1, 1), (1,
0)]
(2, 2) - [(3, 3), (3, 2), (3, 1), (2, 3), (2, 1), (1, 3), (1, 2), (1,
1)]
(2, 3) - [(3, 4), (3, 3), (3, 2), (2, 4), (2, 2), (1, 4), (1, 3), (1,
2)]
(2, 4) - [(3, 5), (3, 4), (3, 3), (2, 5), (2, 3), (1, 5), (1, 4), (1,
3)]
(2, 5) - [(3, 6), (3, 5), (3, 4), (2, 6), (2, 4), (1, 6), (1, 5), (1,
4)]
(2, 6) - [(3, 7), (3, 6), (3, 5), (2, 7), (2, 5), (1, 7), (1, 6), (1,
5)]
(2, 7) - [(3, 7), (3, 6), (2, 6), (1, 7), (1, 6)]
(3, 0) - [(4, 1), (4, 0), (3, 1), (2, 1), (2, 0)]
(3, 1) - [(4, 2), (4, 1), (4, 0), (3, 2), (3, 0), (2, 2), (2, 1), (2,
0)]
(3, 2) - [(4, 3), (4, 2), (4, 1), (3, 3), (3, 1), (2, 3), (2, 2), (2,
1)]
(3, 3) - [(4, 4), (4, 3), (4, 2), (3, 4), (3, 2), (2, 4), (2, 3), (2,
2)]
(3, 4) - [(4, 5), (4, 4), (4, 3), (3, 5), (3, 3), (2, 5), (2, 4), (2,
3)]
(3, 5) - [(4, 6), (4, 5), (4, 4), (3, 6), (3, 4), (2, 6), (2, 5), (2,
4)]
(3, 6) - [(4, 7), (4, 6), (4, 5), (3, 7), (3, 5), (2, 7), (2, 6), (2,
5)]
(3, 7) - [(4, 7), (4, 6), (3, 6), (2, 7), (2, 6)]
(4, 0) - [(5, 1), (5, 0), (4, 1), (3, 1), (3, 0)]
(4, 1) - [(5, 2), (5, 1), (5, 0), (4, 2), (4, 0), (3, 2), (3, 1), (3,
0)]
(4, 2) - [(5, 3), (5, 2), (5, 1), (4, 3), (4, 1), (3, 3), (3, 2), (3,
1)]
(4, 3) - [(5, 4), (5, 3), (5, 2), (4, 4), (4, 2), (3, 4), (3, 3), (3,
2)]
(4, 4) - [(5, 5), (5, 4), (5, 3), (4, 5), (4, 3), (3, 5), (3, 4), (3,
3)]
(4, 5) - [(5, 6), (5, 5), (5, 4), (4, 6), (4, 4), (3, 6), (3, 5), (3,
4)]
(4, 6) - [(5, 7), (5, 6), (5, 5), (4, 7), (4, 5), (3, 7), (3, 6), (3,
5)]
(4, 7) - [(5, 7), (5, 6), (4, 6), (3, 7), (3, 6)]
(5, 0) - [(6, 1), (6, 0), (5, 1), (4, 1), (4, 0)]
(5, 1) - [(6, 2), (6, 1), (6, 0), (5, 2), (5, 0), (4, 2), (4, 1), (4,
0)]
(5, 2) - [(6, 3), (6, 2), (6, 1), (5, 3), (5, 1), (4, 3), (4, 2), (4,
1)]
(5, 3) - [(6, 4), (6, 3), (6, 2), (5, 4), (5, 2), (4, 4), (4, 3), (4,
2)]
(5, 4) - [(6, 5), (6, 4), (6, 3), (5, 5), (5, 3), (4, 5), (4, 4), (4,
3)]
(5, 5) - [(6, 6), (6, 5), (6, 4), (5, 6), (5, 4), (4, 6), (4, 5), (4,
4)]
(5, 6) - [(6, 7), (6, 6), (6, 5), (5, 7), (5, 5), (4, 7), (4, 6), (4,
5)]
(5, 7) - [(6, 7), (6, 6), (5, 6), (4, 7), (4, 6)]
(6, 0) - [(7, 1), (7, 0), (6, 1), (5, 1), (5, 0)]
(6, 1) - [(7, 2), (7, 1), (7, 0), (6, 2), (6, 0), (5, 2), (5, 1), (5,
0)]
(6, 2) - [(7, 3), (7, 2), (7, 1), (6, 3), (6, 1), (5, 3), (5, 2), (5,
1)]
(6, 3) - [(7, 4), (7, 3), (7, 2), (6, 4), (6, 2), (5, 4), (5, 3), (5,
2)]
(6, 4) - [(7, 5), (7, 4), (7, 3), (6, 5), (6, 3), (5, 5), (5, 4), (5,
3)]
(6, 5) - [(7, 6), (7, 5), (7, 4), (6, 6), (6, 4), (5, 6), (5, 5), (5,
4)]
(6, 6) - [(7, 7), (7, 6), (7, 5), (6, 7), (6, 5), (5, 7), (5, 6), (5,
5)]
(6, 7) - [(7, 7), (7, 6), (6, 6), (5, 7), (5, 6)]
(7, 0) - [(7, 1), (6, 1), (6, 0)]
(7, 1) - [(7, 2), (7, 0), (6, 2), (6, 1), (6, 0)]
(7, 2) - [(7, 3), (7, 1), (6, 3), (6, 2), (6, 1)]
(7, 3) - [(7, 4), (7, 2), (6, 4), (6, 3), (6, 2)]
(7, 4) - [(7, 5), (7, 3), (6, 5), (6, 4), (6, 

Re: calling php function from python

2007-02-14 Thread Diez B. Roggisch
mark wrote:

 is it possible to call a php function from python and use a class from
 php in python? i want to use mmslib which creates mms messages and the
 only implementation is a php mmslib implementation.

Do yourself - and the python community... :) - a favor and just translate
the mmslib code to python. It is easy and straightforward todo.

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


Re: c++ for python programmers

2007-02-14 Thread Nicola Musatti
On Feb 14, 12:26 am, Sam [EMAIL PROTECTED] wrote:
[...]
 C++ is -not- strongly typed. You can cast anything to void *, and
 manipulate it in ways unimaginable. Plus there's the whole mess that
 is pointer arithmetic and a weak typesystem...

The previous poster wrote strongly typed, not a straight jacket.
The fact that you may do certain things doesn't mean that you have to
nor that they are going to be done to you against your will.

 Disclaimer: I am unashamedly in the C++ Is Evil camp, and wholly
 believe that if you want proper strong, static type checking, use
 Haskell, or if you want proper, complete object-orientation (C++'s
 primitive types compromise its object system's integrity, and I
 believe I've already discussed casting and pointers), use Python, and
 if you want under-the-hood pointer-fu, use C.

The trouble is that in addition to proper, strong, static type
checking people often also want their daily bread, fancy that. As to
the merits of complete object orientation, I'd like to hear about
them, because nobody managed to explain them to me in a satisfactory
way yet.

There are many valid reasons to dislike C++ and to prefer Python to
it, but dismissing it as C++ Is Evil is just plain stupid. Moreover,
C might be a valid competitor for small projects and it probably
covers most Pythonistas' needs for closeness to the metal, but it
just doesn't scale.

Cheers,
Nicola Musatti

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


Re: c++ for python programmers

2007-02-14 Thread jkn
Hi Thomas

On Feb 12, 6:00 pm, Thomas Nelson [EMAIL PROTECTED] wrote:
 I realize I'm approaching this backwards from the direction most
 people go, but does anyone know of a good c/c++ introduction for
 python programmers?


They are not particularly aimed at Python programmers, but Bruce
Eckel's Thinking in C++ books are (a) excellent, and (b) freely
downloadable, as well as purchasable in book form:

http://www.mindview.net/

Bruce is a python fan FWIW ;-)

HTH
Jon N

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


Re: python not returning true

2007-02-14 Thread Ben Finney
Michael Bentley [EMAIL PROTECTED] writes:

 # Something just doesn't seem right in those
 # Every kiss begins with 'K' commercials.

  'Every Kiss'.startswith('K')
 False

 kisses = [kiss, kiss, kiss, kiss, kiss]
 kisses == [kiss for kiss in kisses
...if kiss.startswith(k)]
True

Happy St. Valentine's Day, everyone.

-- 
 \ Experience is that marvelous thing that enables you to |
  `\  recognize a mistake when you make it again.  -- Franklin P. |
_o__)Jones |
Ben Finney

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


replacing substrings within strings

2007-02-14 Thread amadain
Hi
I was wondering if there was a nicer way to swap the first 2
characters in a string with the 4th and 5th characters other than:

darr=list(010203040506)
aarr=darr[:2]
barr=darr[4:6]
darr[:2]=barr
darr[4:6]=aarr
result=.join(darr)

The above code works fine but I was wondering if anybody had another
way of doing this?

A

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


Re: replacing substrings within strings

2007-02-14 Thread Diez B. Roggisch
amadain wrote:

 Hi
 I was wondering if there was a nicer way to swap the first 2
 characters in a string with the 4th and 5th characters other than:
 
 darr=list(010203040506)
 aarr=darr[:2]
 barr=darr[4:6]
 darr[:2]=barr
 darr[4:6]=aarr
 result=.join(darr)
 
 The above code works fine but I was wondering if anybody had another
 way of doing this?


You can do it like this:


darr=list(010203040506)
darr[:2], darr[4:5] = darr[4:6], darr[:2]
result=.join(darr)
print result


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


Re: replacing substrings within strings

2007-02-14 Thread Maric Michaud
Le mercredi 14 février 2007 13:08, amadain a écrit :
 darr=list(010203040506)
 aarr=darr[:2]
 barr=darr[4:6]
 darr[:2]=barr
 darr[4:6]=aarr
 result=.join(darr)

 The above code works fine but I was wondering if anybody had another
 way of doing this?

Why not :

In [4]: s=010203040506

In [5]: print s[4:6] + s[2:4] + s[0:2] + s[6:]
030201040506

?

-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
Mobile: +33 632 77 00 21
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: replacing substrings within strings

2007-02-14 Thread Rune Strand
On Feb 14, 1:08 pm, amadain [EMAIL PROTECTED] wrote:
 I was wondering if there was a nicer way to swap the first 2
 characters in a string with the 4th and 5th characters other than:

 darr=list(010203040506)
 aarr=darr[:2]
 barr=darr[4:6]
 darr[:2]=barr
 darr[4:6]=aarr
 result=.join(darr)

 The above code works fine but I was wondering if anybody had another
 way of doing this?

Assuming the string length is always at least 5:

def swap(s):
return '%s%s%s%s' % (s[3:6], s[2:3], s[:2], s[6:])


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


Re: replacing substrings within strings

2007-02-14 Thread amadain
On Feb 14, 12:16 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 amadain wrote:
  Hi
  I was wondering if there was a nicer way to swap the first 2
  characters in a string with the 4th and 5th characters other than:

  darr=list(010203040506)
  aarr=darr[:2]
  barr=darr[4:6]
  darr[:2]=barr
  darr[4:6]=aarr
  result=.join(darr)

  The above code works fine but I was wondering if anybody had another
  way of doing this?

 You can do it like this:

 darr=list(010203040506)
 darr[:2], darr[4:5] = darr[4:6], darr[:2]
 result=.join(darr)
 print result

 Diez



Thats the same code. I was wondering if the string manipulation can be
done without an excursion into the list world.

A

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


Re: Tkinter: how; newbie

2007-02-14 Thread Gigs_
jim-on-linux wrote:
 On Tuesday 13 February 2007 18:02, Gigs_ wrote:
 can someone explain me this code?

 from Tkinter import *

 root = Tk()

 def callback(event):
  print clicked at, event.x, event.y

 frame = Frame(root, width=100, height=100)
 frame.bind(Button-1, callback)
 frame.pack()

 root.mainloop()

 if you live on longititude 32, wrere is that? 
 If you live on latitude 40 and longitiude 32 I can 
 find that location. 
 
  Your mouse is pointing to x, and y, which is 
 simply a location on the screen.
 
I know that, Matimus has explained what I didn't get
but thx anyway
 
 well, my problem is at frame.bind(,Button-1,
 callback) callback function prints event.x and
 event.y. How the callback function get this two
 number when it has only one argument (event)
 Why its not: def callback(x, y): print x, y

 Im new to gui programming

 Sorry for bad eng!

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


Re: replacing substrings within strings

2007-02-14 Thread Sion Arrowsmith
amadain [EMAIL PROTECTED] wrote:
I was wondering if there was a nicer way to swap the first 2
characters in a string with the 4th and 5th characters other than:

darr=list(010203040506)
aarr=darr[:2]
barr=darr[4:6]
darr[:2]=barr
darr[4:6]=aarr
result=.join(darr)

darr=list(010203040506)
darr[:2], darr[4:6] = darr[4:6], darr[:2]
result = .join(darr)

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  Frankly I have no feelings towards penguins one way or the other
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: replacing substrings within strings

2007-02-14 Thread Rune Strand
Or, slighly slower, but more general:

def swap(s, order=(3,4,2,0,1)):
# assert len(s) = len(order)
return ''.join([s[o] for o in order]) + s[6:]




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


Re: WindowsNT user authentication

2007-02-14 Thread billie
Another question, I'm sorry.
Do you got any idea about how to get permissions of a file/directory
given the username?
For example: I would like to know if C:\my_file.ext is readable/
writable by user 'x' or not.

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


Re: Parsing HTML

2007-02-14 Thread Frederic Rentsch
mtuller wrote:
 Alright. I have tried everything I can find, but am not getting
 anywhere. I have a web page that has data like this:

 tr 
 td headers=col1_1  style=width:21%   
 span  class=hpPageText LETTER/span/td
 td headers=col2_1  style=width:13%; text-align:right   
 span  class=hpPageText 33,699/span/td
 td headers=col3_1  style=width:13%; text-align:right   
 span  class=hpPageText 1.0/span/td
 td headers=col4_1  style=width:13%; text-align:right   
 /tr

 What is show is only a small section.

 I want to extract the 33,699 (which is dynamic) and set the value to a
 variable so that I can insert it into a database. I have tried parsing
 the html with pyparsing, and the examples will get it to print all
 instances with span, of which there are a hundred or so when I use:

 for srvrtokens in printCount.searchString(printerListHTML):
   print srvrtokens

 If I set the last line to srvtokens[3] I get the values, but I don't
 know grab a single line and then set that as a variable.

 I have also tried Beautiful Soup, but had trouble understanding the
 documentation, and HTMLParser doesn't seem to do what I want. Can
 someone point me to a tutorial or give me some pointers on how to
 parse html where there are multiple lines with the same tags and then
 be able to go to a certain line and grab a value and set a variable's
 value to that?


 Thanks,

 Mike

   
Posted problems rarely provide exhaustive information. It's just not 
possible. I have been taking shots in the dark of late suggesting a 
stream-editing approach to extracting data from htm files. The 
mainstream approach is to use a parser (beautiful soup or pyparsing).
  Often times nothing more is attempted than the location and 
extraction of some text irrespective of page layout. This can sometimes 
be done with a simple regular expression, or with a stream editor if a 
regular expression gets too unwieldy. The advantage of the stream editor 
over a parser is that it doesn't mobilize an arsenal of unneeded 
functionality and therefore tends to be easier, faster and shorter to 
implement. The editor's inability to understand structure isn't a 
shortcoming when structure doesn't matter and can even be an advantage 
in the presence of malformed input that sends a parser on a tough and 
potentially hazardous mission for no purpose at all.
  SE doesn't impose the study of massive documentation, nor the 
memorization of dozens of classes, methods and what not. The following 
four lines would solve the OP's problem (provided the post really is all 
there is to the problem):


  import re, SE# http://cheeseshop.python.org/pypi/SE/2.3

  Filter = SE.SE ('EAT ~(?i)col[0-9]_[0-9](.|\n)*?/td~==SOME 
SPLIT MARK')

  r = re.compile ('(?i)(col[0-9]_[0-9])(.|\n)*?([0-9,]+)/span')

  for line in Filter (s).split ('SOME SPLIT MARK'):
  print r.search (line).group (1, 3)

('col2_1', '33,699')
('col3_1', '0')
('col4_1', '7,428')


---

Input:

  s = '''
td headers=col1_1  style=width:21%   
span  class=hpPageText LETTER/span/td
td headers=col2_1  style=width:13%; text-align:right   
span  class=hpPageText 33,699/span/td
td headers=col3_1  style=width:13%; text-align:right   
span  class=hpPageText 1.0/span/td
td headers=col5_1  style=width:13%; text-align:right   
span  class=hppagetext 7,428/span/td
/tr'''

The SE object handles file input too:

  for line in Filter ('file_name', '').split ('SOME SPLIT MARK'):  # 
'' commands string output
  print r.search (line).group (1, 3)





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


Re: WindowsNT user authentication

2007-02-14 Thread Tim Golden
billie wrote:
 Another question, I'm sorry.
 Do you got any idea about how to get permissions of a file/directory
 given the username?
 For example: I would like to know if C:\my_file.ext is readable/
 writable by user 'x' or not.

This is an unfortunately messy question. The easiest
answer -- and I'm quite serious -- might be to have
the user *try* to read it and to catch the exception.

Quite apart from the mildly labyrinthine techniques for
determining object security, you face a potential race
condition: by the time you've tested and got your answer,
someone could have changed the permissions. Unlikely,
you'll admit, but possible enough to the try-except
approach attractive.

There are some examples of file security both in the
CHM which comes with the pywin32 extensions and in the
demos folder, on my machine:

c:\python24\lib\site-packages\win32\demos\security

I was going to start explaining win32 security terms
in this reply, but perhaps I won't unless the try-it-and-see
approach advocated above doesn't work!

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


Re: WindowsNT user authentication

2007-02-14 Thread Tim Golden
Tim Golden wrote:
 billie wrote:
 Another question, I'm sorry.
 Do you got any idea about how to get permissions of a file/directory
 given the username?
 For example: I would like to know if C:\my_file.ext is readable/
 writable by user 'x' or not.
 
 This is an unfortunately messy question. 

I'm sorry; that probably came out wrong. What I meant
was that, although the question was perfectly intelligible,
the answer is going to be more complex than you probably
expected ;)

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


Re: replacing substrings within strings

2007-02-14 Thread Diez B. Roggisch
 Thats the same code. I was wondering if the string manipulation can be
 done without an excursion into the list world.

That's the price to pay for immutable strings. If you have to to lots of
stuff like that, then keep things a list, and join only when you need the
result as a string.

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


Re: WindowsNT user authentication

2007-02-14 Thread billie
On 14 Feb, 14:30, Tim Golden [EMAIL PROTECTED] wrote:
 Tim Golden wrote:
  billie wrote:
  Another question, I'm sorry.
  Do you got any idea about how to get permissions of a file/directory
  given the username?
  For example: I would like to know if C:\my_file.ext is readable/
  writable by user 'x' or not.

  This is an unfortunately messy question.

 I'm sorry; that probably came out wrong. What I meant
 was that, although the question was perfectly intelligible,
 the answer is going to be more complex than you probably
 expected ;)

 TJG

No problem about that. ;)
I'll try to check demos folder then let you know something about it.
Thanks again.


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


Re: c++ for python programmers

2007-02-14 Thread Neil Cerutti
On 2007-02-13, Sam [EMAIL PROTECTED] wrote:
 On 13 Feb 2007 17:51:00 GMT, Jorgen Grahn
[EMAIL PROTECTED] wrote:
 Well, C++ is a better language than C in many ways. So, if he
 needs to learn one of them, why does it have to be C?

 Another reason some people choose C++ over Python for some
 tasks is that they feel that larger programs benefit from
 strong, static type checking. I like both ways, but depending
 on the task, one or the other is better.

 C++ is -not- strongly typed. You can cast anything to void *,
 and manipulate it in ways unimaginable. Plus there's the whole
 mess that is pointer arithmetic and a weak typesystem...

Don't forget the lack of standard garbage collection. 

Also there's the hell known as exception safety.

Python conceptually has many of the same issues with exception
safety, but at least memory leaks aren't one of the consequences.
I imagine most Python programmers don't even think about
exception safety, but probably should be. We just happily raise
exceptions willy-nilly, without worrying about our objects
remaining in a reasonable state. Or do we? Maybe it's better not
to think about it. ;-)

 Disclaimer: I am unashamedly in the C++ Is Evil camp, and
 wholly believe that if you want proper strong, static type
 checking, use Haskell, or if you want proper, complete
 object-orientation (C++'s primitive types compromise its object
 system's integrity, and I believe I've already discussed
 casting and pointers), use Python, and if you want
 under-the-hood pointer-fu, use C.

C++'s standard library seems such a huge win over the C library,
that I'd hate to switch back. Of course it has its warts and
cancers, but it's an awesome accomplishment. And you *can* get
harder-to-use C versions that are basically portable.

-- 
Neil Cerutti
A billion here, a billion there, sooner or later it adds up to real money.
--Everett Dirksen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recursive calls and stack

2007-02-14 Thread Neil Cerutti
On 2007-02-14, Gabriel Genellina [EMAIL PROTECTED] wrote:
 En Wed, 14 Feb 2007 03:09:37 -0300, [EMAIL PROTECTED]  
[EMAIL PROTECTED] escribió:
  Is this way of implementation fill the stack space with the
  local variables inside each call. If this is not good, is
  there a better way to implement? Or python itself will
  understand that the calls happen in the last line, so local
  variables need not be pushed into the stack?

 I'm afraid not, the calls will be stacked until some object is
 found. Python does not do tail recursion optimization (at
 least, I'm not aware  of that).

To be just a little pedantic, it's tail call optimization. Any
tail call can be optimized, not just recursive ones.

 But even if it could do that, in this case you have recursive
 calls between two functions, and that's a bit harder.

So the effect is that mutual recursion isn't actually any harder.

Moreover, if his functions calls really are tail-calls, then
translating them by hand into iteration might be fairly easy.

A simple, silly example:

def sum(seq):
  if len(seq) == 0:
return 0
  else:
return seq[0] + sum(seq[1:])

Above, sum is not a tail call, since the + operation must be
defered until after the call to sum returns.

Below, sum is a tail call.

def sum(seq, accum=0):
  if len(seq) == 0:
return accum
  else:
return sum(seq[1:], accum+s[0])

Since no state must be retained by sum when calling sum, it's a
tail call. The last version translates more or less directly into
a dumb while loop.

I don't believe Python does tail call optimization; at least it
isn't document that it does it.

-- 
Neil Cerutti
The audience is asked to remain seated until the end of the recession.
--Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


How to print the variable?

2007-02-14 Thread Hans Schwaebli
Hi,
   
  am am a Python beginner with Java knowledge background. Infact I need to use 
Jython.
   
  My first beginner question is how to determine of what type a variable is?
   
  In program which supports Jython there is a variable called rc available. I 
can use the methods on that variable like rc.logMessage(hello). But if I try 
to execute print ${rc} it tells me Invalid variable syntax for attribute 
'code' with value 'print ${rc}.'
   
  In Java I can print any variable. What I want is to do something like 
variable.getClass().getName(). Can this be done with that rc variable in 
Python/Jython scripts?
   
  Then I would know how to instantiate the rc variable.
   
  I apologize for my beginner questions. I should read more or get a teaching, 
but the last I won't get and for the first I have not so much time.
   
  Thanks in advance.

 
-
Now that's room service! Choose from over 150,000 hotels 
in 45,000 destinations on Yahoo! Travel to find your fit.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: replacing substrings within strings

2007-02-14 Thread bearophileHUGS
Diez B. Roggisch:
 That's the price to pay for immutable strings.

Right, but CPython has array.array(c) too. Using Diez Roggisch's
code:

 from array import array
 arrs = array(c, 010203040506)
 arrs[:2], arrs[4:5] = arrs[4:6], arrs[:2]
 arrs.tostring()
'0302013040506'

Using such arrays is useful if you have to do lot of processing before
the final tostring().

Bye,
bearophile

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


Re: How to print the variable?

2007-02-14 Thread Cristiano Paris
Hans Schwaebli wrote:
 Hi,
  
 am am a Python beginner with Java knowledge background. Infact I need to 
 use Jython.
  
 My first beginner question is how to determine of what type a variable is?

Let v be the var, 'print type(v)' should* work. [* I've never used 
Jython before].

You can print any variable using the 'print' statement. If you want to 
be pedantic, surround the variable name with the str() built-in.

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


Re: How to print the variable?

2007-02-14 Thread Jean-Paul Calderone
On Wed, 14 Feb 2007 05:47:31 -0800 (PST), Hans Schwaebli [EMAIL PROTECTED] 
wrote:
Hi,

  am am a Python beginner with Java knowledge background. Infact I need to use 
 Jython.

  My first beginner question is how to determine of what type a variable is?

  In program which supports Jython there is a variable called rc available. 
 I can use the methods on that variable like rc.logMessage(hello). But if I 
 try to execute print ${rc} it tells me Invalid variable syntax for 
 attribute 'code' with value 'print ${rc}.'

  print rc
  print dir(rc)
  print type(rc)
  help(rc)

  http://python.org/doc/tut/

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


Re: replacing substrings within strings

2007-02-14 Thread amadain
Thanks all. I usually turn strings into arrays for processing. I was
looking to see if that was the best way to do it from others that use
python. No one else uses python in my company so its nice to get
different points of view from other python users from lists like this.
A

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


Re: replacing substrings within strings

2007-02-14 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

 Diez B. Roggisch:
 That's the price to pay for immutable strings.
 
 Right, but CPython has array.array(c) too. Using Diez Roggisch's
 code:

Ahhh, ze arrayz. I alwayz forget about the arrayz.

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


Re: How to print the variable?

2007-02-14 Thread Paul McGuire
On Feb 14, 8:00 am, Jean-Paul Calderone [EMAIL PROTECTED] wrote:
 On Wed, 14 Feb 2007 05:47:31 -0800 (PST), Hans Schwaebli [EMAIL PROTECTED] 
 wrote:
 Hi,

   am am a Python beginner with Java knowledge background. Infact I need to 
  use Jython.

   My first beginner question is how to determine of what type a variable is?

   In program which supports Jython there is a variable called rc 
  available. I can use the methods on that variable like 
  rc.logMessage(hello). But if I try to execute print ${rc} it tells me 
  Invalid variable syntax for attribute 'code' with value 'print ${rc}.'

   print rc
   print dir(rc)
   print type(rc)
   help(rc)

  http://python.org/doc/tut/

 Jean-Paul

print The variable rc has the value %s % rc
print The variable rc has the value %(rc)s % locals()

-- Paul

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


Re: replacing substrings within strings

2007-02-14 Thread Paul McGuire
On Feb 14, 6:08 am, amadain [EMAIL PROTECTED] wrote:
 Hi
 I was wondering if there was a nicer way to swap the first 2
 characters in a string with the 4th and 5th characters other than:

 darr=list(010203040506)
 aarr=darr[:2]
 barr=darr[4:6]
 darr[:2]=barr
 darr[4:6]=aarr
 result=.join(darr)

 The above code works fine but I was wondering if anybody had another
 way of doing this?

 A

4th and 5th characters - darr[4:6]

You must be referring to the leading '0' as the 0th character, then.

-- Paul

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


Re: Scripting Visio using Python

2007-02-14 Thread Harry George
Paul Watson [EMAIL PROTECTED] writes:

 I would like to create some additional shapes in Microsoft Visio using
 the Python language.  It would appear that Visio can use any CLR
 language.  Has anyone done this?  Can I use the Python package from
 python.org, or must I use IronPython?

An alternative might be to work (cross-platform) wit the vxd (XML)
file format.  A good reader/writer for that would be handy.

-- 
Harry George
PLM Engineering Architecture
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python not returning true

2007-02-14 Thread Grant Edwards
On 2007-02-14, Terry Reedy [EMAIL PROTECTED] wrote:

| Wit has nothing to do with it. The fact that you are a Python noob is
| also irrelevant. Your problem statement was unintelligible, as is your
| response. What does pwn mean?

 I believe that it is a misspelling of 'own' used by pvp (person versus 
 person, as opposed to person versus monster) gamers to demonstrate their 
 in-ness.  But perhaps agent-s can enlightenment us further.

Mis-spelling things is witty now?  Wow.  I've been witty all
these years and didn't even know it...

-- 
Grant Edwards   grante Yow!  I'm EXCITED!! I want
  at   a FLANK STEAK WEEK-END!! I
   visi.comthink I'm JULIA CHILD!!
-- 
http://mail.python.org/mailman/listinfo/python-list


multi processes

2007-02-14 Thread amadain
Hi
Heres a poser. I want to start a program 4 times at exactly the same
time (emulating 4 separate users starting up the same program). I am
using pexpect to run the program from 4 separate locations accross the
network. How do I start the programs running at exactly the same time?
I want to time how long it takes each program to complete and to show
if any of the program initiations failed. I also want to check for
race conditions. The program that I am running is immaterial for this
question - it could be mysql running queries on the same database for
example. Using threading, you call start() to start each thread but if
I call start on each instance in turn I am not starting
simultaneously.
A

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


rot13 in a more Pythonic style?

2007-02-14 Thread Andy Dingley
I'm trying to write rot13, but to do it in a better and more Pythonic
style than I'm currrently using. What would  you reckon to the
following pretty ugly thing?   How would you improve it?  In
particular, I don't like the way a three-way selection is done by
nesting two binary selections. Also I dislike stating the same
algorithm twice, but can't see how to parameterise them neatly.

Yes, I know of .encode() and .translate().
No, I don't actually need rot13 itself, it's just a convenient
substitute example for the real job-specific task.
No, I don't have to do it with lambdas, but it would be nice if the
final function was a lambda.


#!/bin/python
import string

lc_rot13 = lambda c : (chr((ord(c) - ord('a') + 13) % 26 + ord('a')))

uc_rot13 = lambda c : (chr((ord(c) - ord('A') + 13) % 26 + ord('A')))

c_rot13 = lambda c : (((c, uc_rot13(c)) [c in
'ABCDEFGHIJKLMNOPQRSTUVWXYZ']), lc_rot13(c) )[c in
'abcdefghijklmnopqrstuvwxyz']

rot13 = lambda s : string.join([ c_rot13(c) for c in s ],'')


print rot13( 'Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt' )

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


Re: threading and multicores, pros and cons

2007-02-14 Thread garrickp
On Feb 13, 9:07 pm, Maric Michaud [EMAIL PROTECTED] wrote:
 I've heard of a bunch of arguments to defend python's choice of GIL, but I'm
 not quite sure of their technical background, nor what is really important
 and what is not. These discussions often end in a prudent python has made a
 choice among others... which is not really convincing.

Well, INAG (I'm not a Guru), but we recently had training from a Guru.
When we brought up this question, his response was fairly simple.
Paraphrased for inaccuracy:

Some time back, a group did remove the GIL from the python core, and
implemented locks on the core code to make it threadsafe. Well, the
problem was that while it worked, the necessary locks it made single
threaded code take significantly longer to execute.

He then proceeded to show us how to achieve the same effect
(multithreading python for use on multi-core computers) using popen2
and stdio pipes.

FWIW, ~G

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


Re: threading and multicores, pros and cons

2007-02-14 Thread Istvan Albert
On Feb 14, 1:33 am, Maric Michaud [EMAIL PROTECTED] wrote:

 At this time, it 's not easy to explain him that python
 is notflawed compared to Java, and that he will not
 regret his choice in the future.

Database adaptors such as psycopg do release the GIL while connecting
and exchanging data.  Apache's MPM (multi processing module) can run
mod_python and with that multiple python instances as separate
processes thus avoiding the global lock as well.

 plone install up and running, he will immediately compare it to
 J2EE wonder why he should pay a consultant to make it work properly.

I really doubt that any performance difference will be due to the
global interpreter lock. This not how things work. You most certainly
have far more substantial bottlenecks in each application.

i.

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


Re: multi processes

2007-02-14 Thread garrickp
On Feb 14, 7:53 am, amadain [EMAIL PROTECTED] wrote:
 Hi
 Heres a poser. I want to start a program 4 times at exactly the same
 time (emulating 4 separate users starting up the same program). I am
 using pexpect to run the program from 4 separate locations accross the
 network. How do I start the programs running at exactly the same time?
 I want to time how long it takes each program to complete and to show
 if any of the program initiations failed. I also want to check for
 race conditions. The program that I am running is immaterial for this
 question - it could be mysql running queries on the same database for
 example. Using threading, you call start() to start each thread but if
 I call start on each instance in turn I am not starting
 simultaneously.
 A

Standard answers about starting anything at *exactly* the same time
aside, I would expect that the easiest answer would be to have a fifth
controlling program in communication with all four, which can then
send a start message over sockets to each of the agents at the same
time.

There are several programs out there which can already do this. One
example, Grinder, is designed for this very use (creating concurrent
users for a test). It's free, uses Jython as it's scripting language,
and even is capable of keeping track of your times for you. IMO, it's
worth checking out.

http://grinder.sourceforge.net

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


Re: multi processes

2007-02-14 Thread amadain
On Feb 14, 3:32 pm, [EMAIL PROTECTED] wrote:
 On Feb 14, 7:53 am, amadain [EMAIL PROTECTED] wrote:

  Hi
  Heres a poser. I want to start a program 4 times at exactly the same
  time (emulating 4 separate users starting up the same program). I am
  using pexpect to run the program from 4 separate locations accross the
  network. How do I start the programs running at exactly the same time?
  I want to time how long it takes each program to complete and to show
  if any of the program initiations failed. I also want to check for
  race conditions. The program that I am running is immaterial for this
  question - it could be mysql running queries on the same database for
  example. Using threading, you call start() to start each thread but if
  I call start on each instance in turn I am not starting
  simultaneously.
  A

 Standard answers about starting anything at *exactly* the same time
 aside, I would expect that the easiest answer would be to have a fifth
 controlling program in communication with all four, which can then
 send a start message over sockets to each of the agents at the same
 time.

 There are several programs out there which can already do this. One
 example, Grinder, is designed for this very use (creating concurrent
 users for a test). It's free, uses Jython as it's scripting language,
 and even is capable of keeping track of your times for you. IMO, it's
 worth checking out.

 http://grinder.sourceforge.net


Thank you. I'll check that out.

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


Re: rot13 in a more Pythonic style?

2007-02-14 Thread Rune Strand
You could try some_string.encode('rot_13')

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


How much memory used by a name

2007-02-14 Thread Bernard Lebel
Hello,

I would like to know if there is a way to know how much memory (bytes,
kilobytes, megabytes, etc) a name is using.

More specifically, I have this list of strings that I want to write to
a file as lines.
This list grows througout the script execution, and toward the end,
the file is written.

However I would like to know how much memory, before writing to the
file, is this list using. Is it possible at all?


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


Re: c++ for python programmers

2007-02-14 Thread Nicola Musatti
On Feb 14, 2:41 pm, Neil Cerutti [EMAIL PROTECTED] wrote:
[...]
 Don't forget the lack of standard garbage collection.

Optional garbage collection is highly likely to be included in the
next C++ standard, due out in a couple of years.

 Also there's the hell known as exception safety.

 Python conceptually has many of the same issues with exception
 safety, but at least memory leaks aren't one of the consequences.
 I imagine most Python programmers don't even think about
 exception safety, but probably should be. We just happily raise
 exceptions willy-nilly, without worrying about our objects
 remaining in a reasonable state. Or do we? Maybe it's better not
 to think about it. ;-)

On the other hand having everything dynamically allocated prevents the
adoption of deterministic destruction, which is a far better clean up
mechanism than try/finally clauses.

In modern C++ standard containers and smart pointers help solve most
memory related problems. I'm aware that most is not the same as all,
but on the other hand garbage collection has it's problems too:
depending on the algorithm it may not be able to reclaim all the
unreachable memory and forgetting to explicitly reset variables may
lead to hanging to memory that is really not needed anymore.

Cheers,
Nicola Musatti

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


ANN: py lib 0.9.0: py.test, distributed execution, microthreads ...

2007-02-14 Thread holger krekel
py lib 0.9.0: py.test, distributed execution, greenlets and more
==

Welcome to the 0.9.0 py lib release - a library aiming to 
support agile and test-driven python development on various levels. 

Main API/Tool Features: 

* py.test: cross-project testing tool with many advanced features
* py.execnet: ad-hoc code distribution to SSH, Socket and local sub processes
* py.magic.greenlet: micro-threads on standard CPython (stackless-light)
* py.path: path abstractions over local and subversion files 
* rich documentation of py's exported API 
* tested against Linux, OSX and partly against Win32, python 2.3-2.5

All these features and their API have extensive documentation,
generated with the new apigen, which we intend to make accessible
for other python projects as well.  

Download/Install:   http://codespeak.net/py/0.9.0/download.html
Documentation/API:  http://codespeak.net/py/0.9.0/index.html

Work on the py lib has been partially funded by the 
European Union IST programme and by http://merlinux.de 
within the PyPy project. 

best, have fun and let us know what you think!

Holger Krekel, Maciej Fijalkowski, 
Guido Wesdorp, Carl Friedrich Bolz

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


RE: [pywin32] - Excel COM problem

2007-02-14 Thread Stefan Schukat
Characters is a parameterized property. So you can't call it without a
generated wrapper.

see inside the wrapper:
# Result is of type Characters
# The method GetCharacters is actually a property, but must be
used as a method to correctly pass the arguments
def GetCharacters(self, Start=defaultNamedOptArg,
Length=defaultNamedOptArg):
 

so in your case:

xlsapp = gencache.EnsureDispatch(Excel.Application)
wb = xlsapp.Workbooks.Add()
sheet = wb.Sheets[0]

myShape = sheet.Shapes.AddShape(1, 315, 200, 400, 300)
myShape.Select()

xlsapp.Selection.Characters.Text = finalText[0:200]
xlsapp.Selection.GetCharacters(200).Insert(finalText[200:400])

excelfile = Hello.xls
wb.SaveAs(excelfile)
wb.Close()
xlsapp.Quit()


Stefan

 -Original Message-
 From: [EMAIL PROTECTED] 
 [mailto:[EMAIL PROTECTED] On 
 Behalf Of Andrea Gavana
 Sent: Friday, February 09, 2007 9:59 PM
 To: python-list@python.org
 Subject: [pywin32] - Excel COM problem
 
 Hi All,
 
I have a very simple python script that tries to put a 
 rectangular shape in a worksheet and then add some text 
 inside that shape. The main problem, is that as usual Excel 
 doesn't like input strings longer than 200 and something 
 characters. So, by just recording a macro in Excel, I tried 
 to append the text in the shape by dividing it in chunks. For 
 example, I tried this little script:
 
 #--
 from win32com.client import Dispatch
 
 finalText = A*1250
 
 xlsapp = Dispatch(Excel.Application)
 wb = xlsapp.Workbooks.Add()
 sheet = wb.Sheets[0]
 
 myShape = sheet.Shapes.AddShape(1, 315, 200, 400, 300)
 myShape.Select()
 
 xlsapp.Selection.Characters.Text = finalText[0:200]
 xlsapp.Selection.Characters(200).Insert(finalText[200:400])
 
 excelfile = Hello.xls
 wb.SaveAs(excelfile)
 wb.Close()
 xlsapp.Quit()
 
 #--
 
 And it crashes with an impossible error:
 
 Traceback (most recent call last):
  File D:\MyProjects\pywin32.py, line 13, in module
xlsapp.Selection.Characters(200).Insert(finalText[200:400])
  File 
 C:\Python25\lib\site-packages\win32com\client\dynamic.py, 
 line 172, in __call__
return 
 self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.
 defaultDispatchName,None)
 pywintypes.com_error: (-2147352573, 'Member not found.', None, None)
 
 However, the macro I recorded in Excel does exactly that: it 
 appends chunks of the string with a maximum length of 200 chars.
 Am I missing something here?
 This is with Python 2.5, PythonWin 2.5 (r25:51908, Sep 19 2006,
 09:52:17) [MSC v.1310 32 bit (Intel)] on win32, Windows XP SP2.
 
 Thank you for your consideration.
 
 Andrea.
 
 Imagination Is The Only Weapon In The War Against Reality.
 http://xoomer.virgilio.it/infinity77/
 --
 http://mail.python.org/mailman/listinfo/python-list
 
-- 
http://mail.python.org/mailman/listinfo/python-list


How to ping and shutdown a remote computer?

2007-02-14 Thread joja15
I am working on a Python script to perform as a remote computer
manager. So far I have a WOL function working and I would like to add
the ability to show if a machine is on or off (I figured I would do so
by pinging the machine and seeing if I get a response). I would also
like to add the ability to remotely shutdown a computer from the
python script. Does anyone have a code snippet for pinging an IP, a
code snippet for shutting down a remote Windows XP machine, and a code
snippet for sending a HTTP request?

Here is my current setup:

- PC  running python script
- FreeNAS (media server running on FreeBSD. Can be shutdown from web
interface so I planned on just sending that same web button click from
the python script to shutdown the FreeNAS server)
- Windows XP machine with folder share (What packet is sent over the
network to remotely shutdown a Windows XP machine?)

My hope is to have a script then when you start it will list all your
remote computers/servers and show if they are currently on/off. Then
you can select a server and turn it off if it is on or turn it on if
it is off.

Thank you in advance for any help provided.

- John

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


Re: How to ping and shutdown a remote computer?

2007-02-14 Thread Christophe
[EMAIL PROTECTED] a écrit :
 I am working on a Python script to perform as a remote computer
 manager. So far I have a WOL function working and I would like to add
 the ability to show if a machine is on or off (I figured I would do so
 by pinging the machine and seeing if I get a response). I would also
 like to add the ability to remotely shutdown a computer from the
 python script. Does anyone have a code snippet for pinging an IP, a
 code snippet for shutting down a remote Windows XP machine, and a code
 snippet for sending a HTTP request?
 
 Here is my current setup:
 
 - PC  running python script
 - FreeNAS (media server running on FreeBSD. Can be shutdown from web
 interface so I planned on just sending that same web button click from
 the python script to shutdown the FreeNAS server)
 - Windows XP machine with folder share (What packet is sent over the
 network to remotely shutdown a Windows XP machine?)

import os
os.system(shutdown -s -f)
Try other switches if you want. Requires Windows XP at the minimum.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: rot13 in a more Pythonic style?

2007-02-14 Thread Neil Cerutti
On 2007-02-14, Andy Dingley [EMAIL PROTECTED] wrote:
 I'm trying to write rot13, but to do it in a better and more
 Pythonic style than I'm currrently using. What would  you
 reckon to the following pretty ugly thing?   How would you
 improve it?  In particular, I don't like the way a three-way
 selection is done by nesting two binary selections. Also I
 dislike stating the same algorithm twice, but can't see how to
 parameterise them neatly.

 Yes, I know of .encode() and .translate().

str.translate is what I'd do.

import string
rot13table = string.maketrans(
  'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 
  'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM')

print 'Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt'.translate(rot13table)

 No, I don't actually need rot13 itself, it's just a convenient
 substitute example for the real job-specific task. No, I don't
 have to do it with lambdas, but it would be nice if the final
 function was a lambda.

How would it being a lambda help you?

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


Re: How much memory used by a name

2007-02-14 Thread Diez B. Roggisch
Bernard Lebel wrote:

 Hello,
 
 I would like to know if there is a way to know how much memory (bytes,
 kilobytes, megabytes, etc) a name is using.
 
 More specifically, I have this list of strings that I want to write to
 a file as lines.
 This list grows througout the script execution, and toward the end,
 the file is written.
 
 However I would like to know how much memory, before writing to the
 file, is this list using. Is it possible at all?

How about summing up the individual string lengths?

total = sum(len(s) for s in my_list)


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


Re: How to ping and shutdown a remote computer?

2007-02-14 Thread Tim Golden
[EMAIL PROTECTED] wrote:
 Here is my current setup:
 
  [... BSD ...]
 - Windows XP machine with folder share (What packet is sent over the
 network to remotely shutdown a Windows XP machine?)
 
 My hope is to have a script then when you start it will list all your
 remote computers/servers and show if they are currently on/off. Then
 you can select a server and turn it off if it is on or turn it on if
 it is off.

Couple of bits of info, speaking only about Windows. First, I'd
be quite worried if someone could send me a packet (maliciously
or otherwise) which simply shut my machine down. Is this possible?
Second, machines -- or networks -- may be configured to reject
or swallow pings so the lack of a ping may not indicate vitality.

Since you specify that the machine has a folder share, that means
it's running SMB/NMB/whatever it's called across a few well-known
ports, including 135 and 137-139 and 445. So you could attempt a
socket connection to one of those:

code
import socket
s = socket.socket ()
s.settimeout (0.25)
try:
   s.connect ((192.168.100.84, 135))
except socket.error:
   print not alive
else:
   print alive

/code

To shut it down, someone has already suggested the
shutdown command, although I think you'd have to
specify the -m param to pass the remote machine name.
Alternatively, you could use WMI (which inadvertently
provides a means of determining vitality):

http://timgolden.me.uk/python/wmi_cookbook.html#reboot_remote_machine

(adapted a bit, but you get the idea)

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


Re: Testers please

2007-02-14 Thread Don Taylor
martien friedeman wrote:
 I have written this tool that allows you to look at runtime data and  
 code at the same time.
 And now I need people to test it.
 
 The easiest way to see what I mean is to look at some videos:
 http://codeinvestigator.googlepages.com/codeinvestigator_videos
 
 It requires Apache and Sqlite.
 
 It works for me with a Firefox browser on Linux. 
   

ODB, the Omniscient Debugger, for Java does the same sort of thing and more.

http://www.lambdacs.com/debugger/ODBDescription.html

I would love to have one of these for Python.

Don.

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


Urllib2 and timeouts

2007-02-14 Thread Johny
In my script I started using urllib2 to connect to a list of
servers.It works well but only  until  a server from the list is not
available.Then if it is down , there is a timeout and my script ends
with the error.
So, if I have a list of 10 servers, and the second from the list is
not available , no others are used.
Is there a way how to solve that problem, so that servers after  the
server that is  not available will be used  too?
Thanks for help
L.

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


Re: rot13 in a more Pythonic style?

2007-02-14 Thread Martin P. Hellwig
Andy Dingley wrote:
 I'm trying to write rot13, but to do it in a better and more Pythonic
 style than I'm currrently using. What would  you reckon to the
 following pretty ugly thing?   How would you improve it?  In
 particular, I don't like the way a three-way selection is done by
 nesting two binary selections. Also I dislike stating the same
 algorithm twice, but can't see how to parameterise them neatly.
 
 Yes, I know of .encode() and .translate().
 No, I don't actually need rot13 itself, it's just a convenient
 substitute example for the real job-specific task.
 No, I don't have to do it with lambdas, but it would be nice if the
 final function was a lambda.
 
 
 #!/bin/python
 import string
 
 lc_rot13 = lambda c : (chr((ord(c) - ord('a') + 13) % 26 + ord('a')))
 
 uc_rot13 = lambda c : (chr((ord(c) - ord('A') + 13) % 26 + ord('A')))
 
 c_rot13 = lambda c : (((c, uc_rot13(c)) [c in
 'ABCDEFGHIJKLMNOPQRSTUVWXYZ']), lc_rot13(c) )[c in
 'abcdefghijklmnopqrstuvwxyz']
 
 rot13 = lambda s : string.join([ c_rot13(c) for c in s ],'')
 
 
 print rot13( 'Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt' )
 

Well first of all, for me (personal) being Pythonic means that I should 
separate the logic and variables, in this case there is the rotation 
mechanism and the variable with the amount it should rotate.
Then of course the letters case is something I consider as a state of 
the letter itself, the meaning of the letter doesn't change.
And being a sucker for dictionaries I use them a lot

So with that in mind I would write a class like this:
###
class Rot(object):
 def __init__(self,amount = 13):
 self.__alpha = 'abcdefghijklmnopqrstuvwxyz'
 self.__amount = amount
 self.__index_string = dict()
 self.__crypt_index_string = dict()
 self.__string_index = dict()
 self.__crypt_string_index = dict()
 self.__position = 0

 self.__create_dicts()


 def __cypher(self,number):
 alpha_len = len(self.__alpha)
 rotation_overflow = alpha_len - self.__amount
 new_number = None

 if number  rotation_overflow:
 new_number = number - self.__amount

 else:
 new_number = self.__position + self.__amount

 return(new_number)


 def __create_dicts(self):
 for letter in self.__alpha:
 self.__position += 1

 self.__index_string[self.__position] = letter
 self.__crypt_index_string[self.__cypher(self.__position)] = 
letter

 self.__string_index[letter] = self.__position
 self.__crypt_string_index[letter] = 
self.__cypher(self.__position)


 def encrypt(self,text):
 text_list = list()
 letter_capital = None

 for letter in text:
 letter_capital = letter.isupper()
 letter = letter.lower()

 if letter not in self.__alpha:
 text_list.append(letter)

 else:
 position_plain = self.__string_index[letter]
 letter_crypt = self.__crypt_index_string[position_plain]

 if letter_capital:
 letter_crypt = letter_crypt.upper()

 text_list.append(letter_crypt)

 return(.join(text_list))


 def decrypt(self,text):
 text_list = list()
 letter_capital = None

 for letter in text:
 letter_capital = letter.isupper()
 letter = letter.lower()

 if letter not in self.__alpha:
 text_list.append(letter)

 else:
 position_crypt = self.__crypt_string_index[letter]
 letter_plain = self.__index_string[position_crypt]

 if letter_capital:
 letter_plain = letter_plain.upper()

 text_list.append(letter_plain)

 return(.join(text_list))
###

Testing if it works:
  rot13.decrypt(rot13.encrypt(This is a TEST))
'This is a TEST'

-- 
mph

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


Re: Urllib2 and timeouts

2007-02-14 Thread Larry Bates
Johny wrote:
 In my script I started using urllib2 to connect to a list of
 servers.It works well but only  until  a server from the list is not
 available.Then if it is down , there is a timeout and my script ends
 with the error.
 So, if I have a list of 10 servers, and the second from the list is
 not available , no others are used.
 Is there a way how to solve that problem, so that servers after  the
 server that is  not available will be used  too?
 Thanks for help
 L.
 
Wrap your connection inside a try: block.  That way you can catch
the exception and continue your loop.

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


Re: rot13 in a more Pythonic style?

2007-02-14 Thread Andy Dingley
On 14 Feb, 16:23, Neil Cerutti [EMAIL PROTECTED] wrote:

 str.translate is what I'd do.

That's what I hope to do too, but it might not be possible (for the
live, complex example). It looks as if I have to make a test, then
process the contents of the code differently depending. There might
well be a translation inside this, but I think I still have to have an
explicit 3-way switch in there.



 How would it being a lambda help you?

I'm going to use it in a context where that would make for cleaner
code. There's not much in it though.

I still don't understand what a lambda is _for_ in Python. I know what
they are, I know what the alternatives are, but I still haven't found
an instance where it permits something novel to be done that couldn't
be done otherwise (if maybe not so neatly).

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


list of range of floats

2007-02-14 Thread Steve
I'm trying to create a list range of floats and running into problems. 
I've been trying something like:

a = 0.0
b = 10.0

flts = range(a, b)

fltlst.append(flts)   

When I run it I get the following DeprecationWarning: integer argument 
expected, got float. How can I store a list of floats?

TIA
Steve

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


Re: list of range of floats

2007-02-14 Thread Simon Brunning
On 2/14/07, Steve [EMAIL PROTECTED] wrote:
 I'm trying to create a list range of floats and running into problems.
 I've been trying something like:

 a = 0.0
 b = 10.0

 flts = range(a, b)

 fltlst.append(flts)

 When I run it I get the following DeprecationWarning: integer argument
 expected, got float. How can I store a list of floats?

There would be an *enormous* number of floats between zero and ten. Do
you really want all of them in your list? I hope you have a few
terrabytes of RAM...

Or do you just want the integer values as floats?

fits = list(float(a) for a in range(0, 10))

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


Re: list of range of floats

2007-02-14 Thread Dale Strickland-Clark
Steve wrote:

 I'm trying to create a list range of floats and running into problems.
 I've been trying something like:
 
 a = 0.0
 b = 10.0
 
 flts = range(a, b)
 
 fltlst.append(flts)
 
 When I run it I get the following DeprecationWarning: integer argument
 expected, got float. How can I store a list of floats?
 
 TIA
 Steve

range only does ints. If you want floats, you'll have to write your own
version.

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


Re: list of range of floats

2007-02-14 Thread Steve
On Wed, 14 Feb 2007 17:27:06 +, Dale Strickland-Clark wrote:

 Steve wrote:
 
 I'm trying to create a list range of floats and running into problems.
 I've been trying something like:
 
 a = 0.0
 b = 10.0
 
 flts = range(a, b)
 
 fltlst.append(flts)
 
 When I run it I get the following DeprecationWarning: integer argument
 expected, got float. How can I store a list of floats?
 
 TIA
 Steve
 
 range only does ints. If you want floats, you'll have to write your own
 version.

I was afraid of that. Thanks for the quick reply.

Steve

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


Re: list of range of floats

2007-02-14 Thread Matimus
 fits = list(float(a) for a in range(0, 10))

Another way of writing that:

flts = map(float,range(10))

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


Re: list of range of floats

2007-02-14 Thread Larry Bates
Steve wrote:
 I'm trying to create a list range of floats and running into problems. 
 I've been trying something like:
 
 a = 0.0
 b = 10.0
 
 flts = range(a, b)
 
 fltlst.append(flts)   
 
 When I run it I get the following DeprecationWarning: integer argument 
 expected, got float. How can I store a list of floats?
 
 TIA
 Steve
 
What does range of floats mean?  How many floats are there
between 0.0 and 10.0?  If you want the step to be 1.0
and beginning and ending values will be whole numbers then
this will work:

flts=[float(i) for i in range(1, 11)]

If you want arbitrary starting and ending floats and an
arbitrary step, you will need to write your own function.

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


Re: rot13 in a more Pythonic style?

2007-02-14 Thread Gabriel Genellina
En Wed, 14 Feb 2007 14:04:17 -0300, Andy Dingley [EMAIL PROTECTED]  
escribió:

 I still don't understand what a lambda is _for_ in Python. I know what
 they are, I know what the alternatives are, but I still haven't found
 an instance where it permits something novel to be done that couldn't
 be done otherwise (if maybe not so neatly).

A lambda is a shorthand for a simple anonymous function. Any lambda can be  
written as a function:

lambda args: expression

is the same as:

def __anonymous(args): return expression

(but the inverse is not true; lambda only allows a single expression in  
the function body).

Except for easy event binding in some GUIs, deferred argument evaluation,  
and maybe some other case, the're not used much anyway. Prior common usage  
with map and filter can be replaced by list comprehensions (a lot more  
clear, and perhaps as fast - any benchmark?)

-- 
Gabriel Genellina

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


Re: list of range of floats

2007-02-14 Thread [EMAIL PROTECTED]
a = 0.0
b = 10.0
inc = .2
flts = []
while a  b:
flts.append(a)
a += inc


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


Re: multiple inheritance of a dynamic list of classes?

2007-02-14 Thread Peter Otten
Neil Cerutti wrote:

 On 2007-02-13, Peter Otten [EMAIL PROTECTED] wrote:
 Well, what problems ocurring with

 class A: pass
 class B: pass
 class C(A, B): pass

 could be avoided by writing

 class A: pass
 class B(A): pass
 class C(B): pass

 instead?
 
 With multiple inheritance, the choice of algorithm for Method
 Resolution Ordering isn't obvious or trivial. As I understand it,
 Python got it wrong for quite some time, allowing bad
 hierarchies to compile, i.e., classes for which the properties of
 local precedence ordering and monotonicity did not hold.
 
 URL:http://www.python.org/download/releases/2.3/mro/

Is it correct that as long as no classes occur twice in the hierarchy no
such ambiguities can arise?

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


Re: multiple inheritance of a dynamic list of classes?

2007-02-14 Thread Peter Otten
massimo s. wrote:

 On 13 Feb, 12:46, Peter Otten [EMAIL PROTECTED] wrote:
 Well, what problems ocurring with

 class A: pass
 class B: pass
 class C(A, B): pass

 could be avoided by writing

 class A: pass
 class B(A): pass
 class C(B): pass

 instead? Classes have to be designed for subclassing, so essentially you
 get two interfaces, one for subclasses and one for client code instead of
 just the latter. A more relevant mantra governing inheritance is Flat is
 better than nested.
 
 I am truly getting lost. Are you saying that doing A--B(A)--C(B) is
 better than C(A,B)? And isn't the former thing nested? Or are you
 saying that C(A,B) is better than A,B(A),C(B)? And in both cases:why?

Neither. I wanted to express that I don't buy the mantra you mentioned
above. Just because it uses only single inheritance code doesn't become
magically more robust. Use whatever works best to solve the actual problem.
 
 And why classes have to be designed for subclassing? I often do
 classes that are not thought to be subclassed.

That's fine. If (and only if) you expect a class to be subclassed you better
spend some thought on what methods should be overriden etc. This increases
the effort spent on the class significantly. Distinct classes are often
easier to write and maintain.

Hope-I'm-clear-this-time,
Peter

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


Re: How to ping and shutdown a remote computer?

2007-02-14 Thread joja15
On Feb 14, 10:09 am, Christophe [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] a écrit :



  I am working on a Python script to perform as a remote computer
  manager. So far I have a WOL function working and I would like to add
  the ability to show if a machine is on or off (I figured I would do so
  by pinging the machine and seeing if I get a response). I would also
  like to add the ability to remotely shutdown a computer from the
  python script. Does anyone have a code snippet for pinging an IP, a
  code snippet for shutting down a remote Windows XP machine, and a code
  snippet for sending a HTTP request?

  Here is my current setup:

  - PC  running python script
  - FreeNAS (media server running on FreeBSD. Can be shutdown from web
  interface so I planned on just sending that same web button click from
  the python script to shutdown the FreeNAS server)
  - Windows XP machine with folder share (What packet is sent over the
  network to remotely shutdown a Windows XP machine?)

 import os
 os.system(shutdown -s -f)
 Try other switches if you want. Requires Windows XP at the minimum.

That is a good idea but I don't have Windows XP on the machine
performing the shutdown. I should have been more detailed. I said PC
but what it is is a Xbox running XBMC: http://www.xboxmediacenter.com

I should have been more detailed in that.

- John

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


Re: Newbie Question

2007-02-14 Thread David Boddie
On Tuesday 13 February 2007 11:04, [EMAIL PROTECTED] wrote:

 To be true, I don't know if any of these toolkits (GTK, wxWindows, QT)
 and their GUIDesigners have the features you like in Delphi. What I
 know is that:
 1/ these three toolkits have everything *needed* to write serious GUI
 apps
 2/ they are all (more or less) portable
 3/ the first two are free software

And, for the sake of completeness, it should be mentioned that the third
is available under the GPL, which is a Free Software license.

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


Re: list of range of floats

2007-02-14 Thread Steve
On Wed, 14 Feb 2007 17:29:26 +, Simon Brunning wrote:

 On 2/14/07, Steve [EMAIL PROTECTED] wrote:
 I'm trying to create a list range of floats and running into problems.
 I've been trying something like:

 a = 0.0
 b = 10.0

 flts = range(a, b)

 fltlst.append(flts)

 When I run it I get the following DeprecationWarning: integer argument
 expected, got float. How can I store a list of floats?
 
 There would be an *enormous* number of floats between zero and ten. Do
 you really want all of them in your list? I hope you have a few
 terrabytes of RAM...
 
 Or do you just want the integer values as floats?
 
 fits = list(float(a) for a in range(0, 10))

After re-reading my original post I was pretty vague. I'm trying to creat
a list of ranges of floats, 0.0 10.0, 11 20, etc then checking to see if
an float, example 12.5 falls in the list and if so get the list index of 
where it is in the index. Does this make sense?

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


Re: list of range of floats

2007-02-14 Thread Simon Brunning
On 2/14/07, Steve [EMAIL PROTECTED] wrote:
 After re-reading my original post I was pretty vague. I'm trying to creat
 a list of ranges of floats, 0.0 10.0, 11 20, etc then checking to see if
 an float, example 12.5 falls in the list and if so get the list index of
 where it is in the index. Does this make sense?

Ah, you want to know if a certain number is between to other numbers.
That's not what range() is for - range() is for generating lists of
integers. You can use it to do a between test for integers, I suppose,
but even for integers it's a pretty poor way of going about it -
you'll be creating a potentially large lists of integers, only to
throw it away again.

Consider something like:

def between(lower, upper, target):
return lower  target  upper

Works for integers and floats interchangably. Or better still, do the
lower  target  upper thing inline.

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


Re: Testers please

2007-02-14 Thread Martien Friedeman
That's amazing!
We had the same idea.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiple inheritance of a dynamic list of classes?

2007-02-14 Thread Neil Cerutti
On 2007-02-14, Peter Otten [EMAIL PROTECTED] wrote:
 Neil Cerutti wrote:

 On 2007-02-13, Peter Otten [EMAIL PROTECTED] wrote:
 Well, what problems ocurring with

 class A: pass
 class B: pass
 class C(A, B): pass

 could be avoided by writing

 class A: pass
 class B(A): pass
 class C(B): pass

 instead?
 
 With multiple inheritance, the choice of algorithm for Method
 Resolution Ordering isn't obvious or trivial. As I understand it,
 Python got it wrong for quite some time, allowing bad
 hierarchies to compile, i.e., classes for which the properties of
 local precedence ordering and monotonicity did not hold.
 
 URL:http://www.python.org/download/releases/2.3/mro/

 Is it correct that as long as no classes occur twice in the
 hierarchy no such ambiguities can arise?

As long as you forbid the diamond-shaped hierarchy, I think so.
Of course, since all new-style classes inherit from 'object' you
can't avoid it in practice, and a good algorithm for MRO had to
be stolen from Dylan. ;)

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


try...except...finally problem in Python 2.5

2007-02-14 Thread redawgts
I keep getting this error local variable 'f' referenced before
assignment in the finally block when I run the following code.

try:
f = file(self.filename, 'rb')
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True
except:
self.isDataLoaded = False
finally:
f.close()

Can someone tell me what's wrong with the code? Am I doing something
wrong? I'm somewhat new to python but this makes sense to me.

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


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Jean-Paul Calderone
On 14 Feb 2007 11:41:29 -0800, redawgts [EMAIL PROTECTED] wrote:
I keep getting this error local variable 'f' referenced before
assignment in the finally block when I run the following code.

try:
f = file(self.filename, 'rb')
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True
except:
self.isDataLoaded = False
finally:
f.close()

Can someone tell me what's wrong with the code? Am I doing something
wrong? I'm somewhat new to python but this makes sense to me.


f is not bound until the first line of the try suite has completely
successfully executed.  If it fails to do this, for example because
self.filename is an attribute error, or the filename given by that
attribute does not exist, then the finally suite will execute before
f has been bound, and the UnboundLocalError will mask the real error.

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


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Robert Kern
redawgts wrote:
 I keep getting this error local variable 'f' referenced before
 assignment in the finally block when I run the following code.
 
 try:
 f = file(self.filename, 'rb')
 f.seek(DATA_OFFSET)
 self.__data = f.read(DATA_SIZE)
 self.isDataLoaded = True
 except:
 self.isDataLoaded = False
 finally:
 f.close()
 
 Can someone tell me what's wrong with the code? Am I doing something
 wrong? I'm somewhat new to python but this makes sense to me.

Move the f = file(self.filename, 'rb') above the try:. If opening the file
happens to throw an exception, then the assignment will never happen and there
will be no 'f' to close.

-- 
Robert Kern

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

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


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Andrew Koenig
redawgts [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

I keep getting this error local variable 'f' referenced before
 assignment in the finally block when I run the following code.

try:
f = file(self.filename, 'rb')
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True
except:
self.isDataLoaded = False
finally:
f.close()

 Can someone tell me what's wrong with the code? Am I doing something
 wrong? I'm somewhat new to python but this makes sense to me.

If the call to file raises an exception, then variable f won't have been 
created.

Here's a simple example:

def f():
throw 42
try:
x = f()
except:
print x

Try it and see what happens.  While you're at it, you might try to figure 
out what you would like it to print.



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


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Larry Bates
redawgts wrote:
 I keep getting this error local variable 'f' referenced before
 assignment in the finally block when I run the following code.
 
 try:
 f = file(self.filename, 'rb')
 f.seek(DATA_OFFSET)
 self.__data = f.read(DATA_SIZE)
 self.isDataLoaded = True
 except:
 self.isDataLoaded = False
 finally:
 f.close()
 
 Can someone tell me what's wrong with the code? Am I doing something
 wrong? I'm somewhat new to python but this makes sense to me.
 
finally: block is executed even if there is an exception in which case f
hasn't been defined.  What you want is:

try:
f = file(self.filename, 'rb')
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True

except:
isDataLoaded=False

else:
f.close()

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


Re: rot13 in a more Pythonic style?

2007-02-14 Thread Beej
On Feb 14, 9:04 am, Andy Dingley [EMAIL PROTECTED] wrote:
 I still don't understand what a lambda is _for_ in Python.

Python supports functional programming to a certain extent, and
lambdas are part of this.

http://linuxgazette.net/109/pramode.html

 I know what
 they are, I know what the alternatives are, but I still haven't found
 an instance where it permits something novel to be done that couldn't
 be done otherwise (if maybe not so neatly).

Strictly speaking, you can live your whole life without using them.
There's always a procedural way of doing things, as well.

-Beej

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


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Paul Rubin
redawgts [EMAIL PROTECTED] writes:
 try:
 f = file(self.filename, 'rb') ...
 Can someone tell me what's wrong with the code? 

Various people have explained the error: if the file open attempt
fails, f is never assigned.  Doing it the right way (i.e. handling the
potential exceptions separately) with try/except statements is messy,
so it's worth mentioning that 2.5 adds the new with statement to
clean this up.  I'm not using 2.5 myself yet so maybe someone will
have to correct me, but I think you'd write:

from __future__ import with_statement

self.isDataLoaded = False
with open(self.filename, 'rb') as f:
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True

and that should handle everything, closing the file automatically.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Segmentation faults using threads

2007-02-14 Thread John Nagle
Mathias wrote:

 What module are you using for SSH?

 What's in your program that isn't pure Python?
 The problem is probably in some non-Python component; you shouldn't
 be able to force a memory protection error from within Python code.

 
 It looks like the error could be in scipy/Numeric, when a large array's 
 type is changed, like this:
 
   from scipy import *
   a=zeros(1,'b')#100 MiB
   b=a.copy().astype('d')  #800 MiB, ok
   a=zeros(10,'b')#1GiB
   b=a.copy().astype('d')  #8GiB, fails with sf
 Segmentation fault
 
 if I use zeros directly for allocation of the doubles it works as expected:
 
   from scipy import *
   a=zeros(10,'d')#8GiB, fails with python exception
 Traceback (most recent call last):
   File stdin, line 1, in ?
 MemoryError: can't allocate memory for array
  
 
 I use python 2.4, but my scipy and Numeric aren't quite up-to-date: 
 scipy version 0.3.2, Numeric v 24.2

That sounds like the case where the array has to be reallocated from
4-byte floats to 8-byte doubles is being botched.

Take a look at 
http://www.mail-archive.com/numpy-discussion@lists.sourceforge.net/msg02033.html;

and then at array_cast in arrraymethods.c of scipy.  There may be a
reference count bug in that C code.  I'm not familiar enough with
Python reference count internals to be sure, though.

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


Re: How much memory used by a name

2007-02-14 Thread Bruno Desthuilliers
Bernard Lebel a écrit :
 Hello,
 
 I would like to know if there is a way to know how much memory (bytes,
 kilobytes, megabytes, etc) a name is using.
 
 More specifically, I have this list of strings that I want to write to
 a file as lines.
 This list grows througout the script execution, and toward the end,
 the file is written.

Do you really need to first grow the list then write it ?

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


reference data in a dictionary

2007-02-14 Thread Wensui Liu
dear all,
i am new to python and have a question about referencing data in a dict.
is there anyway that allows me to do something like:
dict[['row1', 'row2', .'row100']]

thanks much.

-- 
WenSui Liu
A lousy statistician who happens to know a little programming
(http://spaces.msn.com/statcompute/blog)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threading and multicores, pros and cons

2007-02-14 Thread Nikita the Spider
In article [EMAIL PROTECTED],
 Maric Michaud [EMAIL PROTECTED] wrote:

 This is a recurrent problem I encounter when I try to sell python solutions 
 to 
 my customers. I'm aware that this problem is sometimes overlooked, but here 
 is the market's law.
 
 I've heard of a bunch of arguments to defend python's choice of GIL, but I'm 
 not quite sure of their technical background, nor what is really important 
 and what is not. These discussions often end in a prudent python has made a 
 choice among others... which is not really convincing.
 
 If some guru has made a good recipe, or want to resume the main points it 
 would be really appreciated.

When designing a new Python application I read a fair amount about the 
implications of multiple cores for using threads versus processes, and 
decided that using multiple processes was the way to go for me. On that 
note, there a (sort of) new module available that allows interprocess 
communication via shared memory and semaphores with Python. You can find 
it here: 
http://NikitaTheSpider.com/python/shm/

Hope this helps

-- 
Philip
http://NikitaTheSpider.com/
Whole-site HTML validation, link checking and more
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reference data in a dictionary

2007-02-14 Thread Ben Finney
Wensui Liu [EMAIL PROTECTED] writes:

 i am new to python and have a question about referencing data in a
 dict.  is there anyway that allows me to do something like:

 dict[['row1', 'row2', .'row100']]

What behaviour would you expect from that statement? If we know what
you're trying to do, perhaps we can suggest a solution.

-- 
 \Like the creators of sitcoms or junk food or package tours, |
  `\ Java's designers were consciously designing a product for |
_o__)people not as smart as them.  -- Paul Graham |
Ben Finney

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


Re: How much memory used by a name

2007-02-14 Thread Bernard Lebel
Diez: thanks, I will try that. However isn't sum() returning an
integer that here would represent the number of elements?


Bruno: good question. We're talking about text files that can have
300,000 lines, if not more. Currently, the way I have coded the file
writing, every line calls for a write() to the file object, which in
turns write to the text file. The file is on the network.

This is taking a long time, and I'm looking for ways to speed up this
process. I though that keeping the list in memory and dropping to the
file at the very end could be a possible approach.


Bernard




On 2/14/07, Bruno Desthuilliers [EMAIL PROTECTED] wrote:
 Bernard Lebel a écrit :
  Hello,
 
  I would like to know if there is a way to know how much memory (bytes,
  kilobytes, megabytes, etc) a name is using.
 
  More specifically, I have this list of strings that I want to write to
  a file as lines.
  This list grows througout the script execution, and toward the end,
  the file is written.

 Do you really need to first grow the list then write it ?

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

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


Re: reference data in a dictionary

2007-02-14 Thread Wensui Liu
I know dict['row1'] will always work. but it will only get 1 row out
of the dict. is there anyway i can get multiple (1) rows out of dict
by directly refeencing them, something like dict[['row1', 'row2']].

thank you for reply, Ben.

wensui

On 2/14/07, Ben Finney [EMAIL PROTECTED] wrote:
 Wensui Liu [EMAIL PROTECTED] writes:

  i am new to python and have a question about referencing data in a
  dict.  is there anyway that allows me to do something like:

  dict[['row1', 'row2', .'row100']]

 What behaviour would you expect from that statement? If we know what
 you're trying to do, perhaps we can suggest a solution.

 --
  \Like the creators of sitcoms or junk food or package tours, |
   `\ Java's designers were consciously designing a product for |
 _o__)people not as smart as them.  -- Paul Graham |
 Ben Finney

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



-- 
WenSui Liu
A lousy statistician who happens to know a little programming
(http://spaces.msn.com/statcompute/blog)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reference data in a dictionary

2007-02-14 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Wensui Liu
wrote:

 I know dict['row1'] will always work. but it will only get 1 row out
 of the dict. is there anyway i can get multiple (1) rows out of dict
 by directly refeencing them, something like dict[['row1', 'row2']].

Not by directly referencing them, but with a list comprehension::

  result = [the_dict[key] for key in ('row1', 'row2', 'row3')]

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


f---ing typechecking

2007-02-14 Thread Sergey Dorofeev
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on 
win32
Type help, copyright, credits or license for more information.
 (1,)+[1]
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: can only concatenate tuple (not list) to tuple
 [1]+(1,)
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: can only concatenate list (not tuple) to list


Its ugly and boring. 


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


  1   2   >