Re: How to request data from a lazily-created tree structure ?

2008-06-23 Thread méchoui
On Jun 17, 11:54 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > Do you know if there is suchXPathengine that can be applied to a DOM-
> > like structure ?
>
> No. But I toyed with the idea to write one :)
>
> > One way would be to take anXPathengine from an existing XML engine
> > (ElementTree, or any other), and see what APIs it calls... and see if
> > we cannot create a DOM-like structure that has the same API. Duck
> > typing, really...
>
> Why can't you create a *real* DOM?
>
> Diez

I may have found sg: http://sourceforge.net/projects/pdis-xpath/

A XPath 1.0, in pure python, on top of ElementTree. I'll have a look.
--
http://mail.python.org/mailman/listinfo/python-list


Re: An idiom for code generation with exec

2008-06-23 Thread Bruno Desthuilliers

eliben a écrit :

   d = {}
 execcode in globals(), d
  return d['foo']

My way:

  return function(compile(code, '', 'exec'), globals())



With some help from the guys at IRC I came to realize your way doesn't
do the same. It creates a function that, when called, creates 'foo' on
globals(). This is not exactly what I need.


I possibly messed up a couple things in the arguments, flags etc - I 
very seldom use compile() and function(). The point was that  it didn't 
require any extra step.

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


Re: Ruby doctest

2008-06-23 Thread Duncan Booth
Paddy <[EMAIL PROTECTED]> wrote:

> I monitor changes to the Wikipedia doctest page, and so noticed a
> change in the Ruby implementation of doctest.
> 
> Scooting around their implementation I found that they have an !!!
> special directive that says drop into the interpreter at this point
> when testing allowing debugging in context.
> http://github.com/tablatom/rubydoctest/wikis/special-directives
> 
Whereas Python has the more wordy version which works anywhere in ordinary 
code or in doctests:

>>> import pdb; pdb.set_trace()


-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python in a group

2008-06-23 Thread windstorm
On Jun 23, 1:12 pm, Mensanator <[EMAIL PROTECTED]> wrote:
> On Jun 22, 5:43�am, "Jonathan Roberts" <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > Hi all,
>
> > I'm looking to learn Python (as my first programming language) and I'm
> > pretty sure I'd be more successful doing this with a group of other
> > people.
>
> > I've currently got one other person to learn with me, and we plan to
> > work remotely over the net using tools such as IM/VoiP/Gobby/WIkis
> > etc. We'd still like a few others to work with us, with a group of
> > about 5 or 6 being seen as ideal. We'd also like to find somebody to
> > act as a mentor/guide who might be happy to meet with us once every
> > couple of weeks to help keep us moving in the right direction and find
> > solutions to problems when we get really stuck!
>
> > Wondered if there was anybody here who might be interested in working
> > with us in either of these roles? We both have differing goals, but
> > ultimately we'd just like to get more familiar so that we can provide
> > some simple fixes to packages we maintain/scratch a few itches of our
> > own. Any one is welcome, no matter what your own aim :)
>
> > Would love to hear feedback, especially from anyone who's interested
> > in working with us...
>
> Have you considered creating your own Google Group?
>
>
>
> > Best,
>
> > Jon
>
>

Yeah, set up your personal Google group, post the address here and ask
people who want to join in sounds like a better idea rather than
asking here. Considering time-zone, I don't know how you guys
communicate with each other "real-time". So "post in group, get
discuss and reply" may make more sense.
--
http://mail.python.org/mailman/listinfo/python-list

Python module for working with a sudden motion sensor on Linux

2008-06-23 Thread Chris Ortner
Hi everyone,

I am looking for a python module or something similar which makes use
of the capabilities of the kernel module applesmc to provide support
for the sudden motion sensor in Apple hardware. It should be something
like this:
http://pypi.python.org/pypi/PyAppleSMS/1.0

Would it make sense to look for a generic accelerometer module or do I
have to use something specific?

Thanks for your help in advance!

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


2to3 bug and question

2008-06-23 Thread Helmut Jarausch

Hi,

is this the right group to ask / report problems with python3.0 ?

The question:
Is it possible to tell 2to3 to replace, say,
#!/usr/bin/python

by

#!/usr/local/bin/python3.0

?

Here the bug:

While 2to3 keeps  the first line
#!/usr/bin/python

it removes the first line if it was

#!/usr/bin/python -O

Is this a bug or a feature?

Thanks for hint,

Helmut Jarausch

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


Re: An idiom for code generation with exec

2008-06-23 Thread Maric Michaud
Le Monday 23 June 2008 09:22:29 Bruno Desthuilliers, vous avez écrit :
> > With some help from the guys at IRC I came to realize your way doesn't
> > do the same. It creates a function that, when called, creates 'foo' on
> > globals(). This is not exactly what I need.
>
> I possibly messed up a couple things in the arguments, flags etc - I
> very seldom use compile() and function(). The point was that  it didn't
> require any extra step.

In the argument list  of function type, the code object in first place is 
expected to be created directly (no exec - eval) with the python type 'code' 
(either found as types.CodeType or new.code).


In [24]: types.CodeType?
Type:   type
Base Class: 
String Form:
Namespace:  Interactive
Docstring:
code(argcount, nlocals, stacksize, flags, codestring, constants, names,
  varnames, filename, name, firstlineno, lnotab[, freevars[, 
cellvars]])

Create a code object.  Not for the faint of heart.

  ^^^

Even if it looks more "object oriented", I'm not sure it's actually the good 
solution for the original problem. I think these interface are not a 
replacement for the quick eval-exec idiom but more intended to make massive 
code generation programs object oriented and closer to python internals.

AFAIK, the only use case I see code generation (eval - exec, playing with code 
objects) as legitime in python is in programs that actually do code 
generation, that is, parse and compile code from textual inputs (application 
buillders).

If code generation is not the best, and I fail to see any performance issue 
that could explain such a choice, except a misunderstanding of 
what "compilation" means in python, just don't use it, use closures or 
callable instances, there are many way to achieve this.

-- 
_

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


Re: how to send a "Multiline" mail with smtplib?

2008-06-23 Thread Evan
On Jun 19, 6:12 pm, Lie <[EMAIL PROTECTED]> wrote:
> On Jun 19, 4:02 pm, Justin Ezequiel <[EMAIL PROTECTED]>
> wrote:
>
> > perhaps change html
>
> > body=MIMEText('hello,\r\n
> > ok',_subtype='html',_charset='windows-1255')
>
> > to plain
>
> > body=MIMEText('hello,\r\n
> > ok',_subtype='plain',_charset='windows-1255')
>
> If that was the case, and you needed a line break in html-mode, use
>  or  tags.


Thanks all,
and yes, if I use "plain" or use HTML tag "", it worked:
(1) HTML:
I use tag "" and " ", and when I reply that mail, I will
see "" tag in mail content, it is not a good option.


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


[2to3] Bug converting import

2008-06-23 Thread Helmut Jarausch

Hi

Given the following two files in the same directory

Master.py:
--
#!/usr/bin/python
import Slave
Slave.main()

and
Slave.py:
-
def main() :
  print "Hello World"

Invoking Master.py under python-2.5.2
works just fine.

2to3 converts these to

Master.py:
--
from . import Slave
Slave.main()

I have added the first line
#!/usr/local/bin/python3.0
manually

Slave.py:
-
def main() :
  print("Hello World")


Now, when I invoke Master.py  I get

Traceback (most recent call last):
  File "Master.py", line 2, in 
from . import Slave
ValueError: Attempted relative import in non-package


thanks for looking into it,

Helmut Jarausch

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


Re: pyTTS says, '"SAPI" not supported'

2008-06-23 Thread Tim Golden

weheh wrote:

I'm running Python 2.3 and calling pyTTS. I've had it working forever.

Today, I ran out of disk space. After deleting some of my personal files, 
for no apparent reason, pyTTS no longer runs.


For the statement

tts = pyTTS.Create()

I get the error message:

ValueError: "SAPI" not supported

Can anybody help me? What's going on? 


(Hint: you'd have helped if you'd provided the whole
traceback).

Well, going by pyTTS v3.0 for Python 2.5, that error
comes from the __init__.py of the pyTTS package when
either you've specified a speech package other than
"SAPI" (the default) or the sapi module couldn't be imported.
My conclusion would be that you've accidentally removed some
part of the sapi package.

What happens if you open the interpreter (possibly with -v for
more info) from within the pyTTS folder and and do "import sapi"?

C:\Python25\Lib\site-packages\pyTTS>python -v -c "import sapi"

TJG

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


Re: binary number format ? format character %b or similar.

2008-06-23 Thread Ken Starks

Mensanator wrote:

On Jun 22, 4:07�pm, Ken Starks <[EMAIL PROTECTED]> wrote:

weheh wrote:

I don't know if you found this example:
http://www.daniweb.com/code/snippet285.html

Thanks for that. The offerings are very similar to the
algorithms I wrote myself.

It wasn't the solution I was after,really; that's
easy. It was whether anything had found its way into
the standard library.


Isn't that coming in Python 3.0?


Thanks for the tip! following which, I found
information at:

http://docs.python.org/dev/3.0/library/string.html#formatstrings



You could also use gmpy, which has a lot of
other bit-functionality in addition to displaying
them.



Yes, that'll be useful. Thanks again.
--
http://mail.python.org/mailman/listinfo/python-list

Re: inheritance question...

2008-06-23 Thread Eric Brunel
Preamble: when posting a brand new question, you'd better not replying to  
an existing completely unrelated message. In most viewers, this will cause  
your message to appear in the thread for the original question and far  
less people will see it. So better create a brand new thread.


On Fri, 20 Jun 2008 23:19:37 +0200, Hamish McKenzie  
<[EMAIL PROTECTED]> wrote:

I have this class:

class Vector(object):
 TOL = 1e-5
 def __eq__( self, other, tolerance=TOL ):
   print tolerance


shortened for clarity obviously.  so I want to subclass this class like
so:

class BigVector(Vector)
 TOL = 100


for example if I was working with large vectors which I knew would never
be very close hence the large tolerance.  this doesn't work however -
the TOL class variable, while overridden in BigVector, is still using
the Vector.TOL variable in the __eq__ method.


which kinda makes sense to a certain degree, but how do I get the
behaviour where doing:

BigVector().__eq__( otherVec )


prints 100 instead of 1e-5?

does this question make sense?  not sure how clearly I'm phrasing my
question...  any of you guys python experts?


There's just no way. The default values for function/method arguments are  
evaluated when the function definition is interpreted. When the __eq__  
method is defined, TOL is 1e-5, so that will be the value used in the  
method, whatever you may do afterwards.




I *could* do this, but its ugly:

class Vector(object):
 TOL = 1e-5
 def __eq__( self, other, tolerance=None ):
   if tolerance is None: tolerance = self.TOL
   print tolerance


Well, ugliness is in the eye of the beholder... ;-) Even if you find it  
ugly, that's the Python way to do it.


HTH
--
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"

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


Re: how to export functions by name for ctype

2008-06-23 Thread Nick Craig-Wood
rych <[EMAIL PROTECTED]> wrote:
>  I'm on Windows with VS2005 testing ctypes on a very simple dll
>  I create a test.dll project which exports a function fntest(). I don't
>  touch anything in the autogenerated source and build it. I can load
>  the dll but can't access the function by its name fntest. Only by
>  ordinal number or calling getattr with "?fntest@@YAHXZ". How do I
>  export functions by name? It's probably rather a VS2005 question, but
>  I'm a bit disappointed ctypes doesn't work with a default export
>  convention.

I guess you've compiled your DLL with C++ and the above is a C++
mangled name.

Either compile it with C, or export the names in an extern "C" { }
block.


-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python in a group

2008-06-23 Thread ubikvist
I guess it's time to choose what a project your group will work at.
Personally, I'm working at the project relating to text analysis, but
it's rather specific because I use Russian texts. So, maybe we should
to choose more 'international' implementation.
-Ed
--
http://mail.python.org/mailman/listinfo/python-list


Re: listcomprehension, add elements?

2008-06-23 Thread Boris Borcic

John Machin wrote:


Instead of sum(a + b for a, b in zip(foo, bar))
why not use sum(foo) + sum(bar)
?


or even sum(foo+bar) as may apply.

Cheers, BB

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


Re: An idiom for code generation with exec

2008-06-23 Thread Bruno Desthuilliers

Maric Michaud a écrit :

Le Monday 23 June 2008 09:22:29 Bruno Desthuilliers, vous avez écrit :

With some help from the guys at IRC I came to realize your way doesn't
do the same. It creates a function that, when called, creates 'foo' on
globals(). This is not exactly what I need.

I possibly messed up a couple things in the arguments, flags etc - I
very seldom use compile() and function(). The point was that  it didn't
require any extra step.


In the argument list  of function type, the code object in first place is 
expected to be created directly (no exec - eval) with the python type 'code' 


Which is what compile returns. But indeed, re-reading compile's doc more 
carefully, I'm afraid that the code object it returns may not be usable 
the way I thought. My bad. sorry


(snip)

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


Sending arrays of a structure as an argument via ctypes

2008-06-23 Thread Knut Saua Mathiesen
Hi there.
I am reprogrammed my astar* path finding algorithm in C to make it quicker.
I am now trying to make python use this C extension, however I keep
getting "Segmentation fault".

Some of the C stuff:



typedef struct Point {
int x;
int y;
} Point;

typedef struct Node {
Point pos;
int cost;
int g;
int obstacle;
struct Node* parent;
} Node;

void astar(Node map[], Point from, Point to) {
(...)
}
main () {
(...)
Node map[maptotal];
(...)
astar(map, createPoint(0,0), createPoint(50,50));
}


Now I am by no means a C programmer, this is basicly the first "bigger
than hello-world" program, but I have got it working in C. What I am
now trying to do is to make the map using python, and send it to my
astar C function using ctypes.

Basicly I've rewritten my structures in python:


class Point(Structure):
_fields_ = [("x", c_int), ("y", c_int)]
def __repr__(self): return "" % (self.x, self.y)

class Node(Structure):
def __repr__(self):
return "" % (self.pos.x, self.pos.y)
Node._fields_ = [('pos', Point), ('cost', c_int), ('g', c_int),
('obstacle', c_int), ('parent',POINTER(Node))]



And after that, this is how I am trying to call it:

self.astar = astarlib.astar
self.astar.argtypes = [Node * self.maptotal, Point, Point]
self.astar.restype = None

self.nodes = (Node * self.maptotal)()
for i in range(self.mapwidth):
for i2 in range(self.mapheight):
self.nodes[i2 * self.mapwidth + i] = Node(Point(i, i2))

self.astar(self.nodes, Point(5,6), Point(6,6))


When I call the self.astar function it segfaults. And what I think
I've done wrong is the self.nodes part, but I can't find any good
documentation on it.

Any help? :p
--
http://mail.python.org/mailman/listinfo/python-list


Re: flock seems very unsafe, python fcntl bug?

2008-06-23 Thread Nick Craig-Wood
Jens Henrik Leonhard Jensen <[EMAIL PROTECTED]> wrote:
>  Your problem is that open(...,'w') is not locked.
> 
>  Use something like:
>  lockf = open('aaa', 'a')
>  fnctl.flock(lockf,fnctl.LOCK_EX)
>  file = open('aaa', 'w')
>  file.write('asdf')
>  file.close()
>  lockf.close()

I've not seen that trick before - it is a good one.  It wouldn't work
for mandatory locking though...

The basic problem is getting the file open for read/write without
destroying the contents before you have the lock.  None of the
arguments to open() do the right thing

Using an append open is a nice solution to that, apart from the fact
that you can only append data onto the file hence the other open.

Here are some other possible solutions and a test harness!  The low
level open is probably the most unixy solution.  If you could specify
os.O_RDWR|os.O_CREAT to the python open() function then it would be
the best, but none of the documented open strings do that

$ strace python -c 'open("aaa", "r+")' 2>&1 | grep 'open("aaa"'
open("aaa", O_RDWR|O_LARGEFILE) = 3
$ strace python -c 'open("aaa", "w+")' 2>&1 | grep 'open("aaa"'
open("aaa", O_RDWR|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 3
$ strace python -c 'open("aaa", "wr+")' 2>&1 | grep 'open("aaa"'
open("aaa", O_RDWR|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 3
$ strace python -c 'open("aaa", "a+")' 2>&1 | grep 'open("aaa"'
open("aaa", O_RDWR|O_CREAT|O_APPEND|O_LARGEFILE, 0666) = 3



"""
Testing writing stuff to a file with locking
"""

import os
import sys
import fcntl

def method_0(data):
"""
Use an normal open

This doesn't work because it truncates the data before it has the
lock
"""
fd = open('aaa', 'w')
fcntl.flock(fd,fcntl.LOCK_EX)
fd.write(data)
fd.close()

def method_1(data):
"""
Use an additional append open to lock
"""
lock_fd = open('aaa', 'a')
fcntl.flock(lock_fd,fcntl.LOCK_EX)
fd = open('aaa', 'w')
fd.write(data)
fd.close()
lock_fd.close()

def method_2(data):
"""
Use a low level open
"""
fd = os.fdopen(os.open('aaa', os.O_CREAT|os.O_RDWR), "r+")
fcntl.flock(fd, fcntl.LOCK_EX)
fd.truncate()
fd.write(data)
fd.close()

def method_3(data):
"""
Using high level functions only

Possibly racy on open when file doesn't exist
"""
if not os.path.exists('aaa'):
fd = open('aaa', 'w+')
else:
fd = open('aaa', 'r+')
fcntl.flock(fd,fcntl.LOCK_EX)
fd.truncate()
fd.write(data)
fd.close()

def check():
fd = open('aaa', 'r')
fcntl.flock(fd,fcntl.LOCK_EX)
data = fd.read()
fd.close()
if data not in ("sausage", "potato"):
raise AssertionError("Wrong data %r" % data)

if os.path.exists("aaa"):
os.unlink("aaa")

if len(sys.argv) < 2:
print "Syntax: %s " % sys.argv[0]
raise SystemExit(1)
method = globals()["method_"+sys.argv[1]]
if os.fork():
while 1:
method("sausage")
check()
else:
while 1:
method("potato")
check()



-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: listcomprehension, add elements?

2008-06-23 Thread Maric Michaud
Le Monday 23 June 2008 11:39:44 Boris Borcic, vous avez écrit :
> John Machin wrote:
> > Instead of sum(a + b for a, b in zip(foo, bar))
> > why not use sum(foo) + sum(bar)
> > ?
>
> or even sum(foo+bar) as may apply.

Because some are better than others :


sum(foo+bar) is the worst, it create a superfluous list of len(foo) + len(bar) 
elements.

sum(a + b for a, b in zip(foo, bar)), creates a list of max(len(foo), 
len(bar)) elements, in most cases it is the same as the former.

This could have been corrected using itertools.izip.

So the winner is sum(foo) + sum(bar), which does not create anything not 
needed.

But if the question is "how to build the list and sum up all elements in a 
efficient way for sequences of arbitrary length ", it's important to make it 
in the same iteration, so the most effective/clear, and so "pythonic", way to 
do this is (untested) :

res, sum = [], 0
for s in (a + b for a, b 
in zip(itertools.izip(xrange(1, 51),
 xrange(50, 0, -1:
sum += s
res.append(sum)


Which is "pythonic" in first place is to provide sequences of datas as 
iterators when they can grow in size.

-- 
_

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


Re: listcomprehension, add elements?

2008-06-23 Thread John Machin
On Jun 23, 9:16 pm, Maric Michaud <[EMAIL PROTECTED]> wrote:
> Le Monday 23 June 2008 11:39:44 Boris Borcic, vous avez écrit :
>
> > John Machin wrote:
> > > Instead of sum(a + b for a, b in zip(foo, bar))
> > > why not use sum(foo) + sum(bar)
> > > ?
>
> > or even sum(foo+bar) as may apply.
>
> Because some are better than others :
>
> sum(foo+bar) is the worst, it create a superfluous list of len(foo) + len(bar)
> elements.
>
> sum(a + b for a, b in zip(foo, bar)), creates a list of max(len(foo),
> len(bar)) elements, in most cases it is the same as the former.
>
> This could have been corrected using itertools.izip.
>
> So the winner is sum(foo) + sum(bar), which does not create anything not
> needed.
>
> But if the question is "how to build the list and sum up all elements in a
> efficient way for sequences of arbitrary length ", it's important to make it
> in the same iteration, so the most effective/clear, and so "pythonic", way to
> do this is (untested) :
>
> res, sum = [], 0

Please use tot or total, not sum!


> for s in (a + b for a, b
> in zip(itertools.izip(xrange(1, 51),

Perhaps you should not have left zip() in there ...

>  xrange(50, 0, -1:
> sum += s
> res.append(sum)

Do you mean res.append(s) ?

I would have thought that it would have been better to create the list
and then sum it:
res = [a + b for a, b in itertools.izip(foo_iter, bar_iter)]
total = sum(res)

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


xml to mysql (vice versa ) too

2008-06-23 Thread swapna mudavath
Hi,

I need to write a python script to store data which is in XML to MYSQL and
even vice versa
what should be the approach?
i am able to establish a connection,create tables and insert data .
but how to read an xml file and store in MYSQL
my XML structure is like






   .
   
   ...

can somebody please help me..i am really confused!!

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

Re: Learning Python in a group

2008-06-23 Thread Taygun Kekec
hi guys.

I would be glad to join your group because i want to learn deeper
python but i am frustrated of isolation too. It would provide
stimulation and encourage to study and will boost our desire to learn.
So count me in!
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to export functions by name for ctype

2008-06-23 Thread rych
On 23 Jun, 10:32, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> rych <[EMAIL PROTECTED]> wrote:
> >  I'm on Windows with VS2005 testing ctypes on a very simple dll
> >  I create a test.dll project which exports a function fntest(). I don't
> >  touch anything in the autogenerated source and build it. I can load
> >  the dll but can't access the function by its name fntest. Only by
> >  ordinal number or calling getattr with "?fntest@@YAHXZ". How do I
> >  export functions by name? It's probably rather a VS2005 question, but
> >  I'm a bit disappointed ctypes doesn't work with a default export
> >  convention.
>
> I guess you've compiled your DLL with C++ and the above is a C++
> mangled name.
>
> Either compile it with C, or export the names in an extern "C" { }
> block.
>
> --
> Nick Craig-Wood <[EMAIL PROTECTED]> --http://www.craig-wood.com/nick

That fixed it, thank you.
--
http://mail.python.org/mailman/listinfo/python-list


Re: listcomprehension, add elements?

2008-06-23 Thread Maric Michaud
Le Monday 23 June 2008 13:51:34 John Machin, vous avez écrit :
> On Jun 23, 9:16 pm, Maric Michaud <[EMAIL PROTECTED]> wrote:
> > Le Monday 23 June 2008 11:39:44 Boris Borcic, vous avez écrit :
> > > John Machin wrote:
> > > > Instead of sum(a + b for a, b in zip(foo, bar))
> > > > why not use sum(foo) + sum(bar)
> > > > ?
> > >
> > > or even sum(foo+bar) as may apply.
> >
> > Because some are better than others :
> >
> > sum(foo+bar) is the worst, it create a superfluous list of len(foo) +
> > len(bar) elements.
> >
> > sum(a + b for a, b in zip(foo, bar)), creates a list of max(len(foo),
> > len(bar)) elements, in most cases it is the same as the former.
> >
> > This could have been corrected using itertools.izip.
> >
> > So the winner is sum(foo) + sum(bar), which does not create anything not
> > needed.
> >
> > But if the question is "how to build the list and sum up all elements in
> > a efficient way for sequences of arbitrary length ", it's important to
> > make it in the same iteration, so the most effective/clear, and so
> > "pythonic", way to do this is (untested) :
> >
> > res, sum = [], 0
>
> Please use tot or total, not sum!
>
> > for s in (a + b for a, b
> > in zip(itertools.izip(xrange(1, 51),
>
> Perhaps you should not have left zip() in there ...
>
> >  xrange(50, 0,
> > -1: sum += s
> > res.append(sum)
>
> Do you mean res.append(s) ?
>

Yes, my mistakes, all remarks are indeed true. Sorry for this out of thoughts 
sketch.

> I would have thought that it would have been better to create the list
> and then sum it:
> res = [a + b for a, b in itertools.izip(foo_iter, bar_iter)]
> total = sum(res)
>

This is good enough if you accept the overhead of iterating twice over the 
whole list.

But this may be a bit more complicated, for efficiency, there is a better way 
of allocating memory than successively appending new item.

I guess this should be a far better solution, but you'll need to know the 
required number of iteration (the size of your iterators, the xrange in this 
sample) :

res, total = [None] * n, 0
for i, s in enumerate(a + b for a, b 
   in izip(xrange(1, n+1),
 xrange(n, 0, -1)):
total += s
res[i] =s

-- 
_

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


Re: py2exe, PyQT, QtWebKit and jpeg problem

2008-06-23 Thread Carbonimax
On Jun 21, 12:21 am, David Boddie <[EMAIL PROTECTED]> wrote:
> On Friday 20 June 2008 17:24, Phil Thompson wrote:
>
> > On Fri, 20 Jun 2008 08:04:57 -0700 (PDT),Carbonimax
> > <[EMAIL PROTECTED]> wrote:
> >> I have a problem with py2exe and QtWebKit :
> >> I make a program with a QtWebKit view.
> >> If I launch the .py directly, all images (jpg, png) are displayed but
> >> if I compile it with py2exe I have only png images. No jpg !
> >> No error message, nothing.
>
> >> Have you a solution ? Thank you.
>
> > At a guess, the JPEG support is implemented as a Qt plugin which you are
> > not including.
>
> Yes, that would appear to the be most obvious cause. See here for another
> report about this:
>
> http://lists.trolltech.com/qt4-preview-feedback/2008-03/msg00064.html
>
> David

How can I do that ?
If I copy the dll in the dist directory, and I use QLibrary() and
load(),
it does work in the .py but it doesn't in .exe made with py2exe

my code :
dll = QLibrary(path_to_dll)
res = dll.load()

res == true in the .py
res == false in the .exe

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


Re: py2exe, PyQT, QtWebKit and jpeg problem

2008-06-23 Thread Carbonimax
On Jun 21, 12:21 am, David Boddie <[EMAIL PROTECTED]> wrote:
> On Friday 20 June 2008 17:24, Phil Thompson wrote:
>
> > On Fri, 20 Jun 2008 08:04:57 -0700 (PDT), Carbonimax
> > <[EMAIL PROTECTED]> wrote:
> >> I have a problem with py2exe and QtWebKit :
> >> I make a program with a QtWebKit view.
> >> If I launch the .py directly, all images (jpg, png) are displayed but
> >> if I compile it with py2exe I have only png images. No jpg !
> >> No error message, nothing.
>
> >> Have you a solution ? Thank you.
>
> > At a guess, the JPEG support is implemented as a Qt plugin which you are
> > not including.
>
> Yes, that would appear to the be most obvious cause. See here for another
> report about this:
>
> http://lists.trolltech.com/qt4-preview-feedback/2008-03/msg00064.html
>
> David

How can I do that ?
If I copy the dll in the dist directory, and I use QPluginLoader() and
load(),
it does work in the .py but it doesn't in .exe made with py2exe

my code :
dll = QPluginLoader(path_to_dll)
res = dll.load()

res == true in the .py
res == false in the .exe

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


Re: -1/2

2008-06-23 Thread Lie
On Jun 23, 1:32 am, "Serve Lau" <[EMAIL PROTECTED]> wrote:
> What is the expected result of -1/2 in python?


Operator precedence:
Both python 2 and 3 follows the same rule for operator precedence,
see: http://www.ibiblio.org/g2swap/byteofpython/read/operator-precedence.html
. In -1/2, unary negative takes precedence, then division, i.e. it's
interpreted as ((-1) / 2).

Py3k and Python 2 differences:
Before Python 3, integer division is always rounds to minus infinity.
In Python 3, integer division yields floats. To use integer division
in Python 3, you use // operator.

Simple answer:
Python 2: (-1)/2 = round(-0.5)  = -1
Py3k: (-1)/2 = float(-1) / float(2) = -0.5
--
http://mail.python.org/mailman/listinfo/python-list


Distutils and unit test files

2008-06-23 Thread Joe Riopel
Hi,

I am using Distutils to build and distribute some packages. I do write
unit tests, but I am confused as to where to put them and how to run
them prior to the package being installed (The modules being tested
would not be in my sys.path). I would rather not put the test cases in
the same files as the modules being tested, I want keep them in a sub
directory of the module, or in a separate "test" directory.

What are some of the strategies for dealing with this?

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


Re: Sending arrays of a structure as an argument via ctypes

2008-06-23 Thread bearophileHUGS
Knut Saua Mathiesen:
> Any help? :p

My faster suggestion is to try ShedSkin, it may help you produce a
fast enough extension.
If ShedSkin doesn't compile it, its author (Mark) may be quite willing
to help.

bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Distutils and unit test files

2008-06-23 Thread Cédric Lucantis
Le Monday 23 June 2008 15:38:40 Joe Riopel, vous avez écrit :
> Hi,
>
> I am using Distutils to build and distribute some packages. I do write
> unit tests, but I am confused as to where to put them and how to run
> them prior to the package being installed (The modules being tested
> would not be in my sys.path). I would rather not put the test cases in
> the same files as the modules being tested, I want keep them in a sub
> directory of the module, or in a separate "test" directory.
>
> What are some of the strategies for dealing with this?
>

Yes a checksuite should be kept separate from the 'real' code. You can run it 
locally by setting the PYTHONPATH environment variable :

PYTHONPATH=/path/to/your/modules python checksuite.py

-- 
Cédric Lucantis
--
http://mail.python.org/mailman/listinfo/python-list


Re: Distutils and unit test files

2008-06-23 Thread Joe Riopel
On Mon, Jun 23, 2008 at 9:59 AM, Cédric Lucantis <[EMAIL PROTECTED]> wrote:
> Yes a checksuite should be kept separate from the 'real' code. You can run it
> locally by setting the PYTHONPATH environment variable :
>
> PYTHONPATH=/path/to/your/modules python checksuite.py

So I could also just append the path to sys.path in checksuite.py file
and use checksuite to run all my unit tests?

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


[ANN] Virtual Worlds Open Grid Protocols testing library in Python (pyogp)

2008-06-23 Thread Lawson English
A new open source project has been started by Linden Lab, makers of the 
Second Life™ virtual worlds, and the Second Life Architecture Working 
Group (AWG) to test LL's proposed virtual worlds Open Grid Protocols 
(OGP) that will allow any virtual world to support multi-world login, 
between-world teleport and other transportation mechanisms, as well as 
asset/property and currency sharing between worlds.



https://wiki.secondlife.com/w/index.php?title=AWG_Test_Harness

The code is released to all comers in Python under an Apache v2 
agreement, although contributions require the signing of Linden Lab's 
developer contribution agreement (giving LL equal copyrights to the 
original contributer--a boilerplate LL corporate requirement that likely 
is redundant given the nature of Apache v2).


svn: http://svn.secondlife.com/trac/linden/browser/projects/2008/pyogp.

Second Life contribution agreement: 
http://secondlifegrid.net.s3.amazonaws.com/docs/SLVcontribution_agmt.pdf


irc: irc://irc.freenode.net/#pyogp

AWG homepage: https://wiki.secondlife.com/wiki/AWG

AWG discussion group homepage: 
https://wiki.secondlife.com/wiki/Category:AW_Groupies


AWG-related pages, irc channels and forums: 
https://wiki.secondlife.com/wiki/Category:AW_Groupies#External_Resources



The near-term AWG goal is to create a set of open standard protocols that:

1) Enable third parties to run servers that connect to the Second Life 
Grid platform
2) Scale the Second Life Grid architecture to support the 
industry-projected situation in the next 10 years, where virtual worlds 
will comprise at least 60 million regions, 2 billion users and in-world 
concurrency of 50-100 million residents.


https://wiki.secondlife.com/wiki/SLGOGP_Draft_1
https://wiki.secondlife.com/wiki/SLGOGP_Teleport_Strawman

The long-term goal is to design a set of protocols and standards that 
will enable almost any virtual world of any kind to "plug into" this 
system to varying degrees, from support for a "universal avatar" to full 
support for all Second Life features and/or the ability to inform 
universal 3D viewers what features are supported (or not) in any given 
virtual world.



More info on pyogp and the AWG can be obtained on the website or via irc.


Lawson English
AKA Saijana Kuhn, AWGroupies admin



















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


Re: Distutils and unit test files

2008-06-23 Thread Cédric Lucantis

> On Mon, Jun 23, 2008 at 9:59 AM, Cédric Lucantis <[EMAIL PROTECTED]> wrote:
> > Yes a checksuite should be kept separate from the 'real' code. You can
> > run it locally by setting the PYTHONPATH environment variable :
> >
> > PYTHONPATH=/path/to/your/modules python checksuite.py
>
> So I could also just append the path to sys.path in checksuite.py file
> and use checksuite to run all my unit tests?
>

(woops, sorry for the private post :)

Yes this is equivalent, as sys.path is initialized from PYTHONPATH at startup. 
But I'd suggest to insert your path at the beginning of sys.path rather than 
appending it, so you'll be sure to use the local modules even if they are 
already installed (I use 1 instead of 0 because sys.path[0] has a special 
meaning) :

sys.path.insert(1, '/path/...')

But I prefer to use PYTHONPATH, so the user keeps control on it (and can 
eventually check installed modules too). If you don't want to have to set it 
at each run, you can still write a simple wrapper script for your own needs.

-- 
Cédric Lucantis
--
http://mail.python.org/mailman/listinfo/python-list


PyOpenGL New Installation

2008-06-23 Thread Colin J. Williams
I have just installed PyOpenGL and get a 
series of warning messages:


Best match: PyOpenGL 3.0.0b3
Downloading 
http://downloads.sourceforge.net/pyopengl/PyOpenGL-3.0.0b3.zip?modtime=1213363873&big_mirror=0

Processing PyOpenGL-3.0.0b3.zip
Running PyOpenGL-3.0.0b3\setup.py -q 
bdist_egg --dist-dir 
c:\docume~1\cjw\locals~1\temp\easy_install-hjyff7\PyOpenGL-3.0.0b3\egg-dist-tmp-iqd53p
warning: no previously-included files 
matching '*.odt' found anywhere in 
distribution
warning: no previously-included files 
matching '*.odp' found anywhere in 
distribution
warning: no previously-included files 
matching '.cvsignore' found anywhere in 
distribution
warning: no previously-included files 
matching '*.diff' found anywhere in 
distribution
warning: no previously-included files 
found matching 'src\*.h'
warning: no previously-included files 
found matching 'src\*.xml'
warning: no previously-included files 
found matching 'src\*.zip'
Adding pyopengl 3.0.0b3 to 
easy-install.pth file


Installed 
c:\python25\lib\site-packages\pyopengl-3.0.0b3-py2.5.egg

Processing dependencies for PyOpenGL
Finished processing dependencies for 
PyOpenGL


Could someone please advise the 
significance of these messages?


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


String question

2008-06-23 Thread Andreu

I want to split a sentence and assign each word to a variable.
In Ruby I can do it as:

v1,v2,v3,v4,v5 = str1.split

Which will be the Python equivalent ? Thanks.

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


Re: String question

2008-06-23 Thread Tim Golden

Andreu wrote:

I want to split a sentence and assign each word to a variable.
In Ruby I can do it as:

v1,v2,v3,v4,v5 = str1.split

Which will be the Python equivalent ? Thanks.


That would be:

str1 = "The quick brown fox jumps"
v1, v2, v3, v4, v5 = str1.split ()

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


Re: String question

2008-06-23 Thread Andreu

Wow...about ten seconds to get a kind response 
Thanks Tim.

Andrew.

Tim Golden wrote:

Andreu wrote:

I want to split a sentence and assign each word to a variable.
In Ruby I can do it as:

v1,v2,v3,v4,v5 = str1.split

Which will be the Python equivalent ? Thanks.


That would be:

str1 = "The quick brown fox jumps"
v1, v2, v3, v4, v5 = str1.split ()

TJG

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


learning unit testing in python

2008-06-23 Thread Alex
Hi all.

I'd like learn some basic unit testing with python.
I red some articles about different testing framework like unittest or
nose, but I'm a bit confused: what is the best choice? I'm not a
professional developer (I'm a SEO) but I belive that unit testing is a
good and pragmatic way to produce working software, so I'd like to
find something really simple ad straightforward because I don't have
to manage big programming projects.

Thanks in advance,

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


Re: -1/2

2008-06-23 Thread Duncan Booth
Lie <[EMAIL PROTECTED]> wrote:

> On Jun 23, 1:32 am, "Serve Lau" <[EMAIL PROTECTED]> wrote:
>> What is the expected result of -1/2 in python?
> 
> 
> Operator precedence:
> Both python 2 and 3 follows the same rule for operator precedence,
> see:
> http://www.ibiblio.org/g2swap/byteofpython/read/operator-precedence.htm
> l . In -1/2, unary negative takes precedence, then division, i.e. it's
> interpreted as ((-1) / 2).
> 
> Py3k and Python 2 differences:
> Before Python 3, integer division is always rounds to minus infinity.
> In Python 3, integer division yields floats. To use integer division
> in Python 3, you use // operator.
> 
> Simple answer:
> Python 2: (-1)/2 = round(-0.5)  = -1
> Py3k: (-1)/2 = float(-1) / float(2) = -0.5
> 
Python 2.x gives -1 or -0.5 depending on the division mode in operation and 
for -1 may also generate a deprecation warning:


C:\>python25\python -Qnew -c "print -1/2"
-0.5

C:\>python25\python -Qwarn -c "print -1/2"
-c:1: DeprecationWarning: classic int division
-1


-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: String question

2008-06-23 Thread cokofreedom
On Jun 23, 4:45 pm, Andreu <[EMAIL PROTECTED]> wrote:
> I want to split a sentence and assign each word to a variable.
> In Ruby I can do it as:
>
> v1,v2,v3,v4,v5 = str1.split
>
> Which will be the Python equivalent ? Thanks.
>
> Andrew.

Well a straight copy would be...

>>> example = "Hello, how are you"
>>> v1, v2, v3, v4 = example.split()
>>> print v1, v2, v3, v4
Hello, how are you
>>> print v1
Hello,

However I would make a list of it.

>>> v_list = example.split()
>>> print v_list
['Hello,', 'how', 'are', 'you']
>>> for word in v_list:
print word
Hello,
how
are
you

That seems to me to be the more pythonic way to do it, since it is
dynamic.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regular expression problem

2008-06-23 Thread MRAB
On Jun 22, 10:13 pm, abranches <[EMAIL PROTECTED]> wrote:
> Hello everyone.
>
> I'm having a problem when extracting data from HTML with regular
> expressions.
> This is the source code:
>
> You are ready in the next style="display: inline;">12 span>M 48S
>
> And I need to get the remaining time. Until here, isn't a problem
> getting it, but if the remaining time is less than 60 seconds then the
> source becomes something like this:
>
> You are ready in the next style="display: inline;">36 span>S
>
> I'm using this regular expression, but the minutes are always None...
> You are ready in the next.*?(?:>(\d+)M)?.*?(?:>(\d+) span>S)
>
> If I remove the ? from the first group, then it will work, but if
> there are only seconds it won't work.
> I could resolve this problem in a couple of python lines, but I really
> would like to solve it with regular expressions.
>
Your regex is working like this:

1. Match 'You are ready in the next'.
2. Match an increasing number of characters, starting with none
('.*?').
3. Try to match a pattern ('(?:>...)?') from where the previous step
left off. This doesn't match, but it's optional anyway, so continue to
the next step. (No characters consumed.)
4. Match an increasing number of characters, starting from none
('.*?'). It's this step that consumes the minutes.

It then goes on to match the seconds, and the minutes are always None
as you've found.

I've come up with this regex:

You are ready in the next(?:.*?>(\d+)M)?(?:.*?>(\d+)S)

Hope that helps.
--
http://mail.python.org/mailman/listinfo/python-list


Terminating processes on Windows (handles and IDs)

2008-06-23 Thread geoffbache
Hi all,

I've always wondered why os.kill isn't supported on Windows. I found a
discussion somewhere from 2006 about this so it seems others have
wanted it, but still nothing. So I have a half-baked solution
involving calling "taskkill" on Windows Vista or "tskill" on Windows
XP via the shell. I feel there has to be a better way.

I'm also fairly confused about when I've got an ID and when I've got a
handle. The subprocess module gives me IDs which the above programs
accept, but other ways of spawning processes give me process handles
(while referring to them as process IDs in the docs...) and I don't
know how to kill a process with these. Besides, I've found an
amazingly useful PyGTK method, gobject.child_watch_add, which does
exactly what I want on UNIX but wants process handles on Windows. So I
can't use it in conjunction with subprocess there, and if I use some
other way of spawning processes I can't clean them up later.

Is there any way to convert one of these numbers to the other? Or to
get a process handle out of subprocess?
(There must be one down there somewhere, surely?)

Sorry for rambling a bit, am confused.

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


Passing arguments to subclasses

2008-06-23 Thread John Dann
May I ask a simple newbie question, which I presume is true, but for
which I can't readily find confirmation:

Let's say I have a parent class with an __init__ method explicitly
defined:

class ParentClass(object):
def __init__(self, keyword1, keyword2):
etc

and I subclass this:

class ChildClass(ParentClass):
# No __init__ method explicitly defined

Now I presume that I can instantiate a child object as:

child = ChildClass(arg1, arg2)

and arg1, arg2 will be passed through to the 'constructor' of the
antecedent ParentClass (there being no overrriding __init__ method
defined for ChildClass) and mapping to keyword1, keyword2 etc.

Have I understood this correctly?
--
http://mail.python.org/mailman/listinfo/python-list


Find class attributes creation order

2008-06-23 Thread Marcob
Let's see these simple classes:

class base_foo()
 pass

class foo(base_foo):
 a=1
 b={}
 c="zz"

I would like to find class foo attributes creation order.
Using __metaclass__ is not of help because special method __new__
receive attrs as a dictionary and so the order isn't preserved. Any
other idea?

Thanks for your time.

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


Re: Passing arguments to subclasses

2008-06-23 Thread Bruno Desthuilliers

John Dann a écrit :

May I ask a simple newbie question, which I presume is true, but for
which I can't readily find confirmation:

Let's say I have a parent class with an __init__ method explicitly
defined:

class ParentClass(object):
def __init__(self, keyword1, keyword2):
etc

and I subclass this:

class ChildClass(ParentClass):
# No __init__ method explicitly defined

Now I presume that I can instantiate a child object as:

child = ChildClass(arg1, arg2)

and arg1, arg2 will be passed through to the 'constructor' of the
antecedent ParentClass (there being no overrriding __init__ method
defined for ChildClass) and mapping to keyword1, keyword2 etc.

Have I understood this correctly?


Yes. But you could have checked by yourself:

[EMAIL PROTECTED]:~$ python
Python 2.5.1 (r251:54863, Mar  7 2008, 03:41:45)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Parent(object):
... def __init__(self, kw1, kw2):
... print self, kw1, kw2
... self.kw1, self.kw2 = kw1, kw2
...
>>> class Child(Parent): pass
...
>>> c = Child("arg1", "arg2")
<__main__.Child object at 0xb7ddeccc> arg1 arg2
>>> c.kw1
'arg1'
>>> c.kw2
'arg2'
>>>

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


Re: Passing arguments to subclasses

2008-06-23 Thread Gary Herron

John Dann wrote:

May I ask a simple newbie question, which I presume is true, but for
which I can't readily find confirmation:

Let's say I have a parent class with an __init__ method explicitly
defined:

class ParentClass(object):
def __init__(self, keyword1, keyword2):
etc

and I subclass this:

class ChildClass(ParentClass):
# No __init__ method explicitly defined

Now I presume that I can instantiate a child object as:

child = ChildClass(arg1, arg2)

and arg1, arg2 will be passed through to the 'constructor' of the
antecedent ParentClass (there being no overrriding __init__ method
defined for ChildClass) and mapping to keyword1, keyword2 etc.

Have I understood this correctly?



Yes, but...

The nice things about Python is that you can use the interactive 
interpreter to test such things in an instant.  (And not have to wait 
for a response from python-list.  Like this:



>>> class ParentClass(object):
...   def __init__(self, keyword1, keyword2):
... print 'ParentClass.__init__ called with', keyword1, keyword2
...
>>> class ChildClass(ParentClass):
...  pass
...
>>> child = ChildClass(123,456)
ParentClass.__init__ called with 123 456
>>>


Gary Herron


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


Going from Tkinter to pyQT

2008-06-23 Thread Alex Bryan
I had a guy on this mailing list tell me that pyQT is much better than  
Tkinter, and after looking into it a bit I think he is right. However,  
I can't find much on it. I want to know if there are any good books or  
online tutorials that would be helpful. I doubt there is one, but if  
there is one on going from Tkinter to pyQT, that would be amazing.  
Well if any of you guys have any tips or suggestions on any of this I  
would appreciate it. 
--

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


Re: Find class attributes creation order

2008-06-23 Thread Cédric Lucantis
Le Monday 23 June 2008 17:53:07 Marcob, vous avez écrit :
> Let's see these simple classes:
>
> class base_foo()
>  pass
>
> class foo(base_foo):
>  a=1
>  b={}
>  c="zz"
>
> I would like to find class foo attributes creation order.
> Using __metaclass__ is not of help because special method __new__
> receive attrs as a dictionary and so the order isn't preserved. Any
> other idea?
>

I don't really understand what you want, but __new__ may accept any kind of 
attributes, this is your choice. You can use named params or a vararg list 
(which will preserve params order).

But in your example you're only using class attributes, so __new__ is not 
involved and they are just created once for all in the order you write them: 
a, b, c.

-- 
Cédric Lucantis
--
http://mail.python.org/mailman/listinfo/python-list


Using Python and MS-SQL Server

2008-06-23 Thread hwcowan
Hello,

I have programmed before, but I am new to using Python.  I am
currently using the ArcGIS software which uses Python as its scripting
language for automating tasks.

The current script that I am working on requires pulling in some
information from a Microsoft SQL Server.

I was wondering if anyone could suggest the best way of doing this?  I
have looked at the different modules that are specific to SQL server,
but none of them seem to be active or up to date.

If not, could anyone make any suggestions?  Or would it be better to
go the ODBC route?  I am not talking about large amounts of data, so I
am not concerned about performance so ODBC would be fine to use as
well.

Also, being new to Python, I recently read about dictionaries and was
wondering if there was a quick way to dump a table into a dictionary?

For example, I have a customer list with a customer ID.  It would be
great to have the ID as the "key" and the name as the "data" (or even
better, have a list as the data element containing all the information
about the customer).

I am sure that this could be done manually, by looping through each
record and adding it to the dictionary -- but I was just wondering if
something like this has already been done (I don't need to reinvent
the wheel here).

Thanks so much,

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


IDE on the level of Eclipse or DEVc++?

2008-06-23 Thread cirfu
is there an IDE for python of the same quality as Eclipse or DEVC++?

I am currently using the editor that coems iwth python and it is all
fine but for bigger projects it would be nice to have some way to
easier browse the projectfiles for example.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Find class attributes creation order

2008-06-23 Thread Marcob
On 23 Giu, 18:08, Cédric Lucantis <[EMAIL PROTECTED]> wrote:
> Le Monday 23 June 2008 17:53:07 Marcob, vous avez écrit :
>
> > Let's see these simple classes:
>
> >     class base_foo()
> >          pass
>
> >     class foo(base_foo):
> >          a=1
> >          b={}
> >          c="zz"
>
> > I would like to find class foo attributes creation order.
> > Using __metaclass__ is not of help because special method __new__
> > receive attrs as a dictionary and so the order isn't preserved. Any
> > other idea?
>
> I don't really understand what you want, but __new__ may accept any kind of
> attributes, this is your choice. You can use named params or a vararg list
> (which will preserve params order).

Ok, I'll try to make myself clearer.

> But in your example you're only using class attributes, so __new__ is not
> involved and they are just created once for all in the order you write them:
> a, b, c.

Yes, this is true but if another piece of code define class foo (and
consequently a, b, c) and I would like to find how many class
attributes are defined and their order, how can I do this?

It's easy to find how many attributes there are: using __dict__ or
dir() or whatever.

But to find their order isn't so easy.

Besides that I can do whatever I want with class base_foo but I can't
touch class foo.

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


Re: Find class attributes creation order

2008-06-23 Thread Michele Simionato
On Jun 23, 5:53 pm, Marcob <[EMAIL PROTECTED]> wrote:
> Let's see these simple classes:
>
>     class base_foo()
>          pass
>
>     class foo(base_foo):
>          a=1
>          b={}
>          c="zz"
>
> I would like to find class foo attributes creation order.
> Using __metaclass__ is not of help because special method __new__
> receive attrs as a dictionary and so the order isn't preserved. Any
> other idea?

You need to wait for Python 3.0 metaclasses:

http://stacktrace.it/articoli/2008/01/metaclassi-python-3000/ which
you should know already (ciao Marco! ;-)

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


Re: IDE on the level of Eclipse or DEVc++?

2008-06-23 Thread Andrii V. Mishkovskyi
2008/6/23 cirfu <[EMAIL PROTECTED]>:
> is there an IDE for python of the same quality as Eclipse or DEVC++?
>
> I am currently using the editor that coems iwth python and it is all
> fine but for bigger projects it would be nice to have some way to
> easier browse the projectfiles for example.

Actually, there is a great plugin for Eclipse, called PyDev. You
should check it out. :)

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



-- 
Wbr, Andrii Mishkovskyi.

He's got a heart of a little child, and he keeps it in a jar on his desk.
--
http://mail.python.org/mailman/listinfo/python-list


Re: IDE on the level of Eclipse or DEVc++?

2008-06-23 Thread Tim Arnold
"cirfu" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> is there an IDE for python of the same quality as Eclipse or DEVC++?
>
> I am currently using the editor that coems iwth python and it is all
> fine but for bigger projects it would be nice to have some way to
> easier browse the projectfiles for example.

why not eclipse itself, using the pydev plugin?
--Tim


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


Question: How do I format printing in python

2008-06-23 Thread joemacbusiness
Hi All,

How do I format printed data in python?
I could not find this in the Python Reference Manual:
http://docs.python.org/ref/print.html
Nor could I find it in Matloff's great tutorial:
http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf


For example, how do I turn this:

512 Jun 5 2004 X11r6
22 Jan 17 2005 a2p
22 Jan 17 2005 acctcom
5374 Sep 15 2002 acledit
5664 May 13 2004 aclget
12020 May 13 2004 aclput
115734 Jun 2 2004 adb
46518 Jun 4 2004 admin
66750 Sep 16 2002 ali
1453 Sep 15 2002 alias
28150 Jun 4 2004 alog
15 May 12 2005 alstat

into this:

512Jun   5   2004X11r6
22 Jan   17  2005a2p
22 Jan   17  2005acctcom
5374   Sep   15  2002acledit
5664   May   13  2004aclget
12020  May   13  2004aclput
115734 Jun   2   2004adb
46518  Jun   4   2004admin
66750  Sep   16  2002ali
1453   Sep   15  2002alias
28150  Jun   4   2004alog
15 May   12  2005alstat

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


Re: Passing arguments to subclasses

2008-06-23 Thread John Dann
Thanks for the responses - they're much appreciated. And I understand
the slight impatience with questions that could possibly be answered
without recourse to a forum - I'm usually in the opposite position of
fielding many newbie questions in a forum in a completely different
field!

But don't be too harsh on this category of questions for a couple of
reasons. First, newbies don't necessarily yet have the same easy
familiarity with the Python interpreter that's implied. - personally
I'd be a little concerned as to whether any significant block of
test/example code that I'd entered into the interpreter was actually
addressing the exact question that I had in mind. 

And second, the answer might have been of the 'yes, but' kind. In
other words, it might perhaps have been true in a certain sort of
simple example, but one that failed to provide the complete picture.
So sometimes it's reassuring to be able to get an authoritative
answer.

Thanks again for taking the time to answer.
--
http://mail.python.org/mailman/listinfo/python-list


Using Python to run SSH commands on a remote server

2008-06-23 Thread John Salerno
Generally speaking, what tools would I use to do this? Is there a built-in 
module for it? I looked at the telnetlib module, but the documentation 
wasn't really complete enough for me to get a good idea of it. Is Telnet and 
SSH even the same thing?

Basically, I want to write a script that will automate the process of making 
all .py files on my web server executable (chmod 755, or something similar).

Thanks. 


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


Re: Going from Tkinter to pyQT

2008-06-23 Thread kib2

Alex Bryan a écrit :
I had a guy on this mailing list tell me that pyQT is much better than 
Tkinter, and after looking into it a bit I think he is right. However, I 
can't find much on it. I want to know if there are any good books or 
online tutorials that would be helpful. I doubt there is one, but if 
there is one on going from Tkinter to pyQT, that would be amazing. Well 
if any of you guys have any tips or suggestions on any of this I would 
appreciate it.


Hi Alex,

Check Mark Summerfield's book on PyQt4 :
http://www.qtrac.eu/pyqtbook.html

Other links :
http://www.rkblog.rk.edu.pl/w/p/python/

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


Re: Question: How do I format printing in python

2008-06-23 Thread Saul Spatz

format the strings:
http://www.python.org/doc/2.1.3/lib/typesseq-strings.html



[EMAIL PROTECTED] wrote:

Hi All,

How do I format printed data in python?
I could not find this in the Python Reference Manual:
http://docs.python.org/ref/print.html
Nor could I find it in Matloff's great tutorial:
http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf


For example, how do I turn this:

512 Jun 5 2004 X11r6
22 Jan 17 2005 a2p
22 Jan 17 2005 acctcom
5374 Sep 15 2002 acledit
5664 May 13 2004 aclget
12020 May 13 2004 aclput
115734 Jun 2 2004 adb
46518 Jun 4 2004 admin
66750 Sep 16 2002 ali
1453 Sep 15 2002 alias
28150 Jun 4 2004 alog
15 May 12 2005 alstat

into this:

512Jun   5   2004X11r6
22 Jan   17  2005a2p
22 Jan   17  2005acctcom
5374   Sep   15  2002acledit
5664   May   13  2004aclget
12020  May   13  2004aclput
115734 Jun   2   2004adb
46518  Jun   4   2004admin
66750  Sep   16  2002ali
1453   Sep   15  2002alias
28150  Jun   4   2004alog
15 May   12  2005alstat

Thank you

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


Re: Using Python to run SSH commands on a remote server

2008-06-23 Thread Jean-Paul Calderone

On Mon, 23 Jun 2008 13:30:55 -0400, John Salerno <[EMAIL PROTECTED]> wrote:

Generally speaking, what tools would I use to do this? Is there a built-in
module for it? I looked at the telnetlib module, but the documentation
wasn't really complete enough for me to get a good idea of it. Is Telnet and
SSH even the same thing?


Telnet and SSH are different things.  There's nothing in the standard library
for making an SSH connection (aside from the process control libraries, which
let you run an external SSH client in a child process).



Basically, I want to write a script that will automate the process of making
all .py files on my web server executable (chmod 755, or something similar).


There are several third-party SSH libraries, eg Twisted Conch and Paramiko.

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


Re: Question: How do I format printing in python

2008-06-23 Thread Mensanator
On Jun 23, 12:12 pm, [EMAIL PROTECTED] wrote:
> Hi All,
>
> How do I format printed data in python?
> I could not find this in the Python Reference 
> Manual:http://docs.python.org/ref/print.html
> Nor could I find it in Matloff's great 
> tutorial:http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf
>
> For example, how do I turn this:
>
> 512 Jun 5 2004 X11r6
> 22 Jan 17 2005 a2p
> 22 Jan 17 2005 acctcom
> 5374 Sep 15 2002 acledit
> 5664 May 13 2004 aclget
> 12020 May 13 2004 aclput
> 115734 Jun 2 2004 adb
> 46518 Jun 4 2004 admin
> 66750 Sep 16 2002 ali
> 1453 Sep 15 2002 alias
> 28150 Jun 4 2004 alog
> 15 May 12 2005 alstat
>
> into this:
>
> 512        Jun   5   2004    X11r6
> 22         Jan   17  2005    a2p
> 22         Jan   17  2005    acctcom
> 5374       Sep   15  2002    acledit
> 5664       May   13  2004    aclget
> 12020      May   13  2004    aclput
> 115734     Jun   2   2004    adb
> 46518      Jun   4   2004    admin
> 66750      Sep   16  2002    ali
> 1453       Sep   15  2002    alias
> 28150      Jun   4   2004    alog
> 15         May   12  2005    alstat
>
> Thank you


You could do this:

data = ['512 Jun 5 2004 X11r6 ', \
'22 Jan 17 2005 a2p', \
'22 Jan 17 2005 acctcom ', \
'5374 Sep 15 2002 acledit ', \
'5664 May 13 2004 aclget ', \
'12020 May 13 2004 aclput ', \
'115734 Jun 2 2004 adb ', \
'46518 Jun 4 2004 admin ', \
'66750 Sep 16 2002 ali ', \
'1453 Sep 15 2002 alias ', \
'28150 Jun 4 2004 alog ', \
'15 May 12 2005 alstat ']

for i in data:
  d = i.split()
  print d[0].ljust(9),
  print d[1].ljust(6),
  print d[2].ljust(4),
  print d[3].ljust(7),
  print d[4].ljust(9)


which gives you

512   Jun52004X11r6
22Jan17   2005a2p
22Jan17   2005acctcom
5374  Sep15   2002acledit
5664  May13   2004aclget
12020 May13   2004aclput
115734Jun22004adb
46518 Jun42004admin
66750 Sep16   2002ali
1453  Sep15   2002alias
28150 Jun42004alog
15May12   2005alstat


or perhaps this:

for i in data:
  d = i.split()
  print d[0].rjust(9),
  print d[1].ljust(6),
  print d[2].zfill(2).ljust(4),
  print d[3].ljust(7),
  print d[4].ljust(9)

which gives this (if you want the digits in the numbers to
line up):

  512 Jun05   2004X11r6
   22 Jan17   2005a2p
   22 Jan17   2005acctcom
 5374 Sep15   2002acledit
 5664 May13   2004aclget
12020 May13   2004aclput
   115734 Jun02   2004adb
46518 Jun04   2004admin
66750 Sep16   2002ali
 1453 Sep15   2002alias
28150 Jun04   2004alog
   15 May12   2005alstat
--
http://mail.python.org/mailman/listinfo/python-list


installed 3.0, rebind winprompt to 2.5?

2008-06-23 Thread cirfu
i installed python 3.0. now when im laucnhing from the dos prompt in
win vista it searches in python3.0

i want to rebind it to 2.5, what do i need to change?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question: How do I format printing in python

2008-06-23 Thread Mensanator
On Jun 23, 12:47 pm, Mensanator <[EMAIL PROTECTED]> wrote:
> On Jun 23, 12:12 pm, [EMAIL PROTECTED] wrote:
>
>
>
>
>
> > Hi All,
>
> > How do I format printed data in python?
> > I could not find this in the Python Reference 
> > Manual:http://docs.python.org/ref/print.html
> > Nor could I find it in Matloff's great 
> > tutorial:http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf
>
> > For example, how do I turn this:
>
> > 512 Jun 5 2004 X11r6
> > 22 Jan 17 2005 a2p
> > 22 Jan 17 2005 acctcom
> > 5374 Sep 15 2002 acledit
> > 5664 May 13 2004 aclget
> > 12020 May 13 2004 aclput
> > 115734 Jun 2 2004 adb
> > 46518 Jun 4 2004 admin
> > 66750 Sep 16 2002 ali
> > 1453 Sep 15 2002 alias
> > 28150 Jun 4 2004 alog
> > 15 May 12 2005 alstat
>
> > into this:
>
> > 512        Jun   5   2004    X11r6
> > 22         Jan   17  2005    a2p
> > 22         Jan   17  2005    acctcom
> > 5374       Sep   15  2002    acledit
> > 5664       May   13  2004    aclget
> > 12020      May   13  2004    aclput
> > 115734     Jun   2   2004    adb
> > 46518      Jun   4   2004    admin
> > 66750      Sep   16  2002    ali
> > 1453       Sep   15  2002    alias
> > 28150      Jun   4   2004    alog
> > 15         May   12  2005    alstat
>
> > Thank you
>
> You could do this:
>
> data = ['512 Jun 5 2004 X11r6 ', \
> '22 Jan 17 2005 a2p', \
> '22 Jan 17 2005 acctcom ', \
> '5374 Sep 15 2002 acledit ', \
> '5664 May 13 2004 aclget ', \
> '12020 May 13 2004 aclput ', \
> '115734 Jun 2 2004 adb ', \
> '46518 Jun 4 2004 admin ', \
> '66750 Sep 16 2002 ali ', \
> '1453 Sep 15 2002 alias ', \
> '28150 Jun 4 2004 alog ', \
> '15 May 12 2005 alstat ']
>
> for i in data:
>   d = i.split()
>   print d[0].ljust(9),
>   print d[1].ljust(6),
>   print d[2].ljust(4),
>   print d[3].ljust(7),
>   print d[4].ljust(9)
>
> which gives you
>
> 512       Jun    5    2004    X11r6
> 22        Jan    17   2005    a2p
> 22        Jan    17   2005    acctcom
> 5374      Sep    15   2002    acledit
> 5664      May    13   2004    aclget
> 12020     May    13   2004    aclput
> 115734    Jun    2    2004    adb
> 46518     Jun    4    2004    admin
> 66750     Sep    16   2002    ali
> 1453      Sep    15   2002    alias
> 28150     Jun    4    2004    alog
> 15        May    12   2005    alstat
>
> or perhaps this:
>
> for i in data:
>   d = i.split()
>   print d[0].rjust(9),
>   print d[1].ljust(6),
>   print d[2].zfill(2).ljust(4),
>   print d[3].ljust(7),
>   print d[4].ljust(9)
>
> which gives this (if you want the digits in the numbers to
> line up):
>
>       512 Jun    05   2004    X11r6
>        22 Jan    17   2005    a2p
>        22 Jan    17   2005    acctcom
>      5374 Sep    15   2002    acledit
>      5664 May    13   2004    aclget
>     12020 May    13   2004    aclput
>    115734 Jun    02   2004    adb
>     46518 Jun    04   2004    admin
>     66750 Sep    16   2002    ali
>      1453 Sep    15   2002    alias
>     28150 Jun    04   2004    alog
>        15 May    12   2005    alstat

In retrospect, that looks kind of clunky. If it was for my
use, I'd do

for i in data:
  d = i.split()
  print d[0].rjust(9),
  print d[1].rjust(6),
  print d[2].zfill(2),
  print d[3].ljust(7),
  print d[4].ljust(9)

which looks like:

  512Jun 05 2004X11r6
   22Jan 17 2005a2p
   22Jan 17 2005acctcom
 5374Sep 15 2002acledit
 5664May 13 2004aclget
12020May 13 2004aclput
   115734Jun 02 2004adb
46518Jun 04 2004admin
66750Sep 16 2002ali
 1453Sep 15 2002alias
28150Jun 04 2004alog
   15May 12 2005alstat

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


Re: IDE on the level of Eclipse or DEVc++?

2008-06-23 Thread cirfu
i downloaded the extension for eclipse, nice.

any opinions of netbeans vs eclipse for python?
--
http://mail.python.org/mailman/listinfo/python-list


socket error: connection refused?

2008-06-23 Thread cirfu
The first time i start the shell it always works. But often after
closing it and restarting it I get:

Two windows pops up and the shell, after clicking the windows the
shell just closes by itself.


socket error: connection refused

IDLE's subprocess didnt make connection.


im using python 2.5.1 and windows vista.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using Python to run SSH commands on a remote server

2008-06-23 Thread Mark Wooding
John Salerno <[EMAIL PROTECTED]> wrote:

> Generally speaking, what tools would I use to do this? Is there a built-in 
> module for it? 

There's paramiko (q.g.).  I can't personally vouch for it, but it seems
popular...  It seems to depend on a separate crypto library.

> Is Telnet and SSH even the same thing?

No.  They're very different.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using Python to run SSH commands on a remote server

2008-06-23 Thread Jeffrey Froman
John Salerno wrote:

> Generally speaking, what tools would I use to do this? Is there a built-in
> module for it?

I've had a very nice experience using the 3rd-party package "paramiko" for
ssh communication. There's nothing in the standard library that I know of.

> I looked at the telnetlib module, but the documentation 
> wasn't really complete enough for me to get a good idea of it. Is Telnet
> and SSH even the same thing?

Telnet is not the same protocol. SSH is an encrypted transport, telnet is
not. 

> Basically, I want to write a script that will automate the process of
> making all .py files on my web server executable (chmod 755, or something
> similar).

Be careful, this procedure sounds potential risky, security-wise ;-)


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


Re: Using Python to run SSH commands on a remote server

2008-06-23 Thread John Salerno
"Jeffrey Froman" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Be careful, this procedure sounds potential risky, security-wise ;-)

I guess a blanket process might be a tad risky, but don't you want all CGI 
files to be executable by all? 


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


insertion sorts...

2008-06-23 Thread python_newbie
I don't know this list is the right place for newbie questions. I try
to implement insertion sort in pyhton. At first code there is no
problem. But the second one ( i code it in the same pattern i think )
doesn't work. Any ideas ?


def insertion_sort(aList):

for i in range(len(aList)):
for j in range(i):
if aList[i] < aList[j]:
aList.insert(j,aList[i])
del aList[i+1]


if __name__ == "__main__":

MyList = [7,3,5,19,8,2,9,4,15,6,8,3,19]
insertion_sort(MyList)
print MyList
-

def insertion_sort(aList):

for iterator in aList:
for number in range(aList.index(iterator)):
if iterator < number:
aList.insert(aList.index(number),iterator)
del aList[aList.index(iterator)+1]

if __name__ == "__main__":

MyList = [7,3,5,19,8,2,9,4,15,6,8,3,19]
insertion_sort(MyList)
print MyList
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using Python and MS-SQL Server

2008-06-23 Thread Tim Golden

[EMAIL PROTECTED] wrote:

I have programmed before, but I am new to using Python.  I am
currently using the ArcGIS software which uses Python as its scripting
language for automating tasks.

The current script that I am working on requires pulling in some
information from a Microsoft SQL Server.

I was wondering if anyone could suggest the best way of doing this?  I
have looked at the different modules that are specific to SQL server,
but none of them seem to be active or up to date.

If not, could anyone make any suggestions?  Or would it be better to
go the ODBC route?  I am not talking about large amounts of data, so I
am not concerned about performance so ODBC would be fine to use as
well.


Have a look at this:

http://ramblings.timgolden.me.uk/2007/09/26/using-mssql-from-within-python-25/

It's hardly comprehensive, but it more-or-less answers
your question.


Also, being new to Python, I recently read about dictionaries and was
wondering if there was a quick way to dump a table into a dictionary?

For example, I have a customer list with a customer ID.  It would be
great to have the ID as the "key" and the name as the "data" (or even
better, have a list as the data element containing all the information
about the customer).

I am sure that this could be done manually, by looping through each
record and adding it to the dictionary -- but I was just wondering if
something like this has already been done (I don't need to reinvent
the wheel here).


The key phrase you're looking for here is ORM (Object-Relational
Mapper). Again, not an exact match for what you're saying, but
unless you app remains *remarkably* simple, you're going to end
up reinventing an ORM anyway. Probably the front runner these
days is sqlalchemy (which certainly supports MS-SQL):

http://sqlalchemy.org

but just Google for "python orm" for any number of discussions
and comparisons.

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


Re: socket error: connection refused?

2008-06-23 Thread hall . jeff
It's a security conflict. You should be able to run it again and have
it work. Our company's cisco does the same thing (even after we
approve the app)
--
http://mail.python.org/mailman/listinfo/python-list


Re: socket error: connection refused?

2008-06-23 Thread cirfu
On 23 Juni, 20:55, [EMAIL PROTECTED] wrote:
> It's a security conflict. You should be able to run it again and have
> it work. Our company's cisco does the same thing (even after we
> approve the app)

doesnt work but i found out i should open the task manager and kill
all the python processes, then it works.
--
http://mail.python.org/mailman/listinfo/python-list


Re: learning unit testing in python

2008-06-23 Thread Josh English
A good starting point is Mark Pilgrim's Dive Into Python.

http://www.diveintopython.org/unit_testing/index.html

Josh
On Jun 23, 7:55 am, Alex <[EMAIL PROTECTED]> wrote:
> Hi all.
>
> I'd like learn some basic unit testing with python.
> I red some articles about different testing framework like unittest or
> nose, but I'm a bit confused: what is the best choice? I'm not a
> professional developer (I'm a SEO) but I belive that unit testing is a
> good and pragmatic way to produce working software, so I'd like to
> find something really simple ad straightforward because I don't have
> to manage big programming projects.
>
> Thanks in advance,
>
> Alex

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


Re: installed 3.0, rebind winprompt to 2.5?

2008-06-23 Thread Fuzzyman
On Jun 23, 6:53 pm, cirfu <[EMAIL PROTECTED]> wrote:
> i installed python 3.0. now when im laucnhing from the dos prompt in
> win vista it searches in python3.0
>
> i want to rebind it to 2.5, what do i need to change?

Reinstalling 2.5 should work.

Michael Foord
http://www.ironpythoninaction.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: learning unit testing in python

2008-06-23 Thread Josip
> Hi all.
>
> I'd like learn some basic unit testing with python.
> I red some articles about different testing framework like unittest or
> nose, but I'm a bit confused: what is the best choice? I'm not a
> professional developer (I'm a SEO) but I belive that unit testing is a
> good and pragmatic way to produce working software, so I'd like to
> find something really simple ad straightforward because I don't have
> to manage big programming projects.
>
> Thanks in advance,
>
> Alex

Have you checked out doctest?
http://docs.python.org/lib/module-doctest.html
It's the best way to add few tests to function or class, you just add
them to docstring.
Unit tests are somewhat demanding as they usualy require creating another
file just for storing them, but are ofcourse more powerful as well. For 
example,
unittest module alows you to execute a section of code before or after each 
test
to initialize values and clean up.

Nose module has few extra features, but it can also run test writen for 
unittest,
so it's easy to switch if you find standard library module lacking for your 
purpose. 


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


Re: Fast and easy GUI prototyping with Python

2008-06-23 Thread Sebastian "lunar" Wiesner
Michael Torrie <[EMAIL PROTECTED]>:

> Pete Kirkham wrote:
>> 2008/6/21 Val-Amart <[EMAIL PROTECTED]>:
>> 
>>> Use PyQt. You will gain great portability +all the functionality built
>>> in qt.
>>> You can try PyGTK also, though i wont recommend it.
>>>
>> Why would you not recommend it? I've been using it for a mall project,
>> and would like to know if there's some pit waiting for me to fall into.
> 
> The only pitfall is Mac compatibility.  OS X support in GTK is still
> under development, and much harder to get running than Qt.  I guess one
> other minor thing is that on win32 it's not quite native-looking, but
> pretty darn close.

Just out of curiosity:  Does gtk's look also match Vista's look?

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
--
http://mail.python.org/mailman/listinfo/python-list


Re: An idiom for code generation with exec

2008-06-23 Thread Fuzzyman
On Jun 21, 7:52 am, Peter Otten <[EMAIL PROTECTED]> wrote:
> eliben wrote:
> > On Jun 20, 2:44 pm, Peter Otten <[EMAIL PROTECTED]> wrote:
> >> eliben wrote:
> >> > Additionally, I've found indentation to be a problem in such
> >> > constructs. Is there a workable way to indent the code at the level of
> >> > build_func, and not on column 0 ?
>
> >> exec"if 1:" + code.rstrip()
>
> >> Peter
>
> > Why is the 'if' needed here ? I had .strip work for me:
>
> A simple .strip() doesn't work if the code comprises multiple lines:
>
> >>> def f():
>
> ...     return """
> ...     x = 42
> ...     if x > 0:
> ...             print x
> ...     """
> ...>>> exec "if 1:\n" + f().rstrip()
> 42
> >>> exec f().strip()
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 2
>     if x > 0:
>     ^
> IndentationError: unexpected indent
>
> You can of course split the code into lines, calculate the indentation of
> the first non-white line, remove that indentation from all lines and then
> rejoin.
>


textwrap.dedent will do all that for you...

Michael Foord
http://www.ironpythoninaction.com/

> Peter

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


Re: installed 3.0, rebind winprompt to 2.5?

2008-06-23 Thread Terry Reedy



cirfu wrote:

i installed python 3.0. now when im laucnhing from the dos prompt in
win vista it searches in python3.0

i want to rebind it to 2.5, what do i need to change?


When you install any Python on Windows with the .msi installer, there is 
a box something like

   [x] make this the default Python on this machine.
You apparently did not notice to uncheck it.
You could reinstall 2.5.  You should be able to directly change the file 
association between .py/,pyc and 'open', but I do not know how in Vista. 
 Try the help system or wait for another answer ;-)


PS.  What you call the 'dos prompt' is now called a 'Command Prompt'. 
There is no DOS on nt/xp/vista.


tjr

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


Re: Going from Tkinter to pyQT

2008-06-23 Thread Sebastian "lunar" Wiesner
Alex Bryan <[EMAIL PROTECTED]>:

> I had a guy on this mailing list tell me that pyQT is much better than
> Tkinter, and after looking into it a bit I think he is right. However,
> I can't find much on it. I want to know if there are any good books or
> online tutorials that would be helpful. I doubt there is one, but if
> there is one on going from Tkinter to pyQT, that would be amazing.
> Well if any of you guys have any tips or suggestions on any of this I
> would appreciate it.

There are some tutorials mentioned in the official python wiki [1].  Then
there is the PyQt wiki [2], which as a section dedicated to tutorials [3]. 
Moreover I absolutely recommend to read the reference gui from riverbank
computing [4].  At last, you should always keep the official docs at hand. 
They contain plenty of good tutorials and background documents about
different Qt4 techniques, that are _definitely_ worth reading.  Code
samples and API docs are of course kept in C++, but transferring these to
Python is mostly easy, the differences are not that big.

So you see, there's more than enough PyQt4 stuff out there ;)

But the most important thing to do at the transition from Tk to Qt4 goes
first, before you start digging any Qt4 specific document:  Forget
everything, you learned about GUI programming with Tk.  Qt4 works complety
differently! ;)

[1] http://wiki.python.org/moin/PyQt
[2] http://www.diotavelli.net/PyQtWiki
[3] http://www.diotavelli.net/PyQtWiki/Tutorials
[4] http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
--
http://mail.python.org/mailman/listinfo/python-list


tuple.index() and tuple.count()

2008-06-23 Thread hall . jeff
Before the inevitable response comes, let me assure you I've read
through the posts from Guido about this. 7 years ago Guido clearly
expressed a displeasure with allowing these methods for tuple. Let me
lay out (in a fresh way) why I think we should reconsider.

1) It's counterintuitive to exclude them: It makes very little sense
why an indexable data structure wouldn't have .index() as a method. It
makes even less sense to not allow .count()
2) There's no technical reason (that I'm aware of) why these can't be
added
3) It does not (contrary to one of Guido's assertions) require any
relearning of anything. It's a new method that could be added without
breaking any code whatsoever (there isn't even a UserTuple.py to
break)
4) The additional documentation is relatively minute (especially since
it could be copied and pasted virtually verbatim from the list methods
5) It's MORE Pythonic to do it this way (more intuitive, less
boilerplate)
6) It jives with the help file better. One of Guido's many stated
reasons was that tuples are for heterogeneous sequences and lists are
for homogeneous sequences. While this may be hypothetically true, the
help file does not come close to pointing you in this direction nor
does the implementation of the language.

example: "Tuples have many uses. For example: (x, y) coordinate pairs,
employee records from a database, etc. Tuples, like strings, are
immutable: it is not possible to assign to the individual items of a
tuple (you can simulate much of the same effect with slicing and
concatenation, though). It is also possible to create tuples which
contain mutable objects, such as lists." is a quote from the help
file. Not only does it never mention homogeneous vs. heterogeneous but
mentions both immutable and mutable which draws your mind and
attention to that aspect.

While tuples and lists may have different uses based on convention,
there's really only two reasons to ever use a tuple: Efficiency or
dictionary keys (or some similar immutability requirement). The
implementation contains absolutely NOTHING to reinforce the idea that
lists are for homogeneous data. The implementation of the language
contains EVERY indication that tuples are second class citizens only
to be used for those limited functions above (in fact, efficiency
isn't even talked about in the documentation... I pieced that together
from other threads). Tuples could have been implemented as frozenlist
just as easily.

The lack of .index() and .count() appears to be primarily motivated by
a subtle and silent (at least in the documentation) desire to push
towards coding "best practice" rather than for any technical reason.
While I'm certainly not a "change for change sake" kind of guy and I
understand the "bang for your buck" thinking, I'm just not seeing the
rational for stopping this so forcibly. I get the impression that if a
perfect working patch was submitted, Guido might still reject it which
just seems odd to me.

Again, I'm not trying to raise a stink or open old wounds, I just ran
across it in an app, started doing some research and was thoroughly
confused (for the record, I'm using the tuples as dictionary keys and
had a desire to do k.count() for some edit checks and realized I had
to convert the thing to a list first to run count() )
--
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe, PyQT, QtWebKit and jpeg problem

2008-06-23 Thread David Boddie
On Monday 23 June 2008 15:02, Carbonimax wrote:

> If I copy the dll in the dist directory, and I use QPluginLoader() and
> load(),
> it does work in the .py but it doesn't in .exe made with py2exe
> 
> my code :
> dll = QPluginLoader(path_to_dll)
> res = dll.load()
> 
> res == true in the .py
> res == false in the .exe
> 
> :-/

Maybe py2exe builds executables that can't load DLLs in this way.
In any case, it might be worth asking about this on the PyQt
mailing list

  http://www.riverbankcomputing.com/mailman/listinfo/pyqt

or on the py2exe mailing list

  https://lists.sourceforge.net/lists/listinfo/py2exe-users

where there may well be people who have solved this problem
independently.

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


Re: Using Python to run SSH commands on a remote server

2008-06-23 Thread Grant Edwards
On 2008-06-23, John Salerno <[EMAIL PROTECTED]> wrote:

> Generally speaking, what tools would I use to do this?

In shell scripts I use expect to automate ssh stuff, so I would
probably give pyexpect or pexpect a try:

  http://sourceforge.net/projects/pexpect/

> Is there a built-in module for it? I looked at the telnetlib
> module, but the documentation wasn't really complete enough
> for me to get a good idea of it. Is Telnet and SSH even the
> same thing?

Not even close.

> Basically, I want to write a script that will automate the
> process of making all .py files on my web server executable
> (chmod 755, or something similar).

I'd probably just write an expect script:

  http://expect.nist.gov/

-- 
Grant Edwards   grante Yow! Is a tattoo real, like
  at   a curb or a battleship?
   visi.comOr are we suffering in
   Safeway?
--
http://mail.python.org/mailman/listinfo/python-list


Re: tuple.index() and tuple.count()

2008-06-23 Thread hall . jeff
never mind... a coworker pointed me to this

http://bugs.python.org/issue1696444

apparently they're there in py3k...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using Python to run SSH commands on a remote server

2008-06-23 Thread Jeffrey Froman
John Salerno wrote:

> I guess a blanket process might be a tad risky, but don't you want all CGI
> files to be executable by all?

Typically, I prefer CGI scripts to be executable only the owner. If the web
server runs those scripts as a different user, then that user must also be
permitted to execute the scripts of course.

Also note that "all .py files on my web server" is not necessarily
restricted to CGI scripts -- and therein lies the real gist of my
cautionary note.


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


Re: 2to3 bug and question

2008-06-23 Thread Christian Heimes
Helmut Jarausch wrote:
> Hi,
> 
> is this the right group to ask / report problems with python3.0 ?

While the general Python list is the right place to discuss bugs it's
not sensible to report them here. Most Python core developers except
Martin, me and a few more aren't reading this list at all. The bug
tracker at http://bugs.python.org/ as a category for 2to3 bugs and
feature requests.

Grüße von der anderen Seite Aachens

Christian

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


Re: insertion sorts...

2008-06-23 Thread Terry Reedy



python_newbie wrote:

I don't know this list is the right place for newbie questions.


It is.  We get them all the time.  There is also a tutor mailing list.

> I try to implement insertion sort in pyhton.

python

> At first code there is no problem.

It is pretty straightforward.


But the second one ( i code it in the same pattern i think )


Same pattern, but different algorithm as written.


doesn't work. Any ideas ?


When something 'doesn't work', you should post how and some details.  If 
an exception is raised, *cut and paste* the full traceback and error 
message after examining it yourself.  If bad output is produced, *cut 
and paste* that.  Here is it obvious what good output would be.  When it 
is not, say what you expected that is different.


In this case, I am not sure why you think the new algorithm will work.
But I suspect you were not trying to write a different algorithm ;-)
see below.



def insertion_sort(aList):

for i in range(len(aList)):
for j in range(i):
if aList[i] < aList[j]:
aList.insert(j,aList[i])
del aList[i+1]


The last two lines could be replaced with
aList[j:i+1] = [aList[i]]+aList[j:i]
which directly replace a slice of the list with a rotated version

You could also lookup aList[i] just once by adding item = aList[i] 
before the j loop.  This also makes the code slightly easier to read.



if __name__ == "__main__":

MyList = [7,3,5,19,8,2,9,4,15,6,8,3,19]
insertion_sort(MyList)
print MyList
-

def insertion_sort(aList):

for iterator in aList:


The members of aList are 'items' or whatever, but not iterators.


for number in range(aList.index(iterator)):
if iterator < number:
aList.insert(aList.index(number),iterator)
del aList[aList.index(iterator)+1]


Calculating alist.index(item) twice is bad.  Do it once before the inner 
loop.




if __name__ == "__main__":

MyList = [7,3,5,19,8,2,9,4,15,6,8,3,19]
insertion_sort(MyList)
print MyList


Here is the error message you omitted

Traceback (most recent call last):
  File "C:\Program Files\Python30\misc\temp", line 12, in 
insertion_sort(MyList)
  File "C:\Program Files\Python30\misc\temp", line 6, in insertion_sort
aList.insert(aList.index(number),iterator)
ValueError: list.index(x): x not in list

I believe you meant to insert at number, which is a position, not 
index(position), which only accidentally works.  With that corrected, I 
believe you were trying to write


for item in aList:
i = aList.index(item)
for number in range(i):
if item < aList[number]:
aList.insert(number,item)
del aList[i+1]

which looks parallel to the first code, which runs, but which does not 
sort.  The difference is iterating through items instead of positions.


The problem is that aList is being modified inside the loop.  That 
usually is a bad idea.  If you want to sort the list in place without 
either copying the list or building a new sorted list, you have to use 
indexes.


Terry Jan Reedy



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


Re: 2to3 bug and question

2008-06-23 Thread Terry Reedy



Helmut Jarausch wrote:


is this the right group to ask / report problems with python3.0 ?


It is certainly a place.  Given the number of bogus bug reports on 
bugs.python.org, asking here is often a good idea.  In this and your 
other post, the problems you report look like probable bugs to me, so go 
ahead and report them on the bug list unless someone else has an 
explanation (within a day, say).


2to3 had probably been less well tested and debugged than either of the 
new releases, so testing it now is helpful.


tjr

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


Re: [2to3] Bug converting import

2008-06-23 Thread Christian Heimes
Helmut Jarausch wrote:
> Now, when I invoke Master.py  I get
> 
> Traceback (most recent call last):
>   File "Master.py", line 2, in 
> from . import Slave
> ValueError: Attempted relative import in non-package
> 
> 
> thanks for looking into it,

The cause of the bug is in fixes/fix_import.py
probably_a_local_import(). The function doesn't check if
dirname(file_path) is a package.

This patch should fix the bug:

Index: Lib/lib2to3/fixes/fix_import.py
===
--- Lib/lib2to3/fixes/fix_import.py (Revision 64490)
+++ Lib/lib2to3/fixes/fix_import.py (Arbeitskopie)
@@ -53,8 +53,13 @@
 # Must be stripped because the right space is included by the parser
 imp_name = imp_name.split('.', 1)[0].strip()
 base_path = dirname(file_path)
-base_path = join(base_path, imp_name)
-for ext in ['.py', pathsep, '.pyc', '.so', '.sl', '.pyd']:
-if exists(base_path + ext):
+base_name = join(base_path, imp_name)
+base_init = join(base_path, "__init__")
+exts = ['.py', pathsep, '.pyc', 'pyo', '.so', '.sl', '.pyd']
+if not any(exists(base_init + ext) for ext in exts):
+# not a package
+return False
+if any(exists(base_name + ext) for ext in exts):
 return True
 return False

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


Re: Storing value with limits in object

2008-06-23 Thread Lie
On Jun 23, 1:24 am, "Josip" <[EMAIL PROTECTED]> wrote:
> > Why not make it a function?
>
> > function assignLimited(value, vmin, vmax):
> >     value = max(vmin, value)
> >     value = min(vmax, value)
> >     return value
>
> > a = assignLimited(7, 0, 10)
>
> > Seems like it solves your problem relatively cleanly.
> > Note: I also removed min/max variables because they would mask the
> > built-in min/max functions.
>
> > -Larry
>

> Still, I'm going for object
> oriented solution because I want the value and it's limits to be kept
> together as I'll have many such values with different limits.

In that case, "overriding assignment" makes no sense since if an
operation is done on two values that have two different limits, what
would happen? Take the first's or second's limits, or interpolate the
new limit by some magic function? A much better solution would be for
operation to always return plain vanilla int, and we set limits
explicitly.

> Storing all
> the limits in caller namespace is not really an option.

You want to store limits in the object too?

Try this: (_LimitedInt inherits from int, so operator overloading is
unnecessary)

###
#!/usr/bin/env python

class _LimitedInt(int):
class InvalidLimitsError(Exception): pass

def __init__(self, value, base = 10):
int.__init__(value, base)

def setlimits(self, lim):
''' Set the limits and if value is not within limit,
raise ValueError

The lim argument accepts:
- A _LimitedInt instance, from which to copy the limits
- A two-tuple, which specifies the limits i.e. (min, max)

If lim isn't those or lim[0] > lim[1], raise
InvalidLimitsError

Accepting _LimitedInt instance is just for convenience
'''

if isinstance(lim, _LimitedInt):
lim = lim.limits

try:
self.min, self.max = [int(x) for x in lim]
if self.min > self.max: raise ValueError
except (ValueError, TypeError):
raise self.InvalidLimitsError, ('limit = %s' % str(lim))

if not (self.min < self < self.max):
raise ValueError, \
  ('val = %s, min = %s, max = %s' % \
  (self, self.min, self.max))

def getlimits(self):
return (self.min, self.max)

limits = property(getlimits, setlimits)

def lint(value, limits, base = 10):
if base != 10:
ret = _LimitedInt(value, base)
else:
ret = _LimitedInt(value)

ret.limits = limits
return ret

### END OF REAL CODE###
### THE REST ARE JUST TESTING CODES ###

if __name__ == '__main__':
print 'Instantiating lint...'
a = lint(50, (0, 200))  # Limit explicitly specified
b = lint(150, a)# Copy the limits of a
c = lint(a, (0, 1000))  # Value = a, Limit = (0, 1000)
d = lint(a, c)  # Value = a, Limit = c
print

print 'Printing the value and the limits...'
print a, a.limits
print b, b.limits
print c, c.limits
print d, d.limits
print

print 'Changing limits'
print 'Note: lint is partially immutable,'
print '  its limits is mutable,'
print '  while its value is immutable'
a.limits = (0, 300)
b.limits = a
print a, a.limits
print b, b.limits
print

print '"Changing" values'
a = lint(b, a)
print a, a.limits
print

print 'Operations...'
e = lint(a + b - c * d + 100, (-1, 1000))
f = a + b - c * d  ## Operation returns plain integer
g = lint(f, (-10, 10)) ## Always recast result of operator
print e, e.limits, type(e) ## This is an int, not lint
print f, type(f)   ## BEWARE: f is integer, it has no
limits
print g, g.limits, type(g)

## INVALIDS
# a = lint(100, (1000, 10))
# a = lint(100, 'ab')
# a = lint(100, (1, 0))
# a = lint(100, 10)
# a = lint(100, (10, 1000, 1))###
--
http://mail.python.org/mailman/listinfo/python-list


Re: Storing value with limits in object

2008-06-23 Thread Lie
On Jun 23, 1:24 am, "Josip" <[EMAIL PROTECTED]> wrote:
> > Why not make it a function?
>
> > function assignLimited(value, vmin, vmax):
> >     value = max(vmin, value)
> >     value = min(vmax, value)
> >     return value
>
> > a = assignLimited(7, 0, 10)
>
> > Seems like it solves your problem relatively cleanly.
> > Note: I also removed min/max variables because they would mask the
> > built-in min/max functions.
>
> > -Larry
>

> Still, I'm going for object
> oriented solution because I want the value and it's limits to be kept
> together as I'll have many such values with different limits.

In that case, "overriding assignment" makes no sense since if an
operation is done on two values that have two different limits, what
would happen? Take the first's or second's limits, or interpolate the
new limit by some magic function? A much better solution would be for
operation to always return plain vanilla int, and we set limits
explicitly.

> Storing all
> the limits in caller namespace is not really an option.

You want to store limits in the object too?

Try this: (_LimitedInt inherits from int, so operator overloading is
unnecessary)

###
#!/usr/bin/env python

class _LimitedInt(int):
class InvalidLimitsError(Exception): pass

def __init__(self, value, base = 10):
int.__init__(value, base)

def setlimits(self, lim):
''' Set the limits and if value is not within limit,
raise ValueError

The lim argument accepts:
- A _LimitedInt instance, from which to copy the limits
- A two-tuple, which specifies the limits i.e. (min, max)

If lim isn't those or lim[0] > lim[1], raise
InvalidLimitsError

Accepting _LimitedInt instance is just for convenience
'''

if isinstance(lim, _LimitedInt):
lim = lim.limits

try:
self.min, self.max = [int(x) for x in lim]
if self.min > self.max: raise ValueError
except (ValueError, TypeError):
raise self.InvalidLimitsError, ('limit = %s' % str(lim))

if not (self.min < self < self.max):
raise ValueError, \
  ('val = %s, min = %s, max = %s' % \
  (self, self.min, self.max))

def getlimits(self):
return (self.min, self.max)

limits = property(getlimits, setlimits)

def lint(value, limits, base = 10):
if base != 10:
ret = _LimitedInt(value, base)
else:
ret = _LimitedInt(value)

ret.limits = limits
return ret

### END OF REAL CODE###
### THE REST ARE JUST TESTING CODES ###

if __name__ == '__main__':
print 'Instantiating lint...'
a = lint(50, (0, 200))  # Limit explicitly specified
b = lint(150, a)# Copy the limits of a
c = lint(a, (0, 1000))  # Value = a, Limit = (0, 1000)
d = lint(a, c)  # Value = a, Limit = c
print

print 'Printing the value and the limits...'
print a, a.limits
print b, b.limits
print c, c.limits
print d, d.limits
print

print 'Changing limits'
print 'Note: lint is partially immutable,'
print '  its limits is mutable,'
print '  while its value is immutable'
a.limits = (0, 300)
b.limits = a
print a, a.limits
print b, b.limits
print

print '"Changing" values'
a = lint(b, a)
print a, a.limits
print

print 'Operations...'
e = lint(a + b - c * d + 100, (-1, 1000))
f = a + b - c * d  ## Operation returns plain integer
g = lint(f, (-10, 10)) ## Always recast result of operator
print e, e.limits, type(e) ## This is an int, not lint
print f, type(f)   ## BEWARE: f is integer, it has no
limits
print g, g.limits, type(g)

## INVALIDS
# a = lint(100, (1000, 10))
# a = lint(100, 'ab')
# a = lint(100, (1, 0))
# a = lint(100, 10)
# a = lint(100, (10, 1000, 1))###
--
http://mail.python.org/mailman/listinfo/python-list


Re: insertion sorts...

2008-06-23 Thread Matimus
On Jun 23, 11:52 am, python_newbie <[EMAIL PROTECTED]> wrote:
> I don't know this list is the right place for newbie questions. I try
> to implement insertion sort in pyhton. At first code there is no
> problem. But the second one ( i code it in the same pattern i think )
> doesn't work. Any ideas ?
>
> 
> def insertion_sort(aList):
>
>     for i in range(len(aList)):
>         for j in range(i):
>             if aList[i] < aList[j]:
>                 aList.insert(j,aList[i])
>                 del aList[i+1]
>
> if __name__ == "__main__":
>
>     MyList = [7,3,5,19,8,2,9,4,15,6,8,3,19]
>     insertion_sort(MyList)
>     print MyList
> -
>
> def insertion_sort(aList):
>
>     for iterator in aList:
>         for number in range(aList.index(iterator)):
>             if iterator < number:
>                 aList.insert(aList.index(number),iterator)
>                 del aList[aList.index(iterator)+1]
>
> if __name__ == "__main__":
>
>     MyList = [7,3,5,19,8,2,9,4,15,6,8,3,19]
>     insertion_sort(MyList)
>     print MyList

In your second attempt `number` is still essentially the same thing as
`j` was in the first one. In the following line however, you treat
`number` as if it is the actual value. It _should_ be `if iterator <
aList[number]`.

Also, you are missing a `break` after you do an insertion (this goes
for both versions). The bigger question is why did the first one work?
I think it works because in this statement `if aList[i] < aList[j]:`
the value of `aList[i]` changes after the insertion to a different
value. Because of the way this algorithm works, that _new_ value is
guaranteed to be >= `aList[j]` so the insertion is never performed
again. In the second version `iterator` stays as the original value
even after it makes an insertion. This will cause it to perform the
insertion multiple times.

May I suggest you look into using `enumerate`:

>>> for i, val in enumerate([4,5,6]):
...  print i, val
...
0 4
1 5
2 6

It allows you to get the index and the value at the same time, which
should eliminate the need for `aList.index`.

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


Re: Using Python to run SSH commands on a remote server

2008-06-23 Thread John Salerno

Jeffrey Froman wrote:


Also note that "all .py files on my web server" is not necessarily
restricted to CGI scripts -- and therein lies the real gist of my
cautionary note.



Yeah, I realized that afterwards. Good point. I was assuming all my 
executable files would be CGI, but that's not a good assumption to make! :)

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


Re: learning unit testing in python

2008-06-23 Thread Alex
On 23 Giu, 21:26, "Josip" <[EMAIL PROTECTED]> wrote:
> > Hi all.
>
> > I'd like learn some basic unit testing with python.
> > I red some articles about different testing framework like unittest or
> > nose, but I'm a bit confused: what is the best choice? I'm not a
> > professional developer (I'm a SEO) but I belive that unit testing is a
> > good and pragmatic way to produce working software, so I'd like to
> > find something really simple ad straightforward because I don't have
> > to manage big programming projects.
>
> > Thanks in advance,
>
> > Alex
>
> Have you checked out doctest?http://docs.python.org/lib/module-doctest.html
> It's the best way to add few tests to function or class, you just add
> them to docstring.
> Unit tests are somewhat demanding as they usualy require creating another
> file just for storing them, but are ofcourse more powerful as well. For
> example,
> unittest module alows you to execute a section of code before or after each
> test
> to initialize values and clean up.
>
> Nose module has few extra features, but it can also run test writen for
> unittest,
> so it's easy to switch if you find standard library module lacking for your
> purpose.

Tanks a lot. I'll the resources you suggest..
--
http://mail.python.org/mailman/listinfo/python-list


Re: learning unit testing in python

2008-06-23 Thread BJörn Lindqvist
On Mon, Jun 23, 2008 at 2:55 PM, Alex <[EMAIL PROTECTED]> wrote:
> Hi all.
>
> I'd like learn some basic unit testing with python.
> I red some articles about different testing framework like unittest or
> nose, but I'm a bit confused: what is the best choice? I'm not a
> professional developer (I'm a SEO) but I belive that unit testing is a

The best framework is nose at
http://www.somethingaboutorange.com/mrl/projects/nose/. If you aren't
already familiar with unit testing then http://diveintopython.org has
a good tutorial about it at
http://diveintopython.org/unit_testing/index.html.

-- 
mvh Björn
--
http://mail.python.org/mailman/listinfo/python-list


regexp: match only if previous matched?

2008-06-23 Thread cirfu
I need to extract prices froma html-document.

[0-9]*\$ matches 112$ 45$ etc but also just a $. why that shouldnt
really matter and it is unlikely anyway to appear a $sign with no
price attahced to it I still want to prevent it.

How do I avoid matching "$"? It has to be "nbr$".
--
http://mail.python.org/mailman/listinfo/python-list


Re: regexp: match only if previous matched?

2008-06-23 Thread Vlastimil Brom
2008/6/24, cirfu <[EMAIL PROTECTED]>:
>
> I need to extract prices froma html-document.
>
> [0-9]*\$ matches 112$ 45$ etc but also just a $. why that shouldnt
> really matter and it is unlikely anyway to appear a $sign with no
> price attahced to it I still want to prevent it.
>
> How do I avoid matching "$"? It has to be "nbr$".
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
In this simple case you can simple use something like:

[0-9]+\$

ie. at least one digit immediately folowed by a dollar-sign

If you really needed to check for a preceding text, look into

look-behind assertions of the form  (?<=...) or (?http://docs.python.org/lib/re-syntax.html

hth,

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

Re: String question

2008-06-23 Thread Andreu

Yes, ... don't ask me why, but in fact  v1,v2,v3 = str1.split()
does not seem to work. My original problem was I forgot about
the parenthesis as Tim point out. So I ended up converting to a
list as in:  v = str1.split() and accessing the elements using
v[0] v[1] ect...it is working now. Thanks.

Andreu.


[EMAIL PROTECTED] wrote:

However I would make a list of it.

v_list = example.split()

That seems to me to be the more pythonic way to do it, since it is
dynamic.

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


Re: regexp: match only if previous matched?

2008-06-23 Thread Carl Banks
On Jun 23, 6:02 pm, cirfu <[EMAIL PROTECTED]> wrote:
> I need to extract prices froma html-document.
>
> [0-9]*\$ matches 112$ 45$ etc but also just a $. why that shouldnt
> really matter and it is unlikely anyway to appear a $sign with no
> price attahced to it I still want to prevent it.
>
> How do I avoid matching "$"? It has to be "nbr$".

The answer to your question is to use a + instead of *.  + matches 1
or more elements, * matches zero or more.

The second point to mention is that, at least where I come from, the
currency symbol comes before the number:

$112 and $45

In which case your regexp should be somehting like this: \$[0-9]+


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


Re: Storing value with limits in object

2008-06-23 Thread Lie
#!/usr/bin/env python

## VERSION 2
##
## changelog:
## - Uses inheritance from _Limited
## - Added _LimitedLong and llong
## - limit choose between int, long, and float

class _Limited(object):
def setlimits(self, lim):
''' Set the limits and if value is not within limit,
raise ValueError

The lim argument accepts:
- An instance of _Limited, from which to copy the limits
- A two-tuple, which specifies the limits i.e. (min, max)

If lim isn't those or lim[0] > lim[1], raise
InvalidLimitsError

Accepting _Limited instance is just for convenience
'''

if isinstance(lim, _Limited):
self.min, self.max = lim.limits
else:
try:
self.min, self.max = lim
if self.min > self.max: raise ValueError
except (ValueError, TypeError):
raise self.InvalidLimitsError, ('limit = %s' %
str(lim))

if not (self.min < self < self.max):
raise ValueError, \
  ('val = %s, min = %s, max = %s' % \
  (self, self.min, self.max))

def getlimits(self):
return (self.min, self.max)

limits = property(getlimits, setlimits)

class _LimitedInt(int, _Limited):
def __init__(self, value, base = 10):
int.__init__(value, base)

class _LimitedLong(long, _Limited):
def __init__(self, value, base = 10):
long.__init__(value, base)

class _LimitedFloat(float, _Limited):
def __init__(self, value):
float.__init__(value)


def lint(value, limits, base = None):
''' Always Creates _LimitedInt instance, allows the use of base
'''
if base:
ret = _LimitedInt(value, base)
else:
ret = _LimitedInt(value)

ret.limits = limits
return ret

def llong(value, limits, base = None):
''' Always Creates _LimitedLong instance, allows the use of base
'''
if base:
ret = _LimitedLong(value, base)
else:
ret = _LimitedLong(value)

ret.limits = limits
return ret

def lfloat(value, limits):
''' Always Creates _LimitedFloat instance
'''
ret = _LimitedFloat(value)

ret.limits = limits
return ret

def limit(value, limits):
''' Automatically choose between _LimitedInt, _LimitedLong,
or _LimitedFloat. Cannot use _LimitedInt's/Long's base
'''
if isinstance(value, (int, long)):
try:
ret = _LimitedInt(value)
except OverflowError:
ret = _LimitedLong(value)
elif isinstance(value, float):
ret = _LimitedFloat(value)

ret.limits = limits
return ret
--
http://mail.python.org/mailman/listinfo/python-list


Re: Terminating processes on Windows (handles and IDs)

2008-06-23 Thread Val-Amart
On Jun 23, 6:33 pm, geoffbache <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I've always wondered why os.kill isn't supported on Windows. I found a
> discussion somewhere from 2006 about this so it seems others have
> wanted it, but still nothing. So I have a half-baked solution
> involving calling "taskkill" on Windows Vista or "tskill" on Windows
> XP via the shell. I feel there has to be a better way.
>
> I'm also fairly confused about when I've got an ID and when I've got a
> handle. The subprocess module gives me IDs which the above programs
> accept, but other ways of spawning processes give me process handles
> (while referring to them as process IDs in the docs...) and I don't
> know how to kill a process with these. Besides, I've found an
> amazingly useful PyGTK method, gobject.child_watch_add, which does
> exactly what I want on UNIX but wants process handles on Windows. So I
> can't use it in conjunction with subprocess there, and if I use some
> other way of spawning processes I can't clean them up later.
>
> Is there any way to convert one of these numbers to the other? Or to
> get a process handle out of subprocess?
> (There must be one down there somewhere, surely?)
>
> Sorry for rambling a bit, am confused.
>
> Regards,
> Geoff Bache

My way to do it is using excellent wmi module by Tim Golden, which
relies on Mark Hammond's pywin32 and Windows native wmi functionality.
Here is the link - http://tgolden.sc.sabren.com/python/wmi.html
Maybe, there is a more elegant way of doing that, but it works for me,
and i feel nice with wmi.
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >