Re: Built-in functions and keyword arguments

2007-10-30 Thread Marc 'BlackJack' Rintsch
On Tue, 30 Oct 2007 07:28:07 +0200, Hendrik van Rooyen wrote:

> yes - the point I am trying to make is that the intention of the OP
> was to use an assignment as an argument, and you can't do that,
> as the interpreter thinks its a keyword.   Hence the gotcha.

Then you must have misunderstand his intention.  He wanted to give the
optional third argument of `getattr()` as keyword argument.

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


Re: Iteration for Factorials

2007-10-30 Thread Anurag
What about this no map, reduce, mutiplication or even addition
Its truly interative and You will need to interate till infinity if
you want correct answer ;)

def factorial(N):
"""
Increase I ...and go on increasing...
"""
import random

myNumer = range(N)
count = 0
I = 1 #10**(N+1)
for i in range(I):
bucket = range(N)
number = []
for i in range(N):
k = bucket[ random.randrange(0,len(bucket))]
bucket.remove(k)
number.append(k)

if number == myNumer:
count+=1

return int(I*1.0/count+.5)

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


Re: A Python 3000 Question

2007-10-30 Thread Marc 'BlackJack' Rintsch
On Mon, 29 Oct 2007 19:50:14 -0700, George Sakkis wrote:

> On Oct 29, 5:49 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> 
>> | why not a_string.len()?
>>
>> You are free to bypass builtins and call methods directly if you like:
>> a_string.__len__().
>>
>> But consider rewriting the following:
>>
>> def table(func, seq):
>> return zip(seq, map(func,seq))
>>
>> table(len, ('', (), []))
> 
> table(lambda x:x.__len__(), ('',[],()))
> 
> What was the point again ?

Beautiful is better than ugly!? ;-)

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


Re: A Python 3000 Question

2007-10-30 Thread Thomas Wittek
Bjoern Schliessmann:
> Is there any particular reason why it should be a method?
> 
> [..]
> 
> To make a long story short: Most methods do specific things with
> objects; but len is a common function to get a simple property of
> an object.

You said it. IMHO it really could be a *property*, say `object.len`.
It doesn't do something on the object, but rather gives some information
about its "state".

-- 
Thomas Wittek
Web: http://gedankenkonstrukt.de/
Jabber: [EMAIL PROTECTED]
GPG: 0xF534E231
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How python writes text into another windows application

2007-10-30 Thread Laurent Pointal
Le Mon, 29 Oct 2007 21:53:47 +, Meitham a écrit :

> Hi,
> 
> I am trying to write a simple program that reads data from a source file
> (Excel sheet, XML file or text file) and then write the data into
> another application by pasting the data into the applications fields,
> and jumps from one field to another by writing \t tab.
> 
> My question is, how do I write the data into another application fields.
> My target application is the TNT consignment manager. I asked TNT for
> their API to make my life easier but they refused to release it :(. I
> have a software that uses the same way I am looking after to fill in
> application fields, it is the QuickAddress. Any idea how to achieve
> that?
> 
> Thanks
> 
> Meitham

If you run Windows, try with pywinauto, it should have the tools you need 
to control an external application via its gui.


http://sourceforge.net/projects/pywinauto





-- 
Laurent POINTAL - [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: A Python 3000 Question

2007-10-30 Thread Bruno Desthuilliers
brad a écrit :
> Will len(a_string) become a_string.len()? I was just reading
> 
> http://docs.python.org/dev/3.0/whatsnew/3.0.html
> 
> One of the criticisms of Python compared to other OO languages is that 
> it isn't OO enough

Really ? IIRC, Python doesn't have primitive types, functions are 
objects, methods are objects, classes are objects, even modules are 
objects... Isn't this 'OO enough' ?

> or as OO as others

Which ones ? Java, that does have primitive types ?

(snip question about len() not being a method - no personal opinion on 
the topic)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A class question

2007-10-30 Thread Hrvoje Niksic
Bruno Desthuilliers <[EMAIL PROTECTED]>
writes:

>> While Java's variable declarations bear a superficial (syntactical)
>> similarity to C, their semantics is in fact equivalent to the
>> object-reference semantics we know in Python.   They implicitly refer
>> to objects allocated on the heap and, just like in Python, the same
>> object can be referenced by multiple variables. 
>
> You're talking about reference types here - not primitive types. And
> even then, from what I remember (not having done any Java these last
> 4 years at least), Java's reference types are much closer to C++
> references than to Python.

Feel free to look it up; I believe you will find the semantics of
assignment, parameter-passing, etc., exactly the same as in Python.

>> Variables holding primitive types don't really influence the
>> variable/object relationship, since the values they hold are by
>> nature immutable and without identity.
>
> Python's immutable types instances does have an identity,

Just to clarify, here I was talking about Java's primitive-typed
variables, not drawing a parallel between Java and Python in that
area.
-- 
http://mail.python.org/mailman/listinfo/python-list


Retrieving all open applications ...

2007-10-30 Thread Ajay Deshpande
Hi everyone:

I need to retrieve all currently open applications using a python program.
So my output should be a list of window handles. Is there a module which I
can use?

Thanks for any help.

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

Re: Automatic Generation of Python Class Files

2007-10-30 Thread Bruno Desthuilliers
Fuzzyman a écrit :
> On Oct 22, 6:43 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
(snip)
>> # Inherit from object. There's no reason to create old-style classes.
> 
> 
> We recently had to change an object pipeline from new style classes to
> old style. A lot of these objects were being created and the *extra
> overhead* of new style classes was killing us. :-)
> 
Maybe a dumb question, but what about __slots__ here ? (NB : never faced 
this kind of problem myself).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Python 3000 Question

2007-10-30 Thread Bruno Desthuilliers
brad a écrit :
> Rob Wolfe wrote:
> 
>> I wonder why people always complain about `len` function but never
>> about `iter` or `pprint.pprint`? :)
> 
> Not complaining. len is simple and understandable and IMO fits nicely 
> with split(), strip(), etc... that's why I used it as an example, but 
> list(), etc. could be used as examples as well:
> 
> a_string.list() instead of list(a_string)

Oh, fine. And a_string.tuple(), a_string.int(), a_string.this(), 
a_string.that() etc ?

In case you don't know, list is a type, not a function !-)

>> And to answer the question. In OO programming generic functions
>> are no less important than classes and objects.
> 
> Do they not take away from the OOness of the overall language

Why so ?

> and 
> introduce inconsistencies?

The monotonic approach to callables in Python (I mean: functions are 
callable objects, classes are callable objects, so instanciation and 
function call have the exact same syntax - which let you decouple 
interface from implementation) is another way to be consistent. because 
you can switch from type to factory function (or from closure to 
callable object, etc) back and forth without breaking client code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A class question

2007-10-30 Thread Bruno Desthuilliers
Hrvoje Niksic a écrit :
> Bruno Desthuilliers <[EMAIL PROTECTED]>
> writes:
> 
>>> It seems to me that in recent times more Python beginners come from
>>> a Java background than from a C one.
>> Java does have "container" variables for primitive types, and even
>> for "references", Java's variables are more than names - they do
>> hold type informations too. Now I don't pretend to know how this is
>> really implemented, but AFAICT, and at least from a cognitive POV,
>> Java's variables model looks very close to the C/C++ model.
> 
> While Java's variable declarations bear a superficial (syntactical)
> similarity to C, their semantics is in fact equivalent to the
> object-reference semantics we know in Python.   They implicitly refer
> to objects allocated on the heap and, just like in Python, the same
> object can be referenced by multiple variables. 

You're talking about reference types here - not primitive types. And 
even then, from what I remember (not having done any Java these last 4 
years at least), Java's reference types are much closer to C++ 
references than to Python.

> If Java's model were
> close to C/C++, that would not be possible without explicit
> pointers/references

The reference is implicit for non-primitive types.

> since an object would be "contained" by the
> variable.
> 
> Variables holding primitive types don't really influence the
> variable/object relationship, since the values they hold are by nature
> immutable and without identity.

Python's immutable types instances does have an identity, and follow the 
same rules as mutable types instances - mutability set aside of course. 
Which is not the case with Java, where primitive types and reference 
types follow distinct rules. I'll check this out (not having done Java 
for a couple years) and come back, but I certainly remember Java's model 
as being way closer to C++ than to Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help ctypes on arm linux not compile

2007-10-30 Thread Thomas Heller
Samuel M. Smith schrieb:
> I have built python 1.5.1 from source for an embedded ARM9 debian  
> linux Sarge distribution but
> ctypes doesn't build.  Anybody have any idea what the problem is? Do  
> I have to have the libffi package
> installed.
> See my errors below.

ctypes won't work with Python 1.5 because it uses new style classes, introduced 
in Python 2.2.
It uses other, newer features additionally, so it requires Python 2.3 at least.

Then, the included libffi package doesn't support ARM, you need a newer libffi
version.

I think that the current Python 2.5 sources, from SVN, should work.

Thomas

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


Re: Automatic Generation of Python Class Files

2007-10-30 Thread Hrvoje Niksic
Fuzzyman <[EMAIL PROTECTED]> writes:

> We recently had to change an object pipeline from new style classes
> to old style. A lot of these objects were being created and the
> *extra overhead* of new style classes was killing us. :-)

Can you please expand on this?  What extra overhead of new-style
classes are you referring to?

Memory overhead seems to firmly favor new-style classes, especially
for small object.  A trivial small-object allocation test such as

# After running this, use "top" or "ps" to see the ballpark memory
# consumption.  Remove "(object)" to measure for old-style class.
python -c 'import time
class A(object): pass
l=[A() for n in xrange(200)]
time.sleep(100)'

shows the Python process growing to 78M with a new-style class and to
354M with an old-style class.  And that is without even starting to
use actual optimizations, such as using __slots__!  Instantiation time
difference is less drastic, but still shows significant improvement
with the use of new-style classes: 0.27 usec for new-style, 0.40 usec
old-style (measured with timeit, subtracted baseline overhead).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How python writes text into another windows application

2007-10-30 Thread Wolfgang Draxinger
Meitham wrote:

> My question is, how do I write the data into another
> application fields. My target application is the TNT
> consignment manager. I asked TNT for their API to make my life
> easier but they refused to release it :(.

You know what the word "market" means? Just tell TNT, that it
seems they don't need you as a customer and so you will change
to another parcel service.

I had the very same situation with a regional parcel service a
few years ago, you won't believe how quick they were in
providing me with API information, in the prospect of loosing a
valuable customer (the fact that you want to automatize the
process suggests, that you have a lot of stuff to be delivered).

If they still don't bite, just show them a calculation, that it's
cheaper for you, to choose another parcel service that might
cost more, but you can save that money with the automatized data
entry.

Of course it's possible to send keypresses, mouse moves/clicks
and other messages to another application, but then you _MUST_
make sure, that no other application or a user interferes in the
process, and if an update of the software changes the interface
you have to reimplement the stuff from grounds up.

Wolfgang Draxinger
-- 
E-Mail address works, Jabber: [EMAIL PROTECTED], ICQ: 134682867

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


Re: Iteration for Factorials

2007-10-30 Thread Nick Craig-Wood
Anurag <[EMAIL PROTECTED]> wrote:
>  What about this no map, reduce, mutiplication or even addition
>  Its truly interative and You will need to interate till infinity if
>  you want correct answer ;)
> 
>  def factorial(N):
>  """
>  Increase I ...and go on increasing...
>  """
>  import random
> 
>  myNumer = range(N)
>  count = 0
>  I = 1 #10**(N+1)
>  for i in range(I):
>  bucket = range(N)
>  number = []
>  for i in range(N):
>  k = bucket[ random.randrange(0,len(bucket))]
>  bucket.remove(k)
>  number.append(k)
> 
>  if number == myNumer:
>  count+=1
> 
>  return int(I*1.0/count+.5)

;-)

Note you can write your middle loop as

for i in range(I):
number = myNumer[:]
random.shuffle(number)
if number == myNumer:
count+=1


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


Re: Automatic Generation of Python Class Files

2007-10-30 Thread Fuzzyman
On Oct 29, 11:35 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
> Fuzzyman wrote:
> > On Oct 22, 6:43 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
> >> # Inherit from object. There's no reason to create old-style classes.
>
> > We recently had to change an object pipeline from new style classes to
> > old style. A lot of these objects were being created and the *extra
> > overhead* of new style classes was killing us. :-)
>
> I'm curious.  Was it memory or speed overhead that was the problem?


It was speed overhead - I have to add a disclaimer that this is
IronPython, but my understanding is that the situation is similar with
CPython. Creating new style class instances is slower than for old
style classes.

This was in the execution of spreadsheets, where we had a pipeline of
three objects for each spreadsheet element (not sure if the
implementation is still the same now).

Michael
http://www.manning.com/foord


>
> Steve


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


Re: Iteration for Factorials

2007-10-30 Thread Marco Mariani
Nick Craig-Wood wrote:

> Note you can write your middle loop as
> 
> for i in range(I):
> number = myNumer[:]
> random.shuffle(number)
> if number == myNumer:
> count+=1

Nice. Try 'em all, then count 'em.

Another wtfery would be a SQLAlchemy solution, generating dynamic 
queries, using only OUTER JOINs and COUNT(). Could be a way to justify 
hardware upgrades.


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


Re: A Python 3000 Question

2007-10-30 Thread Eduardo O. Padoan
On 10/29/07, brad <[EMAIL PROTECTED]> wrote:
> Will len(a_string) become a_string.len()? I was just reading
>
> http://docs.python.org/dev/3.0/whatsnew/3.0.html
>
> One of the criticisms of Python compared to other OO languages is that
> it isn't OO enough or as OO as others or that it is inconsistent. And
> little things such as this seem to support those arguments. Not that it
> matters really... just seems that classes with methods used in a more
> consistent manner would be more appropriate in an OO langauage. Is there
> a reason that len cannot be a method?
>
> a_string.lower() makes sense, as does a_string.split(),
> a_string.strip()... why not a_string.len()?

This is a FAQ:
http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm


-- 
http://www.advogato.org/person/eopadoan/
Bookmarks: http://del.icio.us/edcrypt
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Python 3000 Question

2007-10-30 Thread Dustan
On Oct 29, 7:59 pm, Wildemar Wildenburger
<[EMAIL PROTECTED]> wrote:
> Bjoern Schliessmann wrote:
> > The inconsistencies arise, IMHO, if an OO language introduces
> > non-object types for performance reasons, after that gets wrapper
> > classes to wrap those primitives, and even later gets the ability
> > to automatically cast a primitive into a wrapper class instance.
> > That's just ugly.
>
> If you mean Java, then just say Java.

There was no need to; it was heavily implied.

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


Re: Need some help...

2007-10-30 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
> I want to create a program that I type in a word.
> 
> for example...
> 
> chaos
> 
> each letter equals a number
> 
> A=1
> B=20
> 
>  and so on.
> 
> So Chaos would be
> 
> C=13 H=4 A=1 O=7 S=5
> 
> I want to then have those numbers
> 13+4+1+7+5 added together to be 30.
> 
> How can I do that?
> 
> Also, just curious, but, how could I then have the 3 and 0 added
> together to be 3?
> 
> Please help me out.
> 
> Thank you.
> 

 >>> sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS')
30
 >>> sum(eval(ch) for ch in str(_))
3
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Automatic Generation of Python Class Files

2007-10-30 Thread Chris Mellon
On Oct 30, 2007 5:52 AM, Fuzzyman <[EMAIL PROTECTED]> wrote:
> On Oct 29, 11:35 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
> > Fuzzyman wrote:
> > > On Oct 22, 6:43 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
> > >> # Inherit from object. There's no reason to create old-style classes.
> >
> > > We recently had to change an object pipeline from new style classes to
> > > old style. A lot of these objects were being created and the *extra
> > > overhead* of new style classes was killing us. :-)
> >
> > I'm curious.  Was it memory or speed overhead that was the problem?
>
>
> It was speed overhead - I have to add a disclaimer that this is
> IronPython, but my understanding is that the situation is similar with
> CPython. Creating new style class instances is slower than for old
> style classes.
>

The obvious timeit test shows new-style classes being created in half
the time of old style ones. I certainly would not generalize to
CPython from IronPythons performance characteristics, especially with
something that's so dependent on both the .NET runtime and on the
details of IronPython integration as object creation.

C:\>python -m timeit -s "class C: pass" "c = C()"
100 loops, best of 3: 0.315 usec per loop

C:\>python -m timeit -s "class C(object): pass" "c = C()"
1000 loops, best of 3: 0.175 usec per loop
-- 
http://mail.python.org/mailman/listinfo/python-list


redundancy_check

2007-10-30 Thread Beema shafreen
hi everbody,
I have a file,
 a b  c
1454VALTGLTVAEYFR8.9954e-07
1454VALTGLTVAEYFR0.00404626
1498STLTDSLVSK0.00404626
1505TIAMDGTEGLVR1.50931e-05
1528GAEISAILEER0.00055542
1528GAEISAILEER0.00055542
1538YPIEHGIITNWDDMEK0.0180397
1540YPIEHGIITNWDDMEK3.69329e-05
1552AQIVGGFPIDISEAPYQISLR0.015136


The file has redundancy in lines ,  I have to print the line without
redundancy on consideration to the column c of the two lines which are
redundant and those that are having column c  lesser value than the other.
how do i do it.


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

Re: Iteration for Factorials

2007-10-30 Thread Boris Borcic
Py-Fun wrote:
> I'm stuck trying to write a function that generates a factorial of a
> number using iteration and not recursion.  Any simple ideas would be
> appreciated.
> 

fact = lambda n : len(map([1].__imul__,range(1,n+1))[0])

hth :)

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


Re: Iteration for Factorials

2007-10-30 Thread auzaar
On Oct 30, 3:30 pm, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> Anurag <[EMAIL PROTECTED]> wrote:
> >  What about this no map, reduce, mutiplication or even addition
> >  Its truly interative and You will need to interate till infinity if
> >  you want correct answer ;)
>
> >  deffactorial(N):
> >  """
> >  Increase I ...and go on increasing...
> >  """
> >  import random
>
> >  myNumer = range(N)
> >  count = 0
> >  I = 1 #10**(N+1)
> >  for i in range(I):
> >  bucket = range(N)
> >  number = []
> >  for i in range(N):
> >  k = bucket[ random.randrange(0,len(bucket))]
> >  bucket.remove(k)
> >  number.append(k)
>
> >  if number == myNumer:
> >  count+=1
>
> >  return int(I*1.0/count+.5)
>
> ;-)
>
> Note you can write your middle loop as
>
> for i in range(I):
> number = myNumer[:]
> random.shuffle(number)
> if number == myNumer:
> count+=1
>
> --
> Nick Craig-Wood <[EMAIL PROTECTED]> --http://www.craig-wood.com/nick- Hide 
> quoted text -
>
> - Show quoted text -

good :) i thinkif go on improving this we will have worlds' best
useless factorial function.

actually number = myNumer[:] can be moved out of the loop.

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


Readline and record separator

2007-10-30 Thread Johny
Is it possible to change record separator when using readline?
As far as I know readline reads characters until found '\n' and it is
the end of record for readline.
My problem is that my record consits several '\n' and when I use
readline it does NOT read the whole my record.
So If I could change '\n' as  a record separator for readline, it
would solve my problem.
Any idea?
Thank you
L.

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


Re: appending into a list

2007-10-30 Thread c james
Beema shafreen wrote:
>   2721520  2721569A_16_P21360235199-49
>   2721768  2721821A_16_P03641971139-53
>   2721960  2722004A_16_P21360237312-44
> I need to append the column D and E into a list:
> in such a way that the list should have 
> [D,E,D,E,D,E]
> How do i do it.
> 
> regards
> shafreen

Without a header, you could use something like

data = [x.split()[-2:] for x in open(filename).readlines()]

With header

f = open(filename)
f.readline()
data = [x.split()[-2:] for x in f.readlines()]


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


Re: appending into a list; dictionary and list

2007-10-30 Thread Tim Chase
>A B  C D   E
[snipped yet another column of random data]
> I need to append the column D and E into a list:
> in such a way that the list should have
> [D,E,D,E,D,E]
> How do i do it.

You start by writing some code[1].  I recommend Python, as it's a 
wonderful language, easy to learn, easy to read, has lots of 
example code, and the folks on this mailing list are ever so 
helpful (as shown by answering your last umpteen questions for 
which you seem to have not demonstrated a whit of effort towards 
solving yourself).  However, as you're doing lots of text 
manipulations, I've heard Perl and Awk are also good at that sort 
of thing[2].

Then once you've written your code, if you have problems with it, 
you ask questions here on the list.  Post the germane snippet of 
code that isn't working quite the way you expected, along with a 
detailed description of the problem.  Perhaps, if you get an 
exception traceback, you include the whole traceback.[3]

-tkc

[1] Writing code is a difficult thing to do and success may be 
limited to people with an aptitude for the thought process.  If 
programming confounds you, you may want to read any of the 
readily available texts on how to program[4], take a class on the 
topic, or you may need to hire somebody to write the code for you.

[2]  I occasionally do Awk, but try to avoid Perl to the best of 
my abilities.

[3] http://catb.org/~esr/faqs/smart-questions.html

[4] Resources include:
http://docs.python.org/
http://diveintopython.org/toc/index.html
http://aspn.activestate.com/ASPN/Cookbook/Python
http://gnosis.cx/TPiP/
http://www.handysoftware.com/cpif/
http://ppython.com/
http://www.google.com/search?q=learn%20python
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Readline and record separator

2007-10-30 Thread Jeff
If it's a short file you could slurp the entire file and then split it
however you like using regular expressions.

I'm not sure if you can alter it, but os.linesp holds the value that
is accessed when file.readlines() splits lines.  Conceivably, if it
were set to 'FOO', 'FOO' would be used to determine the EOL string.

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


Proxying downloads

2007-10-30 Thread Martin Marcher
Hello,

more a recipe question. I'm working on a proxy that will download a
file for a client. The thing that doesn't yield problems is:

Alice (Client)
Bob (Client)
Sam (Server)

1 Alice asks Sam for "foobar.iso"
2 Sam can't find "foobar.iso" in "cachedir"
3 Sam requests "foobar.iso" from the uplink
4 Sam now saves each chunk received to "cachedir/foobar.iso"
5 At the same time Sam forwards each chunk to Alice.

But I can't figure out how I would solve the following:

1 Alice asks Sam for "foobar.iso"
2 Sam can't find "foobar.iso" in "cachedir"
3 Sam requests "foobar.iso" from uplink
4 Sam saves and forwards to Alice
5 At about 30 % of the download Bob asks Sam for "foobar.iso"
6 How do I serve Bob now?

Now because the internal link is _a lot_ faster than the uplink Bob
will probably reach the end of (the local) "foobar.iso" before Sam has
received "foobar.iso" in total from uplink. So Bob will end up with a
incomplete file...

How do I solve that. The already downloaded data should of course be
served internally.

The solutions I think of are
 * Some kind of subscriber list for the file in question
  * That is serve internally and if the state of "foobar.iso" is in
progress switch to receiving chunk directly from Sam as it comes down
the link
  * How would I realize this switch from internal serving to pass thru
of chunks?

 * Send an acknowledge (lie to the client that we have this file in
the cache) wait until it's finished and then serve the file from the
internal cache)
  * This could lead to timeouts for very large files, at least I think so

 * Forget about all of it and just pass thru from uplink, with a new
request, as long as files are in progress. This would in the worst
case download the file n times where n is the number of clients.
  * I guess that's the easiest one but also the least desirable solution.

I hope I explained my problem somehow understandable.

any hints are welcome
thanks
martin

-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Readline and record separator

2007-10-30 Thread A.T.Hofkamp
On 2007-10-30, Johny <[EMAIL PROTECTED]> wrote:
> Is it possible to change record separator when using readline?
> As far as I know readline reads characters until found '\n' and it is
> the end of record for readline.
> My problem is that my record consits several '\n' and when I use
> readline it does NOT read the whole my record.
> So If I could change '\n' as  a record separator for readline, it
> would solve my problem.
> Any idea?

Read large enough blocks of data, then use block.find() (in the string module)
to find your delimiter, and split the block.

Albert

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


Re: Readline and record separator

2007-10-30 Thread clbr
On Oct 30, 12:21 pm, Johny <[EMAIL PROTECTED]> wrote:
> Is it possible to change record separator when using readline?
> As far as I know readline reads characters until found '\n' and it is
> the end of record for readline.
> My problem is that my record consits several '\n' and when I use
> readline it does NOT read the whole my record.
> So If I could change '\n' as  a record separator for readline, it
> would solve my problem.
> Any idea?
> Thank you
> L.

I'm not aware any such a method. But what you could do is simply read
all of them(readlines()) and then split it(delimeter would be your new
line)

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


Re: Proxying downloads

2007-10-30 Thread Jeff
You use a temp directory to store the file while downloading, then
move it to the cache so the addition of the complete file is atomic.
The file name of the temp file should be checked to validate that you
don't overwrite another process' download.

Currently downloading urls should be registered with the server
process (a simple list or set would work).  New requests should be
checked against that; if there is a matching url in there, the process
must wait until that download is finished and that file should be
delivered to both Alice and Bob.

You need to store the local file path and the url it was downloaded
from and checking against that when a request is made; there might be
two foobar.iso files on the Internet or the network, and they may be
different (such as in differently versioned directories).

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


Re: A Python 3000 Question

2007-10-30 Thread brad
Eduardo O. Padoan wrote:

> This is a FAQ:
> http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm

Thanks to all for the feedback. I'm no language designer. I just see and 
hear these criticisms and I wanted to think through it a bit by posting 
here. I now better understand generic functions and why they are used in 
some cases.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parse text file

2007-10-30 Thread Jeff
You can also use strip() if it's the same possibilities every time:

line_of_text.lstrip('http://mail.python.org/mailman/listinfo/python-list


Re: python in academics?

2007-10-30 Thread Jeff
Yes, Python is used in many CS programs.  In fact, I read that Guido
van Rossum often polls profs about their needs when thinking about new
features and the direction of the language.

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


۩۞۩๑█ TAMIL SEX FREE LIVE๑۩۞۩๑█

2007-10-30 Thread [EMAIL PROTECTED]
๑۩۞۩๑█ TAMIL  SEX  FREE  LIVE๑۩۞۩๑█

NOTBIOTECHNOLOGEY ONLY  SEX

FREE  SEX  LIVE  SHOW  FREE

ROMANCE  SEX  LIVE  INDIAN  SEX


๑۩۞۩๑█ TAMIL  SEX  FREE  LIVE๑۩۞۩๑█



   http://TAMIL-GIRLS-SEX-STILL.notlong.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: python in academics?

2007-10-30 Thread kyosohma
On Oct 29, 10:39 pm, sandipm <[EMAIL PROTECTED]> wrote:
> seeing posts from students on group. I am curious to know, Do they
> teach python in academic courses in universities?
>
> in undergrad comp science courses,  We had scheme language as scheme
> is neat and beautiful language to learn programming. We learnt other
> languages ourselve with basics set right by scheme..
>
> sandip

They didn't at either of the colleges I went to. They seemed to be
focused on C++, COBOL and Visual Basic. All are used all over the
place, but only Visual Basic is easy for complete newbs. I hope more
colleges adopt Python or Ruby as a teaching language, but I don't
think it's a good idea to ignore COBOL or C++ since their used so
extensively in big business.

Mike

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


Re: Iteration for Factorials

2007-10-30 Thread J. Clifford Dyer
On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding Re: 
Iteration for Factorials:
> 
> Py-Fun wrote:
> > I'm stuck trying to write a function that generates a factorial of a
> > number using iteration and not recursion.  Any simple ideas would be
> > appreciated.
> > 
> 
> fact = lambda n : len(map([1].__imul__,range(1,n+1))[0])
> 
> hth :)
> 

Nice one.  I was trying to grok it, and started out by breaking it down:

>>> [1].__imul__(2)
[1, 1]
>>> map([1].__imul__,range(1,3))
[[1, 1], [1, 1]]

So far so good, but I tried to break it down a little more:

>>> [1].__imul__(1), [1].__imul__(2), [1].__imul__(3)
([1], [1, 1], [1, 1, 1])

Hmm.  Wasn't what I was expecting.

Then it hit me:

>>> L = [1]
>>> L.__imul__(1), L.__imul__(2), L.__imul__(3)
([1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1])

Pretty sneaky, sis.

Cheers,
Cliff

P.S.  Regards to those who lack a grounding in American pop-culture, or who are 
to young to remember the origins of "Pretty sneaky, sis."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Readline and record separator

2007-10-30 Thread George Sakkis
On Oct 30, 8:21 am, Johny <[EMAIL PROTECTED]> wrote:
> Is it possible to change record separator when using readline?
> As far as I know readline reads characters until found '\n' and it is
> the end of record for readline.
> My problem is that my record consits several '\n' and when I use
> readline it does NOT read the whole my record.
> So If I could change '\n' as  a record separator for readline, it
> would solve my problem.
> Any idea?
> Thank you
> L.

Check out this recipe, it's pretty generic:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877.

George

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


Re: python in academics?

2007-10-30 Thread BartlebyScrivener
On Oct 29, 10:39 pm, sandipm <[EMAIL PROTECTED]> wrote:
> seeing posts from students on group. I am curious to know, Do they
> teach python in academic courses in universities?

This came up a while back. See:

http://tinyurl.com/2pjjua

If that doesn't work, search the Google group for "Python taught in
schools"

rd

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


Re: getting serialized data into and out of a database

2007-10-30 Thread Michael Pelz Sherman
THANK YOU! I needed to use tostring() in this case but the key was realizing 
what kind of data I was dealing with.

Gabriel Genellina <[EMAIL PROTECTED]> wrote: En Mon, 29 Oct 2007 19:07:18 
-0300, Michael Pelz Sherman  
 escribió:

> I'm having a devil of a time getting serialized data into and out of a  
> database (MySQL in this case) using python and MySQLdb.
>
> I have some C code that has its own serialization/deserialization  
> functions, which we've wrapped using SWIG.
>
> I am able to save the serialized C structs to disk but when I try to  
> write the exact same data to MySQL and pull it back out, I'm getting  
> some strange results. The data comes back looking like this:
>
> array('c', '\x01r\x01\x00\x...)
>
> Is this a python buffer, or what? How can I access the data in there?  
> I've tried using [1] but that doesn't seem to work.

It's an array of characters 
You can write it to disk again using its tofile() method

-- 
Gabriel Genellina

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

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

Re: python2.5 and mysqldb

2007-10-30 Thread BartlebyScrivener
On Oct 29, 2:30 pm, brad <[EMAIL PROTECTED]> wrote:

> or get a
> more flexible OS that easily allows for this sort of thing (like Debian)

Second that. Etch came with 2.3 and 2.4, and I added 2.5 and they
never bother each other.

rd


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


Re: coverage.py: "Statement coverage is the weakest measure of code coverage"

2007-10-30 Thread Ned Batchelder
I don't know how to extend coverage.py to do more extensive checking,
but I know it would be both difficult and fascinating.  To help spur
some thought, I've sketched out some problems with statement coverage:
http://nedbatchelder.com/blog/20071030T084100.html

--Ned.

On Oct 28, 6:56 pm, Ben Finney <[EMAIL PROTECTED]> wrote:
> Howdy all,
>
> Ned Batchelder has been maintaining the nice simple tool 'coverage.py'
> http://nedbatchelder.com/code/modules/coverage.html> for
> measuring unit test coverage.
>
> On the same site, Ned includes documentation
> http://nedbatchelder.com/code/modules/rees-coverage.html> by the
> previous author, Gareth Rees, who says in the "Limitations" section:
>
> Statement coverage is the weakest measure of code coverage. It
> can't tell you when an if statement is missing an else clause
> ("branch coverage"); when a condition is only tested in one
> direction ("condition coverage"); when a loop is always taken and
> never skipped ("loop coverage"); and so on. See [Kaner 2000-10-17]
> http://www.kaner.com/pnsqc.html> for a summary of test
> coverage measures.
>
> So, measuring "coverage of executed statements" reports complete
> coverage incorrectly for an inline branch like 'foo if bar else baz',
> or a 'while' statement, or a 'lambda' statement. The coverage is
> reported complete if these statements are executed at all, but no
> check is done for the 'else' clause, or the "no iterations" case, or
> the actual code inside the lambda expression.
>
> What approach could we take to improve 'coverage.py' such that it
> *can* instrument and report on all branches within the written code
> module, including those hidden inside multi-part statements?
>
> --
>  \"Technology is neither good nor bad; nor is it neutral." |
>   `\   -Melvin Kranzberg's First Law of Technology |
> _o__)  |
> Ben Finney


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


Re: Proxying downloads

2007-10-30 Thread Martin Sand Christensen
> But I can't figure out how I would solve the following:
>
> 1 Alice asks Sam for "foobar.iso"
> 2 Sam can't find "foobar.iso" in "cachedir"
> 3 Sam requests "foobar.iso" from uplink
> 4 Sam saves and forwards to Alice
> 5 At about 30 % of the download Bob asks Sam for "foobar.iso"
> 6 How do I serve Bob now?

Let every file in your download cache be represented by a Python object.
Instead of streaming the file directly to the clients, you can stream
the objects. The object will know if the file it represents has finished
downloading or not, where the file is located etc. This way you can
also, for the sake of persistence, keep partially downloaded files
separate from the completely downloaded files, as per a previous
suggestion, so that you won't start serving half files after a crash,
and it'll be completely transparent in all code except for your proxy
file objects.

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


Re: A Python 3000 Question

2007-10-30 Thread Steven D'Aprano
On Tue, 30 Oct 2007 00:11:58 +, Marc 'BlackJack' Rintsch wrote:

>>> And to answer the question. In OO programming generic functions are no
>>> less important than classes and objects.
>> 
>> Do they not take away from the OOness of the overall language and
>> introduce inconsistencies?
> 
> No not at all.  Why do you think so?

I disagree. I think they *do* take away from the overall Object-Oriented 
nature of the language, and that is A Very Good Thing Indeed.

OO is a tool, and like any tool, it has it's uses and misuses. Some 
things are best written as objects, some as imperative procedures, some 
as functions. As you say:

> There are things that are best expressed as functions.

Agreed. It is a *good thing* that Python doesn't try to be 100% 
functional, or 100% Object Oriented, or 100% procedural.

(Aside: I think it a shame that there is one major paradigm that Python 
doesn't have *any* support for at all: logic programming, like Prolog. I 
don't quite know what it is good for, but I'd like to find out!)


> Other allegedly more OO languages have them
> too, but you need to stuff them as static methods into classes or even
> uglier you see code like ``Spam().spammify(eggs)`` instead of a plain
> function call.


I'm reminded of a very famous proverb from the Kingdom of the Nouns:

For the lack of a nail,
throw new HorseshoeNailNotFoundException("no nails!");

For the lack of a horseshoe,
EquestrianDoctor.getLocalInstance().getHorseDispatcher().shoot();

For the lack of a horse,
RidersGuild.getRiderNotificationSubscriberList().getBroadcaster().run(
  new BroadcastMessage(StableFactory.getNullHorseInstance()));

For the rest of the proverb, which is well worth reading, you'll have to 
see here:


http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html



-- 
Steven.
(no, not that Steve in the URL)
-- 
http://mail.python.org/mailman/listinfo/python-list


Hide comments in emacs python mode?

2007-10-30 Thread Charles Fox
Hi guys,

I'm playing with Python in emacs, with python mode.

I'd like to be able to press a key to toggle the code comments on and
off -- to switch between beautiful clean Python code, and the full
text that tells me what's going in in English.

Is this currently possible?  I know there is a hide/show mode in
emacs, it would need to be set to hide (1) whole lines that start with
#, (2) parts of lines after the '#' for comments after code.  Has
anyone already written this?

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


Earn Up To 100's of $ per Day with Ease!

2007-10-30 Thread jhon
Tired of business opportunities that do not deliver what they promise?

Get Free Advice & a Honest Review on Internet Opportunities that Work!

MOre details http://powerfulmoneymakingideas.blogspot.com/

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


logic programming in python (was something about py3k)

2007-10-30 Thread Jean-Paul Calderone
On Tue, 30 Oct 2007 14:09:39 -, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>
> [snip]
>
>(Aside: I think it a shame that there is one major paradigm that Python
>doesn't have *any* support for at all: logic programming, like Prolog. I
>don't quite know what it is good for, but I'd like to find out!)
>

If you have some time to experiment, PyPy has some support for logic
programming with Python.

http://codespeak.net/pypy/dist/pypy/doc/objspace-proxies.html#the-logic-object-space

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


Re: Readline and record separator

2007-10-30 Thread BartlebyScrivener
On Oct 30, 7:21 am, Johny <[EMAIL PROTECTED]> wrote:
> My problem is that my record consits several '\n' and when I use
> readline it does NOT read the whole my record.
> So If I could change '\n' as  a record separator for readline, it
> would solve my problem.

Python Cookbook (great book!) 2nd Ed pg. 717: "Iterating on a Stream
of Data Blocks as a Stream of Lines."

Allows you to specify both eol for source and output file.

rd

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


Re: Event for multithread help advice

2007-10-30 Thread Aahz
In article <[EMAIL PROTECTED]>,
JoeSox  <[EMAIL PROTECTED]> wrote:
>
>I have two threads going
>class guiThread(threading.Thread)
>class mainThread(threading.Thread)
>
>Within the guiThread, I have an instance of class GUIFramework(Frame)
>in this Tkinter instance I have a ListBox.
>
>The second thread, mainThread, has an instance of a custom class the
>will need to send out text or other objects to the gui.
>
>What is the best or easiest way to send, let's say text, from
>mainThread to the guiThread ListBox?
>
>Should I use a custom Event class, pubsub, or Queue?

Well, I'd recommend a Queue, but that's partly because I have an example
already made up:
http://www.pythoncraft.com/OSCON2001/FibThreaded.py
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Typing is cheap.  Thinking is expensive."  --Roy Smith
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help ctypes on arm linux not compile

2007-10-30 Thread Samuel M. Smith
Sorry, thats a typo. Its python 2.5.1. as the error messages indicate.

On 30 Oct 2007, at 02:55 , Thomas Heller wrote:

> Samuel M. Smith schrieb:
>> I have built python 1.5.1 from source for an embedded ARM9 debian
>> linux Sarge distribution but
>> ctypes doesn't build.  Anybody have any idea what the problem is? Do
>> I have to have the libffi package
>> installed.
>> See my errors below.
>
> ctypes won't work with Python 1.5 because it uses new style  
> classes, introduced in Python 2.2.
> It uses other, newer features additionally, so it requires Python  
> 2.3 at least.
>
> Then, the included libffi package doesn't support ARM, you need a  
> newer libffi
> version.
>
> I think that the current Python 2.5 sources, from SVN, should work.
>
> Thomas
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list

**
Samuel M. Smith Ph.D.
2966 Fort Hill Road
Eagle Mountain, Utah 84005-4108
801-768-2768 voice
801-768-2769 fax
**
"The greatest source of failure and unhappiness in the world is
giving up what we want most for what we want at the moment"
**


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


Re: Iteration for Factorials

2007-10-30 Thread J. Clifford Dyer
On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding Re: 
Iteration for Factorials:
> 
> Py-Fun wrote:
> > I'm stuck trying to write a function that generates a factorial of a
> > number using iteration and not recursion.  Any simple ideas would be
> > appreciated.
> > 
> 
> fact = lambda n : len(map([1].__imul__,range(1,n+1))[0])
> 

OK.  Now I've been sucked in.  How about this:

def fact(x):
def f(x):
if int(x) != x:
raise ValueError
elif x > 1:
return f(x-1) ** x
elif x == 1:
return 10
else:
raise ValueError
return len(str(f(x))) -1

The great part about this recursive solution is that you don't have to worry 
about the stack limit because performance degrades so quickly on the conversion 
to string!  fact(8) takes a little less than a second, fact(9) takes about a 
minute, and fact(10) takes more time than I had patience to wait for!

Cheers,
Cliff

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


SQLObject 0.8.6

2007-10-30 Thread Oleg Broytmann
Hello!

I'm pleased to announce the 0.8.6 release of SQLObject.


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and
Firebird.  It also has newly added support for Sybase, MSSQL and MaxDB (also
known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.8.6

News and changes:
http://sqlobject.org/News.html


What's New
==

News since 0.8.5


Bug Fixes
~

* Remove 'limit' from SelectResults after setting start/end so .clone()
  never sees limit again.

* Fixed a bug in sqlbuilder._LikeQuoted() - call sqlrepr() on the
  expression to escape single quotes if the expression is a string.

* Fixed StringCol and UnicodeCol: use sqlType with MSSQL.

* Fixed startswith/endswith/contains for UnicodeCol.

Other Changes
~

* Removed SelectResults.__nonzero__, which was a design mistake. Raising an
  exception in __nonzero__() is inconsistent with other iterators
  (bool(iter([])) => True).

* Changed the default value for 'varchar' in BLOBColumns from 'auto' to False
  (so that the default type for the columns in  MySQL is BLOB, not TEXT).

* Changed the implementation type in BoolCol under MySQL from TINYINT to
  BOOL (which is a synonym for TINYINT(1)).

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
 Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED]
   Programmers don't die, they just GOSUB without RETURN.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Python 3000 Question

2007-10-30 Thread Neil Cerutti
On 2007-10-30, Eduardo O. Padoan <[EMAIL PROTECTED]> wrote:
> This is a FAQ:
> http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm

Holy Airy Persiflage Batman!

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('len(seq)', 'seq = range(100)').timeit()
0.20332271187463391
>>> timeit.Timer('seq.__len__()', 'seq = range(100)').timeit()
0.48545737364457864

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


Re: setting variables in outer functions

2007-10-30 Thread Neil Cerutti
On 2007-10-29, Steven Bethard <[EMAIL PROTECTED]> wrote:
> Hrvoje Niksic wrote:
>> Tommy Nordgren <[EMAIL PROTECTED]> writes:
>> 
>>> Given the following:
>>> def outer(arg)
>>>  avar = ''
>>>  def inner1(arg2)
>>>   # How can I set 'avar' here ?
>> 
>> I don't think you can, until Python 3:
>> http://www.python.org/dev/peps/pep-3104/
>
> But it definitely does work in Python 3 if you use 'nonlocal'::
>
>  Python 3.0a1+ (py3k:58681, Oct 26 2007, 19:44:30) [MSC v.1310 32 bit
>  (Intel)] on win32
>  Type "help", "copyright", "credits" or "license" for more
>  information.
>  >>> def f():
>  ... x = 1
>  ... def g():
>  ... nonlocal x
>  ... x = 2
>  ... print(x)
>  ... g()
>  ... print(x)
>  ...
>  >>> f()
>  1
>  2
>
> That said, I'd like to see the reason you think you want to do
> this.

It's allows a standard programming idiom which provides a
primitive form of object oriented programming using closures to
represent state.

def account(opening_balance):
  balance = opening_balance
  def get_balance():
nonlocal balance
return balance
  def post_transaction(x):
nonlocal balance
balance += x
  return balance, post_transaction

fred_balance, fred_post = account(1500)
joe_balance, joe_post = account(12)
fred_post(20)
joe_post(-10)
fred_balance()
1520
joe_balance()
2

Python classes will of course nearly always win, though the idiom
looks like it might be faster (I don't have Python 3000 to try it
out).

-- 
Neil Cerutti
It isn't pollution that is hurting the environment; it's the impurities in our
air and water that are doing it. --Dan Quayle
-- 
http://mail.python.org/mailman/listinfo/python-list


SQLObject 0.9.2

2007-10-30 Thread Oleg Broytmann
Hello!

I'm pleased to announce the 0.9.2 release of SQLObject.


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and
Firebird.  It also has newly added support for Sybase, MSSQL and MaxDB (also
known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.9.2

News and changes:
http://sqlobject.org/News.html


What's New
==

News since 0.9.1


Bug Fixes
~

* Remove 'limit' from SelectResults after setting start/end so .clone()
  never sees limit again.

* Fixed a bug in sqlbuilder._LikeQuoted() - call sqlrepr() on the
  expression to escape single quotes if the expression is a string.

* Fixed a bug in Versioning - do not copy "alternateID" and "unique"
  attributes from the versioned table.

* Fixed a misspelled 'zerofill' option's name.

* Fixed StringCol and UnicodeCol: use sqlType with MSSQL.

* Fixed startswith/endswith/contains for UnicodeCol.

* Fixed bugs in SQLiteConnection.guessColumn().

Other Changes
~

* Removed SelectResults.__nonzero__, which was a design mistake. Raising an
  exception in __nonzero__() is inconsistent with other iterators
  (bool(iter([])) => True).

* Changed the default value for 'varchar' in BLOBColumns from 'auto' to False
  (so that the default type for the columns in  MySQL is BLOB, not TEXT).

* Changed the implementation type in BoolCol under MySQL from TINYINT to
  BOOL (which is a synonym for TINYINT(1)).

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
 Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED]
   Programmers don't die, they just GOSUB without RETURN.
-- 
http://mail.python.org/mailman/listinfo/python-list


SQLObject 0.7.9

2007-10-30 Thread Oleg Broytmann
Hello!

I'm pleased to announce the 0.7.9 release of SQLObject.

What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and
Firebird.  It also has newly added support for Sybase, MSSQL and MaxDB (also
known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.7.9

News and changes:
http://sqlobject.org/docs/News.html


What's New
==

News since 0.7.8


Bug Fixes
~

* Remove 'limit' from SelectResults after setting start/end so .clone()
  never sees limit again.

* Fixed a bug in sqlbuilder._LikeQuoted() - call sqlrepr() on the
  expression to escape single quotes if the expression is a string.

* Fixed StringCol and UnicodeCol: use sqlType with MSSQL.

* Fixed startswith/endswith/contains for UnicodeCol.

Other Changes
~

* Changed the default value for 'varchar' in BLOBColumns from 'auto' to False
  (so that the default type for the columns in  MySQL is BLOB, not TEXT).

* Changed the implementation type in BoolCol under MySQL from TINYINT to
  BOOL (which is a synonym for TINYINT(1)).

For a more complete list, please see the news:
http://sqlobject.org/docs/News.html

Oleg.
-- 
 Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED]
   Programmers don't die, they just GOSUB without RETURN.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Python 3000 Question

2007-10-30 Thread Jean-Paul Calderone
On Tue, 30 Oct 2007 15:25:54 GMT, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>On 2007-10-30, Eduardo O. Padoan <[EMAIL PROTECTED]> wrote:
>> This is a FAQ:
>> http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm
>
>Holy Airy Persiflage Batman!
>
>Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on
>win32
>Type "help", "copyright", "credits" or "license" for more information.
 import timeit
 timeit.Timer('len(seq)', 'seq = range(100)').timeit()
>0.20332271187463391
 timeit.Timer('seq.__len__()', 'seq = range(100)').timeit()
>0.48545737364457864
>

Not sure what you're trying to demonstrate.  Here's another pointless
transcript, though:

[EMAIL PROTECTED]:~$ python -m timeit -s '
seq = range(100)
' 'len(seq)'
100 loops, best of 3: 0.211 usec per loop
[EMAIL PROTECTED]:~$ python -m timeit -s '
seq = range(100)
' 'seq.__len__()'
100 loops, best of 3: 0.317 usec per loop
[EMAIL PROTECTED]:~$ python -m timeit -s '
class X(object):
  def __len__(self): return 100
seq = X()
' 'seq.__len__()'
100 loops, best of 3: 0.427 usec per loop
[EMAIL PROTECTED]:~$ python -m timeit -s '
class X(object):
  def __len__(self): return 100
seq = X()
' 'len(seq)'
100 loops, best of 3: 0.701 usec per loop
[EMAIL PROTECTED]:~$

I guess we've learned that sometimes something is faster than something
else, and other times the contrary.

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


Re: setting variables in outer functions

2007-10-30 Thread Steven Bethard
Neil Cerutti wrote:
> On 2007-10-29, Steven Bethard <[EMAIL PROTECTED]> wrote:
>> Hrvoje Niksic wrote:
>>> Tommy Nordgren <[EMAIL PROTECTED]> writes:
>>>
 Given the following:
 def outer(arg)
  avar = ''
  def inner1(arg2)
   # How can I set 'avar' here ?
>>> I don't think you can, until Python 3:
>>> http://www.python.org/dev/peps/pep-3104/
>> But it definitely does work in Python 3 if you use 'nonlocal'::
>>
>>  Python 3.0a1+ (py3k:58681, Oct 26 2007, 19:44:30) [MSC v.1310 32 bit
>>  (Intel)] on win32
>>  Type "help", "copyright", "credits" or "license" for more
>>  information.
>>  >>> def f():
>>  ... x = 1
>>  ... def g():
>>  ... nonlocal x
>>  ... x = 2
>>  ... print(x)
>>  ... g()
>>  ... print(x)
>>  ...
>>  >>> f()
>>  1
>>  2
>>
>> That said, I'd like to see the reason you think you want to do
>> this.
> 
> It's allows a standard programming idiom which provides a
> primitive form of object oriented programming using closures to
> represent state.

Yeah, that's what I was afraid of. ;-)

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


Re: A Python 3000 Question

2007-10-30 Thread George Sakkis
On Oct 30, 11:25 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-10-30, Eduardo O. Padoan <[EMAIL PROTECTED]> wrote:
>
> > This is a FAQ:
> >http://effbot.org/pyfaq/why-does-python-use-methods-for-some-function...
>
> Holy Airy Persiflage Batman!
>
> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] 
> on
> win32
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> import timeit
> >>> timeit.Timer('len(seq)', 'seq = range(100)').timeit()
> 0.20332271187463391
> >>> timeit.Timer('seq.__len__()', 'seq = range(100)').timeit()
>
> 0.48545737364457864

Common mistake; try this instead:

timeit.Timer('seqlen()',
 'seq = range(100); seqlen=seq.__len__').timeit()

George

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


Re: A Python 3000 Question

2007-10-30 Thread Paul Boddie
On 30 Okt, 15:09, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
>

[Language "OOness", hand-waving]

> I disagree. I think they *do* take away from the overall Object-Oriented
> nature of the language, and that is A Very Good Thing Indeed.

But everything is an object in Python: nothing has been taken
away. ;-) Anyway, I don't sympathise with the "methods for everything"
mentality, either, but there's a reason for Java doing things this way
- for Python, in fact, you actually get something extra over and above
Java's implementation of object-orientation.

[...]

> http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns...

As always, a pinch of salt is required when reading the works of
certain commentators (or skimming them, for those making slightly
better use of their time). Some choice words sum up the attitude we
see in works like this:

http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html#c114516329036008490

Thankfully, various decisions in the design of Python and its built-in
types and functions let us leave such squabbles to eat up the time of
the Ruby and Java fanboys.

Paul

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


Re: setting variables in outer functions

2007-10-30 Thread Duncan Booth
Neil Cerutti <[EMAIL PROTECTED]> wrote:

> It's allows a standard programming idiom which provides a
> primitive form of object oriented programming using closures to
> represent state.
> 
> def account(opening_balance):
>   balance = opening_balance
>   def get_balance():
> nonlocal balance
> return balance
>   def post_transaction(x):
> nonlocal balance
> balance += x
>   return balance, post_transaction
> 
> fred_balance, fred_post = account(1500)
> joe_balance, joe_post = account(12)
> fred_post(20)
> joe_post(-10)
> fred_balance()
TypeError: 'int' object is not callable

> 1520
> joe_balance()
TypeError: 'int' object is not callable

> 2
> 
> Python classes will of course nearly always win, though the idiom
> looks like it might be faster (I don't have Python 3000 to try it
> out).

Python classes might be less error prone. I expect they could also be 
faster: accessing non-local variables (whether fetching or setting) has 
always been suprisingly slow in Python 2.x.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: statvfs

2007-10-30 Thread Korthrun
At 2007-10-29, [EMAIL PROTECTED] expressed thier undying love for me by saying:
> On Mon, 29 Oct 2007 16:52:12 -0500, Korthrun wrote:
>
>> I'm writing some scripts to populate RRD's, mainly for practicing python.
>> 
>> As such I've decided to play with statvfs in order to build disk
>> graphs. Here is what I have and what I get. What I'm curious about
>> here is the meaning of the "L" charcter, as that fubars math.
>
> The L means its a `long` literal, i.e. an integer value that can be
> arbitrary big.  Well its limited by memory of course.
>
> And it doesn't "fubar" math, the L just shows up in the string
> representation but you don't calculate with strings but numbers.
>
>> ###start code###
>> 
>> from os import statvfs, path
>> from statvfs import *
>> 
>> mps = [ '/', '/home', '/www', '/var', '/storage/backups',
>> '/storage/snd' ]
>> 
>> for fs in mps:
>>  data = statvfs(fs)
>>  print data
>> 
>> ###end code, start output###
>> (4096, 4096, 4883593L, 4045793L, 4045793L, 0L, 0L, 0L, 1024, 255)
>> (4096, 4096, 1220889L, 1114718L, 1114718L, 0L, 0L, 0L, 0, 255)
>> (4096, 4096, 19267346L, 18273138L, 18273138L, 0L, 0L, 0L, 0, 255)
>> (4096, 4096, 3662687L, 3492397L, 3492397L, 0L, 0L, 0L, 0, 255)
>> (4096, 4096, 3417702L, 2116063L, 2116063L, 0L, 0L, 0L, 0, 255)
>> (4096, 4096, 25885944L, 21799115L, 21799115L, 0L, 0L, 0L, 0, 255)
>> ###end output###
>> 
>> Ideally I'll just do some blocksize * number of blocks math to get
>> the % of used space.
>
> Just go ahead and do it:
>
> In [185]: stat = os.statvfs('/')
>
> In [186]: stat.f_bsize
> Out[186]: 4096
>
> In [187]: stat.f_blocks
> Out[187]: 2622526L
>
> In [188]: stat.f_bsize * stat.f_blocks
> Out[188]: 10741866496L
>
> Ciao,
>   Marc 'BlackJack' Rintsch
Thanks for the response, I'll have to play with it more, as I'm
obviously misunderstanding the error that I'm getting.
I didn't include the part of the script that did the math, as it
wasn't important to my base question.

I was getting TypeError: "sequence index must be integer", so I
thought the L was making python see it as a string.

Thanks for the insight

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


Python Instructor Needed for GIS Symposium in April 2008

2007-10-30 Thread Eric . Foster
I am involved with MAGIC  http://www.magicgis.org/   an organization to 
encourage GIS development, sharing, cooperation, etc. and educate 
practitioners in GIS.  We hold a symposium every two years in April (next 
is April 2008) and provide speakers and workshops in relevant GIS 
subjects. ESRI's ArcGIS software holds  the market majority and has 
embrace Python language as a preferred scripting, customization language.  
 One area we have trouble with for our symposium is  getting instructors 
for Python workshops.   The symposium is in Kansas City on April 20-24, 
2008 and the hands on computer based Python course would be held for 4 
hours on Sunday April 20th in the afternoon for about 30 beginner and 
intermediate programmers.   We would like some application to ArcGIS, but 
just basic Python language instruction is also needed.  The instructors 
and speakers as well as the planning committee are asked to volunteer to 
keep the cost down to symposium attendees.Would you be a good fit (or 
know anyone) as an instructor for this Introduction to Python language 
course?
The Symposium Steering Committee would like to get a commitment by Nov. 2, 
2008 in order to publish a preliminary program.   Sorry for the short 
notice, we thought we had an instructor but do not.   We need a short 1-2 
paragraph summary or outline of the workshop by the Nov 2, 2008 date, but 
will accept later considerations.   We are willing to help develop any 
materials needed.
Contact me by phone or email if you have questions or would like to 
volunteer.   Thanks.

Eric Foster, Senior Transportation Planner
MoDOT, 600 NE Colbern Rd. Lee's Summit, MO 64086
(816) 622-6330

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

Re: Solaris 10 + Sun Studio 12 Pyrhon 2.4.4 64-bit build problem

2007-10-30 Thread MrJean1
Building 64-bit Python 2.4.4 on Solaris 10 and SUC C/C++ using the
instructions from

  

worked just fine on Ultra 20 Opteron machine.  The test result summary
is below.

/Jean Brouwers


249 tests OK.
2 tests failed:
test_cmath test_pty
40 tests skipped:
test_aepack test_al test_applesingle test_bsddb test_bsddb185
test_bsddb3 test_bz2 test_cd test_cl test_codecmaps_cn
test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr
test_codecmaps_tw test_crypt test_curses test_dl test_gdbm test_gl
test_imageop test_imgfile test_linuxaudiodev test_macfs
test_macostools test_nis test_normalization test_ossaudiodev
test_pep277 test_plistlib test_rgbimg test_scriptpackages
test_socket_ssl test_socketserver test_tcl test_timeout
test_unicode_file test_urllib2net test_urllibnet test_winreg
test_winsound
5 skips unexpected on sunos5:
test_tcl test_bz2 test_crypt test_dl test_nis


plumb and tree wrote:
> I've been trying for days to build 64 bit python with Solaris 10 + Sun
> Studio 12.
>
> Can anyone helpl please.
>

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


Re: Solaris 10 + Sun Studio 12 Pyrhon 2.4.4 64-bit build problem

2007-10-30 Thread MrJean1
On final comment.  For 64-bit usage, Python 2.5.1 is the better
choice.

More on that here .

/Jean Brouwers


 On Oct 30, 10:15 am, MrJean1 <[EMAIL PROTECTED]> wrote:
> Building 64-bit Python 2.4.4 on Solaris 10 and SUC C/C++ using the
> instructions from
>
>    python.html>
>
> worked just fine on Ultra 20 Opteron machine.  The test result summary
> is below.
>
> /Jean Brouwers
>
> 
> 249 tests OK.
> 2 tests failed:
> test_cmath test_pty
> 40 tests skipped:
> test_aepack test_al test_applesingle test_bsddb test_bsddb185
> test_bsddb3 test_bz2 test_cd test_cl test_codecmaps_cn
> test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr
> test_codecmaps_tw test_crypt test_curses test_dl test_gdbm test_gl
> test_imageop test_imgfile test_linuxaudiodev test_macfs
> test_macostools test_nis test_normalization test_ossaudiodev
> test_pep277 test_plistlib test_rgbimg test_scriptpackages
> test_socket_ssl test_socketserver test_tcl test_timeout
> test_unicode_file test_urllib2net test_urllibnet test_winreg
> test_winsound
> 5 skips unexpected on sunos5:
> test_tcl test_bz2 test_crypt test_dl test_nis
>
> plumb and tree wrote:
> > I've been trying for days to build 64 bit python with Solaris 10 + Sun
> > Studio 12.
>
> > Can anyone helpl please.


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


Re: Built-in functions and keyword arguments

2007-10-30 Thread Duncan Booth
"J. Clifford Dyer" <[EMAIL PROTECTED]> wrote:

>> How do you interpret:
>> 
>> >>> help(__import__)
>> Help on built-in function __import__ in module __builtin__:
>> 
>> __import__(...)
>> __import__(name, globals={}, locals={}, fromlist=[], level=-1) ->
>> module
>> ...
>> >>> help(int)
>> Help on class int in module __builtin__:
>> 
>> class int(object)
>>  |  int(x[, base]) -> integer
>> ...
>> 
>> Can you find any case (other than a single parameter identified as 
>> 'object') where you can interpret the help string as telling you the
>> types of the parameters?
> 
> OK, good point.  Perhaps it's not so specific as the type, but
> certainly the use of name and x in the docstrings listed above only
> imply something about the character of the argument, not the name of
> the argument itself, which is what I was trying to get at.  Help
> documentation for keyword arguments usually shows the argument being
> used as a keyword, like the example from __import__ above. 

Usually, but not in the second example I gave:

>>> int(base=12, x='42')
50
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dictionary and list

2007-10-30 Thread Gerardo Herzig
Beema shafreen wrote:

>hi everbody,
>   I have a file,
> a b   c   d e
>  2722316  2722360A_16_P03641972150-44
>  2722510  2722554A_16_P2136023916-44
>  2722570  2722614A_16_P0364197344-44
>  2722658  2722702A_16_P415636692187-44
>  2724889  2724948A_16_P03641974738-59
>  2725686  2725745A_16_P03641975422-59
>  2726167  2726219A_16_P0364197688-52
>  2726307  2726366A_16_P415636772167-59
>  2728533  2728589A_16_P213602495819-56
>  2734408  2734467A_16_P21360257-14-59
>  2734453  2734509A_16_P03641977376-56
>  2734885  2734929A_16_P213602591987-44
>
>  
>
This intro looks exactly like the 10 previous post from you. You will 
have to leave some money here, man!
Try posting the result you get, and the result you want for a start. 
Dont make others do what you already did.

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


choose from a list

2007-10-30 Thread barronmo
I'm new to programming and even newer to Python and would be grateful
for some help on what has been a tough problem for me.  The project I
am working on is an electronic medical record using MySQL/Python.  I'm
currrently working on a module that looks up a patient's name based on
input from the user.

My goal is a lookup based on the first 2 or 3 letters of the patient's
last name.  The matching results would appear as numbered choices so
that the user would choose only a number to then access various parts
of the patient's record.  The results might look like this for user
input "smi":

1  387  John Smith
2  453  Jane Smith
3  975  Joe Smithton

Here is a copy of what I have so far, name_lookup.py:


import MySQLdb

def name_find(namefrag):

 conn = MySQLdb.connect(host = "localhost",
  user = "root",
  passwd = "n85",
  db = "meds")
 cursor = conn.cursor(MySQLdb.cursors.DictCursor)
 cursor.execute("SELECT patient_ID, firstname, lastname FROM
demographics WHERE lastname LIKE '"+ str(namefrag)+"%'")
 results = cursor.fetchall()
 for row in results:
  print "%s   %s %s  %s" % (row["patient_ID"],
row["firstname"], row["lastname"])

 cursor.close()
 conn.close()


Thanks in advance for any help.

Mike

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


Python Interview Questions

2007-10-30 Thread Krypto
Hi,

I have used Python for a couple of projects last year and I found it
extremely useful. I could write two middle size projects in 2-3 months
(part time). Right now I am a bit rusty and trying to catch up again
with Python.

I am now appearing for Job Interviews these days and I am wondering if
anybody of you appeared for a Python Interview. Can you please share
the questions you were asked. That will be great help to me.

Thanks,

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


Parsing xml file in python

2007-10-30 Thread amjadcsu
I am a newbie in python
I am trying to parse a xml file and write its content in a txt file.
The txt contains null elements. Any reason what  iam doing wrong here


Here is the code that i wrote

import sys,os
import xml.sax
import xml.sax.handler
from xml.sax.handler import ContentHandler
from xml.sax import make_parser

class gmondxmlparse (ContentHandler):

def __init__(self,searchTerm):
self.searchTerm=searchTerm;

def startElement(self,name,attrs):

if name=="HOST":
self.hostname=attrs.get('NAME',"")
self.IP=attrs.get('IP',"")
elif name=="METRIC":
self.metricname=attrs.get('NAME', "")
self.metricvalue=attrs.get('VAL',"")
self.metrictype=attrs.get('TYPE',"")
self.metricunit=attrs.get('UNITS',"")
return

def endElement(self,name):
if name=="HOST" and self.searchTerm==self.hostname:
try:
fh=open('/root/yhpc-2.0/ganglia.txt' ,'w')
except:
print "File /root/yhpc-2.0/ganglia.txt can not be
open"
sys.exit(1)
fh.write("This is a test for xml parsing with python with
chris and amjad \n")
fh.write("the host name is", self.hostname, "\n")
fh.write("the ip address is", self.IP, "\n")
fh.close()

searchTerm="HOST"
parser=make_parser()
curHandler=gmondxmlparse(searchTerm)
parser.setContentHandler(curHandler)
parser.parse(open("/root/yhpc-2.0/gmond.xml"))


Here is the sample of xml file

Here is the  xmk file called gmond.xml



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


Re: Parsing xml file in python

2007-10-30 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> I am a newbie in python
> I am trying to parse a xml file and write its content in a txt file.
> The txt contains null elements. Any reason what  iam doing wrong here
> 
> 
> Here is the code that i wrote
> 
> import sys,os
> import xml.sax
> import xml.sax.handler
> from xml.sax.handler import ContentHandler
> from xml.sax import make_parser
> 
> class gmondxmlparse (ContentHandler):
> 
> def __init__(self,searchTerm):
> self.searchTerm=searchTerm;
> 
> def startElement(self,name,attrs):
> 
> if name=="HOST":
> self.hostname=attrs.get('NAME',"")
> self.IP=attrs.get('IP',"")
> elif name=="METRIC":
> self.metricname=attrs.get('NAME', "")
> self.metricvalue=attrs.get('VAL',"")
> self.metrictype=attrs.get('TYPE',"")
> self.metricunit=attrs.get('UNITS',"")
> return
> 
> def endElement(self,name):
> if name=="HOST" and self.searchTerm==self.hostname:
> try:
> fh=open('/root/yhpc-2.0/ganglia.txt' ,'w')
> except:
> print "File /root/yhpc-2.0/ganglia.txt can not be
> open"
> sys.exit(1)
> fh.write("This is a test for xml parsing with python with
> chris and amjad \n")
> fh.write("the host name is", self.hostname, "\n")
> fh.write("the ip address is", self.IP, "\n")
> fh.close()
> 
> searchTerm="HOST"
> parser=make_parser()
> curHandler=gmondxmlparse(searchTerm)
> parser.setContentHandler(curHandler)
> parser.parse(open("/root/yhpc-2.0/gmond.xml"))
> 
> 
> Here is the sample of xml file
> 
> Here is the  xmk file called gmond.xml
>  TN="0" TMAX="20" DMAX="0" LOCATION="unspecified"
> GMOND_STARTED="1193170061">
>  TMAX="1200" DMAX="0" SLOPE="zero" SOURCE="gmond"/>
> 

Without an actual error given, it's hard to know what your problem is.

One thing though is noticable: your XML below isn't valid - XML has only 
one root-element.

And just for the record: it appears that you work under linux using a 
root-account. Bad idea. Really.

http://linuxbraindump.org/2007/08/13/the-10-commandments-for-new-linux-users/

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


Re: Python Interview Questions

2007-10-30 Thread sndive

Krypto wrote:
> Hi,
>
> I have used Python for a couple of projects last year and I found it
> extremely useful. I could write two middle size projects in 2-3 months
> (part time). Right now I am a bit rusty and trying to catch up again
> with Python.
>
> I am now appearing for Job Interviews these days and I am wondering if
> anybody of you appeared for a Python Interview. Can you please share
> the questions you were asked. That will be great help to me.
>
> Thanks,

assert() in the c functions extending python ends the interview rather
quickly.
or at least it did for me @IronPort ages ago.
To be honest they have massively multithreaded app
and the last thing they needed was an appliance down because
some programmer was not sure what to do when a certain condition
arises.

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


Re: Iteration for Factorials

2007-10-30 Thread [EMAIL PROTECTED]
On Oct 30, 10:25 am, "J. Clifford Dyer" <[EMAIL PROTECTED]> wrote:
> On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding Re: 
> Iteration for Factorials:
>
>
>
> > Py-Fun wrote:
> > > I'm stuck trying to write a function that generates a factorial of a
> > > number using iteration and not recursion.  Any simple ideas would be
> > > appreciated.
>
> > fact = lambda n : len(map([1].__imul__,range(1,n+1))[0])
>
> OK.  Now I've been sucked in.  How about this:
>
> def fact(x):
> def f(x):
> if int(x) != x:
> raise ValueError
> elif x > 1:
> return f(x-1) ** x
> elif x == 1:
> return 10
> else:
> raise ValueError
> return len(str(f(x))) -1
>
> The great part about this recursive solution is that you don't have to worry 
> about the stack limit because performance degrades so quickly on the 
> conversion to string!  fact(8) takes a little less than a second, fact(9) 
> takes about a minute, and fact(10) takes more time than I had patience to 
> wait for!

And the not-so-great part is that it raises an exception
on fact(0) which makes it utterly useless for calculating
combinations of m things taken n at a time: m!/n!*(m-n)!

Why is it that no one seems able to get this right?

>
> Cheers,
> Cliff


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


Re: Parsing xml file in python

2007-10-30 Thread amjadcsu
That XML is just a snapshot
I am not getting into the xml parser. The error is not generated but
also the /root/yhpc-2.0/ganglia.txt does not contain anything.




On Oct 30, 12:32 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] schrieb:
>
>
>
> > I am a newbie in python
> > I am trying to parse a xml file and write its content in a txt file.
> > The txt contains null elements. Any reason what  iam doing wrong here
>
> > Here is the code that i wrote
>
> > import sys,os
> > import xml.sax
> > import xml.sax.handler
> > from xml.sax.handler import ContentHandler
> > from xml.sax import make_parser
>
> > class gmondxmlparse (ContentHandler):
>
> > def __init__(self,searchTerm):
> > self.searchTerm=searchTerm;
>
> > def startElement(self,name,attrs):
>
> > if name=="HOST":
> > self.hostname=attrs.get('NAME',"")
> > self.IP=attrs.get('IP',"")
> > elif name=="METRIC":
> > self.metricname=attrs.get('NAME', "")
> > self.metricvalue=attrs.get('VAL',"")
> > self.metrictype=attrs.get('TYPE',"")
> > self.metricunit=attrs.get('UNITS',"")
> > return
>
> > def endElement(self,name):
> > if name=="HOST" and self.searchTerm==self.hostname:
> > try:
> > fh=open('/root/yhpc-2.0/ganglia.txt' ,'w')
> > except:
> > print "File /root/yhpc-2.0/ganglia.txt can not be
> > open"
> > sys.exit(1)
> > fh.write("This is a test for xml parsing with python with
> > chris and amjad \n")
> > fh.write("the host name is", self.hostname, "\n")
> > fh.write("the ip address is", self.IP, "\n")
> > fh.close()
>
> > searchTerm="HOST"
> > parser=make_parser()
> > curHandler=gmondxmlparse(searchTerm)
> > parser.setContentHandler(curHandler)
> > parser.parse(open("/root/yhpc-2.0/gmond.xml"))
>
> > Here is the sample of xml file
>
> > Here is the  xmk file called gmond.xml
> >  > TN="0" TMAX="20" DMAX="0" LOCATION="unspecified"
> > GMOND_STARTED="1193170061">
> >  > TMAX="1200" DMAX="0" SLOPE="zero" SOURCE="gmond"/>
>
> Without an actual error given, it's hard to know what your problem is.
>
> One thing though is noticable: your XML below isn't valid - XML has only
> one root-element.
>
> And just for the record: it appears that you work under linux using a
> root-account. Bad idea. Really.
>
> http://linuxbraindump.org/2007/08/13/the-10-commandments-for-new-linu...
>
> Diez


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


simple? embedding question

2007-10-30 Thread sndive
suppose i have imported two modules foo and bar with
foo=PyImport_ImportModule("foo") and bar=PyImport_ImportModule("bar")
respectively.

Now suppose I have an artitrary python expression to evaluate.
Do I need to parse that thring and check for foo. and bar. before
jumping the usual
PyModule_GetDict,PyDict_GetItemString,PyObject_CallObject hoop hoop on
the PyObject for
the prefix or there is a better way?

btw PyRun_SimpleString("foo.baz()"); does not work:
 Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'foo' is not defined

and i potentially need a PyObject* back with the result of the
expression anyway.

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


Re: Iteration for Factorials

2007-10-30 Thread J. Clifford Dyer
On Tue, Oct 30, 2007 at 11:37:57AM -0700, [EMAIL PROTECTED] wrote regarding Re: 
Iteration for Factorials:
> 
> On Oct 30, 10:25 am, "J. Clifford Dyer" <[EMAIL PROTECTED]> wrote:
> > On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding Re: 
> > Iteration for Factorials:
> >
> >
> >
> > > Py-Fun wrote:
> > > > I'm stuck trying to write a function that generates a factorial of a
> > > > number using iteration and not recursion.  Any simple ideas would be
> > > > appreciated.
> >
> > > fact = lambda n : len(map([1].__imul__,range(1,n+1))[0])
> >
> > OK.  Now I've been sucked in.  How about this:
> >
> > def fact(x):
> > def f(x):
> > if int(x) != x:
> > raise ValueError
> > elif x > 1:
> > return f(x-1) ** x
> > elif x == 1:
> > return 10
> > else:
> > raise ValueError
> > return len(str(f(x))) -1
> >
> > The great part about this recursive solution is that you don't have to 
> > worry about the stack limit because performance degrades so quickly on the 
> > conversion to string!  fact(8) takes a little less than a second, fact(9) 
> > takes about a minute, and fact(10) takes more time than I had patience to 
> > wait for!
> 
> And the not-so-great part is that it raises an exception
> on fact(0) which makes it utterly useless for calculating
> combinations of m things taken n at a time: m!/n!*(m-n)!
> 
> Why is it that no one seems able to get this right?
> 

I can't speak for everyone, but my excuses are as follows:

* I haven't studied math or done math-heavy work in 8 years.
* I'm not at my home computer, and most of the thread (wherein, I now recall, 
that particular rule was specified) is downloaded to my home computer, so I was 
working from my feeble memory.
* I didn't care enough to google for it.

That said, s/elif x == 1:/elif x in (0,1):/ should solve the problem
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: choose from a list

2007-10-30 Thread [EMAIL PROTECTED]
On Oct 30, 1:03 pm, barronmo <[EMAIL PROTECTED]> wrote:
> I'm new to programming and even newer to Python and would be grateful
> for some help on what has been a tough problem for me.  The project I
> am working on is an electronic medical record using MySQL/Python.  I'm
> currrently working on a module that looks up a patient's name based on
> input from the user.
>
> My goal is a lookup based on the first 2 or 3 letters of the patient's
> last name.  The matching results would appear as numbered choices so
> that the user would choose only a number to then access various parts
> of the patient's record.  The results might look like this for user
> input "smi":
>
> 1  387  John Smith
> 2  453  Jane Smith
> 3  975  Joe Smithton
>
> Here is a copy of what I have so far, name_lookup.py:
>
> import MySQLdb
>
> def name_find(namefrag):
>
>  conn = MySQLdb.connect(host = "localhost",
>   user = "root",
>   passwd = "n85",
>   db = "meds")
>  cursor = conn.cursor(MySQLdb.cursors.DictCursor)
>  cursor.execute("SELECT patient_ID, firstname, lastname FROM
> demographics WHERE lastname LIKE '"+ str(namefrag)+"%'")
>  results = cursor.fetchall()

Change this

>  for row in results:
>   print "%s   %s %s  %s" % (row["patient_ID"],
> row["firstname"], row["lastname"])

to this

 for rec,row in enumerate(results):
  print "%d %s   %s %s  %s" %
(rec,row["patient_ID"],row["firstname"], row["lastname"])

>
>  cursor.close()
>  conn.close()
>
> Thanks in advance for any help.
>
> Mike


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


Re: Parsing xml file in python

2007-10-30 Thread Marc 'BlackJack' Rintsch
On Tue, 30 Oct 2007 11:45:17 -0700, amjadcsu wrote:

> I am not getting into the xml parser.

What does this mean!?

> The error is not generated but also the /root/yhpc-2.0/ganglia.txt does
> not contain anything.

Maybe because…

>> > def endElement(self,name):
>> > if name=="HOST" and self.searchTerm==self.hostname:
>> > try:
>> > fh=open('/root/yhpc-2.0/ganglia.txt' ,'w')
>> > except:
>> > print "File /root/yhpc-2.0/ganglia.txt can not be
>> > open"
>> > sys.exit(1)
>> > fh.write("This is a test for xml parsing with python with
>> > chris and amjad \n")
>> > fh.write("the host name is", self.hostname, "\n")

…this line will raise an exception.  `file.write()` takes just one
argument, not three as in this call.  If you don't get an exception maybe
you have other places with a bare ``except`` like in the snippet above. 
Don't do that.  Catch the specific exception you want to handle with an
``except`` and not simply *all*.

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

Re: Python Interview Questions

2007-10-30 Thread Tim Chase
 > I have used Python for a couple of projects last year and
 > I found it extremely useful. I could write two middle size
 > projects in 2-3 months (part time). Right now I am a bit
 > rusty and trying to catch up again with Python.
 >
 > I am now appearing for Job Interviews these days and I am
 > wondering if anybody of you appeared for a Python
 > Interview. Can you please share the questions you were
 > asked. That will be great help to me.

While I haven't interviewed precisely for Python, I've been
on the other (interviewing) end and can offer a few of the
sorts of things I ask.  I don't expect perfect answers to
all of them, but they show me a range of what the
interviewee knows.  I try and give a scattershot of
questions from the following areas to try and narrow down
where they fall in terms of pythonability, and then grill
more deeply around the edges that I find.

Basic Python:
=
- do they know a tuple/list/dict when they see it?

- when to use list vs. tuple vs. dict. vs. set

- can they use list comprehensions (and know when not to
   abuse them? :)

- can they use tuple unpacking for assignment?

- string building...do they use "+=" or do they build a list
   and use .join() to recombine them efficiently

- truth-value testing questions and observations (do they
   write "if x == True" or do they just write "if x")

- basic file-processing (iterating over a file's lines)

- basic understanding of exception handling

Broader Basic Python:
=
- questions about the standard library ("do you know if
   there's a standard library for doing X?", or "in which
   library would you find [common functionality Y]?")  Most
   of these are related to the more common libraries such as
   os/os.path/sys/re/itertools

- questions about iterators/generators

- questions about map/reduce/sum/etc family of functions

- questions about "special" methods ()

More Advanced Python:
=
- can they manipulate functions as first-class objects
   (Python makes it easy, but do they know how)

- more detailed questions about the std. libraries (such as
   datetime/email/csv/zipfile/networking/optparse/unittest)

- questions about testing (unittests/doctests)

- questions about docstrings vs. comments, and the "Why" of
   them

- more detailed questions about regular expressions

- questions about mutability

- keyword/list parameters and unpacked kwd args

- questions about popular 3rd-party toolkits (BeautifulSoup,
   pyparsing...mostly if they know about them and when to use
   them, not so much about implementation details)

- questions about monkey-patching

- questions about PDB

- questions about properties vs. getters/setters

- questions about classmethods

- questions about scope/name-resolution

- use of lambda

Python History:
===
- decorators added in which version?

- "batteries included" SQL-capible DB in which version?

- the difference between "class Foo" and "class Foo(object)"

- questions from "import this" about pythonic code

Python Resources:
=
- what do they know about various Python web frameworks
   (knowing a few names is usually good enough, though
   knowledge about the frameworks is a nice plus) such as
   Django, TurboGears, Zope, etc.

- what do they know about various Python GUI frameworks and
   the pros/cons of them (tkinter, wx, pykde, etc)

- where do they go with Python related questions (c.l.p,
   google, google-groups, etc)

Other Process-releated things:
==
- do they use revision control
   (RCS/CVS/Subversion/Mercurial/Git...anything but VSS) and
   know how to use it well

- do they write automated tests for their code

Touchy-feely things:

- tabs vs. spaces, and their reasoning

- reason for choosing Python

- choice of editor/IDE

Good luck with your interviewing and hope this helped,

-tkc





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


Re: A class question

2007-10-30 Thread Bruno Desthuilliers
Donn Ingle a écrit :
>>vzcbeg vafcrpg
>>
>>qrs _svaq(senzr, bow):
>>sbe anzr, inyhr va senzr.s_ybpnyf.vgrevgrzf():
>>vs inyhr vf bow:
>>erghea anzr
>>sbe anzr, inyhr va senzr.s_tybonyf.vgrevgrzf():
>>vs inyhr vf bow:
>>erghea anzr
>>envfr XrlReebe("Bowrpg abg sbhaq va senzr tybonyf be ybpnyf")
>>
>>pynff K:
>>qrs qroht(frys):
>>cevag ("Pnyyre fgberf zr va %f (nzbat bgure cbffvoyr cynprf)"
>>   % _svaq(vafcrpg.pheeragsenzr(1), frys))
> 
> 
> Now that's taking i18n too far. Klingon is not a widely understood
> language :D

s/i18n/rot13/ !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing xml file in python

2007-10-30 Thread J. Clifford Dyer
On Tue, Oct 30, 2007 at 11:45:17AM -0700, [EMAIL PROTECTED] wrote regarding Re: 
Parsing xml file in python:

Top-posting corrected

> 
> 
> 
> On Oct 30, 12:32 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > [EMAIL PROTECTED] schrieb:
> >
> >
> >
> > > I am a newbie in python
> > > I am trying to parse a xml file and write its content in a txt file.
> > > The txt contains null elements. Any reason what  iam doing wrong here
> >
> > > Here is the code that i wrote
> >
> > > import sys,os
> > > import xml.sax
> > > import xml.sax.handler
> > > from xml.sax.handler import ContentHandler
> > > from xml.sax import make_parser
> >
> > > class gmondxmlparse (ContentHandler):
> >
> > > def __init__(self,searchTerm):
> > > self.searchTerm=searchTerm;
> >
> > > def startElement(self,name,attrs):
> >
> > > if name=="HOST":
> > > self.hostname=attrs.get('NAME',"")
> > > self.IP=attrs.get('IP',"")
> > > elif name=="METRIC":
> > > self.metricname=attrs.get('NAME', "")
> > > self.metricvalue=attrs.get('VAL',"")
> > > self.metrictype=attrs.get('TYPE',"")
> > > self.metricunit=attrs.get('UNITS',"")
> > > return
> >
> > > def endElement(self,name):
> > > if name=="HOST" and self.searchTerm==self.hostname:
> > > try:
> > > fh=open('/root/yhpc-2.0/ganglia.txt' ,'w')
> > > except:
> > > print "File /root/yhpc-2.0/ganglia.txt can not be
> > > open"
> > > sys.exit(1)
> > > fh.write("This is a test for xml parsing with python with
> > > chris and amjad \n")
> > > fh.write("the host name is", self.hostname, "\n")
> > > fh.write("the ip address is", self.IP, "\n")
> > > fh.close()
> >
> > > searchTerm="HOST"
> > > parser=make_parser()
> > > curHandler=gmondxmlparse(searchTerm)
> > > parser.setContentHandler(curHandler)
> > > parser.parse(open("/root/yhpc-2.0/gmond.xml"))
> >
> > > Here is the sample of xml file
> >
> > > Here is the  xmk file called gmond.xml
> > >  > > TN="0" TMAX="20" DMAX="0" LOCATION="unspecified"
> > > GMOND_STARTED="1193170061">
> > >  > > TMAX="1200" DMAX="0" SLOPE="zero" SOURCE="gmond"/>
> >
> > Without an actual error given, it's hard to know what your problem is.
> >
> > One thing though is noticable: your XML below isn't valid - XML has only
> > one root-element.
> >
> > And just for the record: it appears that you work under linux using a
> > root-account. Bad idea. Really.
> >
> > http://linuxbraindump.org/2007/08/13/the-10-commandments-for-new-linu...
> >
> > Diez
> 
> 
> That XML is just a snapshot
> I am not getting into the xml parser. The error is not generated but
> also the /root/yhpc-2.0/ganglia.txt does not contain anything.
> 

Well, if ganglia.txt contains nothing, and you received no output from the 
program, then either endElement never got called, or `if name=="HOST" and 
self.searchTerm==self.hostname:` never evaluated to true.  Because if you 
couldn't open for writing, you would have gotten the message you set up on the 
except block, and if you could, then even if your variables didn't contain any 
data, you would have seen the boilerplate text that you wrote.

Cheers,
Cliff

P.S. Please bottom-post when replying to the python list.  It sucks to have to 
look up and down a thread to see what's been said.

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


Re: simple? embedding question

2007-10-30 Thread Farshid Lashkari
[EMAIL PROTECTED] wrote:
> suppose i have imported two modules foo and bar with
> foo=PyImport_ImportModule("foo") and bar=PyImport_ImportModule("bar")
> respectively.
> 
> Now suppose I have an artitrary python expression to evaluate.
> Do I need to parse that thring and check for foo. and bar. before
> jumping the usual
> PyModule_GetDict,PyDict_GetItemString,PyObject_CallObject hoop hoop on
> the PyObject for
> the prefix or there is a better way?
> 
> btw PyRun_SimpleString("foo.baz()"); does not work:
>  Traceback (most recent call last):
>   File "", line 1, in ?
> NameError: name 'foo' is not defined
> 
> and i potentially need a PyObject* back with the result of the
> expression anyway.
> 

I believe the problem is that you are not importing the "foo" and "bar" 
modules into the __main__ scope. Try using PyImport_ImportModuleEx, 
which will allow you to specify the global scope to import the module 
into. For example, to import the modules into the __main__ scope you 
could do the following:

PyObject* mainmod = PyImport_AddModule("__main__");
PyObject* maindict = PyModule_GetDict(mainmod);

foo = PyImport_ImportModuleEx("foo", maindict , maindict , NULL);
bar = PyImport_ImportModuleEx("bar", maindict , maindict , NULL);

Once the modules are imported into the __main__ scope, you should be 
able to use PyRun_SimpleString() to evaluate expressions.

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


parsing ast nodes help to get callfunc values.

2007-10-30 Thread Glich
"""
Hi! This is my code so far:

This code analyzes a python file.

How can I separate CallFunc from the est of the ast node?

file.py is as follows:
_
def fun1():
print "Hi"
fun2()
fun4()

def fun2():
pass

def fun4():
pass

fun1()

_


The output from running this program (not file.py) is:
_
Func name: fun1
Func line number: 1

Stmt([Printnl([Const('Hi')], None), Discard(CallFunc(Name('fun2'), [],
None, None)), Discard(CallFunc(Name('fun4'), [], None, None))])

isinstance false

Func name: fun2
Func line number: 6

Stmt([Pass()])

isinstance false

Func name: fun4
Func line number: 9

Stmt([Pass()])

isinstance false
Traceback (most recent call last):
  File "/home/glich/compi.py", line 15, in 
print "\nFunc name: " + str(func.name)
AttributeError: Discard instance has no attribute 'name'

_

Please note the traceback is not important right now. I can deal with
that on my own.

What I want to do is sepperate "CallFunc(Name('fun2'), [], None,
None)" from each "func.code" and furthermore to get "fun2" from
"CallFunc(Name('fun2'), [], None, None)" (my ultimate goal!).

I gues I could split the string but I need to be able to get
"CallFunc(Name()" from "func.code" which might have multiple
"CallFunc(Name()" such as:

"Stmt([Printnl([Const('Hi')], None), Discard(CallFunc(Name('fun2'),
[], None, None)), Discard(CallFunc(Name('fun4'), [], None, None))])"


which is an "ast" repesentation of the function "fun1" in "file.py".

If some one could show me how to use something called "visitor"? I
would be very grateful. I did not understand the documentation and I
am in need of more SIMPLE example code. Any way, thanks.

Is there somthing along the lines of:

>>> first_callfunc = func.code.callfunc(1)
>>> second_callfunc = func.code.callfunc(2)
>>> third_callfunc = func.code.callfunc(3)
>>> print first_callfunc
CallFunc(Name('fun2'), [], None, None)

"""

import compiler
import compiler.ast

parse_file = compiler.parseFile("/home/glich/file.py")

count = 0

for count, func in enumerate(parse_file.node.nodes):

print "\nFunc name: " + str(func.name)  # Prints function name.
print "Func line number: " + str(func.lineno) + "\n"

print str(func.code) + "\n"

if isinstance(func, compiler.ast.CallFunc):
print "isinstance true" # This should be called 
sometimes.
else:
print "isinstance false"# This is always called but 
why?!?!?

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


Re: choose from a list

2007-10-30 Thread Bruno Desthuilliers
barronmo a écrit :
> I'm new to programming and even newer to Python and would be grateful
> for some help on what has been a tough problem for me.  The project I
> am working on is an electronic medical record using MySQL/Python.  I'm
> currrently working on a module that looks up a patient's name based on
> input from the user.
> 
> My goal is a lookup based on the first 2 or 3 letters of the patient's
> last name.  The matching results would appear as numbered choices so
> that the user would choose only a number to then access various parts
> of the patient's record.  The results might look like this for user
> input "smi":
> 
> 1  387  John Smith
> 2  453  Jane Smith
> 3  975  Joe Smithton
> 
> Here is a copy of what I have so far, name_lookup.py:
> 
> 
> import MySQLdb
> 
> def name_find(namefrag):
> 
>  conn = MySQLdb.connect(host = "localhost",
>   user = "root",
>   passwd = "n85",
>   db = "meds")

Opening (and closing) a connection to the RDBMS on each and every 
function is certainly not the best way to go.

>  cursor = conn.cursor(MySQLdb.cursors.DictCursor)
>  cursor.execute("SELECT patient_ID, firstname, lastname FROM
> demographics WHERE lastname LIKE '"+ str(namefrag)+"%'")

Please re-read both the db-api and MySQLdb docs. You should not build 
the whole query this way, but instead use (db module specific) 
plaeholders and pass actual params as a tuple, ie (if I correctly 
remember MySQLdb specificities):

cursor.execute(
"SELECT patient_ID, firstname, lastname FROM " \
  + " demographics WHERE lastname LIKE '%s%%'),
(namefrag, )
)


>  results = cursor.fetchall()
>  for row in results:

Some db modules let you iterate directly over the cursor. Check if it's 
the case with MySQLdb. If so, you may want:

for row in cursor:

instead.

>   print "%s   %s %s  %s" % (row["patient_ID"],
> row["firstname"], row["lastname"])

Python has better to offer wrt/ string formatting (assuming patient_ID 
is an integer):

print "%(patient_ID)03d %(firstname)s, %(lastname)s" % row

> 
> Thanks in advance for any help.

wrt/ (what I guess is) your (very implicit) question, you may want to 
have a look at enumerate(iterable):

for index, item in enumerate(cursor): #or:enumerate(cursor.fetchall()):
 print i, item

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


Re: simple? embedding question

2007-10-30 Thread kyosohma
On Oct 30, 1:31 pm, [EMAIL PROTECTED] wrote:
> suppose i have imported two modules foo and bar with
> foo=PyImport_ImportModule("foo") and bar=PyImport_ImportModule("bar")
> respectively.
>
> Now suppose I have an artitrary python expression to evaluate.
> Do I need to parse that thring and check for foo. and bar. before
> jumping the usual
> PyModule_GetDict,PyDict_GetItemString,PyObject_CallObject hoop hoop on
> the PyObject for
> the prefix or there is a better way?
>
> btw PyRun_SimpleString("foo.baz()"); does not work:
>  Traceback (most recent call last):
>   File "", line 1, in ?
> NameError: name 'foo' is not defined
>
> and i potentially need a PyObject* back with the result of the
> expression anyway.

I'm confused. What is the benefit of importing this way in the first
place? Everything I've read has always been either of the following
(or a variant thereof):

import foo

or

from foo import bar

Mike

P.S. Yes, I did see the docs mention this method here:
http://docs.python.org/api/importing.html but i have always followed
http://effbot.org/zone/import-confusion.htm or 
http://docs.python.org/ref/import.html

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


Re: appending into a list

2007-10-30 Thread Bruno Desthuilliers
c james a écrit :
> Beema shafreen wrote:
> 
>>  2721520  2721569A_16_P21360235199-49
>>  2721768  2721821A_16_P03641971139-53
>>  2721960  2722004A_16_P21360237312-44
>>I need to append the column D and E into a list:
>>in such a way that the list should have 
>>[D,E,D,E,D,E]
>>How do i do it.
>>
>>regards
>>shafreen
> 
> 
> Without a header, you could use something like
> 
> data = [x.split()[-2:] for x in open(filename).readlines()]
> 
> With header
> 
> f = open(filename)
> f.readline()
> data = [x.split()[-2:] for x in f.readlines()]
>   
> 
Or just use the CSV module ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Readline and record separator

2007-10-30 Thread Bruno Desthuilliers
Johny a écrit :
> Is it possible to change record separator when using readline?
> As far as I know readline reads characters until found '\n' and it is
> the end of record for readline.

This is not a "record" separator, but a newline. As the name implies, 
file.readline is about reading a text file line by line. For a 
definition of "line" being : "a chuk of text that starts either at the 
beginning of the document or after a newline" and for a definition of 
"newline" being "a platform-specific character or character sequence".

> My problem is that my record consits several '\n' and when I use
> readline it does NOT read the whole my record.
> So If I could change '\n' as  a record separator for readline, it
> would solve my problem.
> Any idea?

If you're dealing with (so-called) CSV files, you might want to have a 
look at the (oh surprise) CSV module (in the stdlib) instead.

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


Re: Readline and record separator

2007-10-30 Thread Bruno Desthuilliers
Jeff a écrit :
> If it's a short file you could slurp the entire file and then split it
> however you like using regular expressions.

My my my...

> I'm not sure if you can alter it,

You can. But it hopefully won't alter your binary-compiled system libs. 
IOW : it's so (obviously) useless that no one even bothered doing 
anything to prevent you from altering it !-)

  but os.linesp
  os.line

> holds the value that
> is accessed when file.readlines() splits lines.  Conceivably, if it
> were set to 'FOO', 'FOO' would be used to determine the EOL string.

Hopefully not. Anyway, the answer is elsewhere (hint: import csv).

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


Re: python in academics?

2007-10-30 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> On Oct 29, 10:39 pm, sandipm <[EMAIL PROTECTED]> wrote:
> 
>>seeing posts from students on group. I am curious to know, Do they
>>teach python in academic courses in universities?
>>
>>in undergrad comp science courses,  We had scheme language as scheme
>>is neat and beautiful language to learn programming. We learnt other
>>languages ourselve with basics set right by scheme..
>>
>>sandip
> 
> 
> They didn't at either of the colleges I went to. They seemed to be
> focused on C++, COBOL and Visual Basic. All are used all over the
> place, but only Visual Basic is easy for complete newbs.

And alas one of the worst languages for a beginner - because you'll 
probably need years to unlearn it.

> I hope more
> colleges adopt Python or Ruby as a teaching language, but I don't
> think it's a good idea to ignore COBOL or C++ since their used so
> extensively in big business.

being widely used doesn't imply being a good language for teaching CS 
(nor even being a good language for anything).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: setting variables in outer functions

2007-10-30 Thread Bruno Desthuilliers
brad a écrit :
> Tommy Nordgren wrote:
> 
>>> def outer(avar=False):
>>>  print avar
>>>  if avar == True:
>>>  return
>>>
>>>  def inner(avar=True):
>>>  print avar
>>>  return avar
>>>
>>>  outer(inner())
>>>
>>> outer()
> 
> 
>> This is not a general solution to this problem.
> 
> 
> Run my example code, it works (if I'm understanding your question 
> correctly). It sets outer to True... inner returns True to outer and 
> thus the var is set... am I missing something?

Yes: you forgot to rebind avar in inner and check the result in outer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A class question

2007-10-30 Thread Bruno Desthuilliers
Hrvoje Niksic a écrit :
> Bruno Desthuilliers <[EMAIL PROTECTED]>
> writes:
> 
> 
>>>While Java's variable declarations bear a superficial (syntactical)
>>>similarity to C, their semantics is in fact equivalent to the
>>>object-reference semantics we know in Python.   They implicitly refer
>>>to objects allocated on the heap and, just like in Python, the same
>>>object can be referenced by multiple variables. 
>>
>>You're talking about reference types here - not primitive types. And
>>even then, from what I remember (not having done any Java these last
>>4 years at least), Java's reference types are much closer to C++
>>references than to Python.
> 
> 
> Feel free to look it up; I believe you will find the semantics of
> assignment, parameter-passing, etc., exactly the same as in Python.

I'll do - while perhaps not in a near future !-) - and keep you informed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iteration for Factorials

2007-10-30 Thread [EMAIL PROTECTED]
On Oct 30, 1:52 pm, "J. Clifford Dyer" <[EMAIL PROTECTED]> wrote:
> On Tue, Oct 30, 2007 at 11:37:57AM -0700, [EMAIL PROTECTED] wrote regarding 
> Re: Iteration for Factorials:
>
>
>
>
>
>
>
> > On Oct 30, 10:25 am, "J. Clifford Dyer" <[EMAIL PROTECTED]> wrote:
> > > On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding 
> > > Re: Iteration for Factorials:
>
> > > > Py-Fun wrote:
> > > > > I'm stuck trying to write a function that generates a factorial of a
> > > > > number using iteration and not recursion.  Any simple ideas would be
> > > > > appreciated.
>
> > > > fact = lambda n : len(map([1].__imul__,range(1,n+1))[0])
>
> > > OK.  Now I've been sucked in.  How about this:
>
> > > def fact(x):
> > > def f(x):
> > > if int(x) != x:
> > > raise ValueError
> > > elif x > 1:
> > > return f(x-1) ** x
> > > elif x == 1:
> > > return 10
> > > else:
> > > raise ValueError
> > > return len(str(f(x))) -1
>
> > > The great part about this recursive solution is that you don't have to 
> > > worry about the stack limit because performance degrades so quickly on 
> > > the conversion to string!  fact(8) takes a little less than a second, 
> > > fact(9) takes about a minute, and fact(10) takes more time than I had 
> > > patience to wait for!
>
> > And the not-so-great part is that it raises an exception
> > on fact(0) which makes it utterly useless for calculating
> > combinations of m things taken n at a time: m!/n!*(m-n)!
>
> > Why is it that no one seems able to get this right?
>
> I can't speak for everyone, but my excuses are as follows:
>
> * I haven't studied math or done math-heavy work in 8 years.

Fair enough. I primarily do math-heavy work, and am familiar
with such matters. But that's just me.

> * I'm not at my home computer, and most of the thread (wherein,
>   I now recall, that particular rule was specified) is downloaded
>   to my home computer, so I was working from my feeble memory.

Well, I've only had to point it out a dozen times already in
this thread. Nice to see that all that effort has been for nought.

> * I didn't care enough to google for it.

Quoting from Monty Python:
"It's just as easy to get these things right, you know."

>
> That said, s/elif x == 1:/elif x in (0,1):/ should solve the problem

Sure, it's always easily solvable. I just hope someone learns the
lesson on how to test properly, to make sure things work the way
they should and to fail the way they should so that one can actually
trust the algorithms they write.

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


_tkinter installation in python 2.5 on mandriva with a default 2.4

2007-10-30 Thread wyleu
 I'm running on  Mandriva 2007 (2.6.17-5mdv) and thus have python2.4.3
installed by default,
I'm running code requiring yield(), so need python2.5 and have
installed this sucessfully, and linked appropriately to allow me to
start python2.5 by typing python2.5. However I'd like to use idle so
require to be able to import _tkinter.
I gather I need to modift the setup.py script in my python directory
but am wary of experimenting since I've had problems with damaging the
default tkinter installation before.


import Tkinter
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.5/lib-tk/Tkinter.py", line 38, in

import _tkinter # If this fails your Python may not be configured
for Tk
ImportError: No module named _tkinter


Should I need to download a later version of tkinter and/or should I
alter setup.py in my python install directory and then remake?
If the former how do I ensure I don't overwrite the original tkinter
install thus damaging the many mandriva utilities that rely on
python2.4.3 and if the later what should I be looking for within the
python2.5 installation to point to and what alterations within
setup.py are required?

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


Re: Python Interview Questions

2007-10-30 Thread Krypto


> Good luck with your interviewing and hope this helped,
>
> -tkc

Well, I was looking exactly for this. Many thanks to you Tim. After
going through your list I came to know that I know nothing in Python
and have to catch up a whole lot.

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


Re: python in academics?

2007-10-30 Thread kyosohma
On Oct 30, 2:55 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] a écrit :
>
> > On Oct 29, 10:39 pm, sandipm <[EMAIL PROTECTED]> wrote:
>
> >>seeing posts from students on group. I am curious to know, Do they
> >>teach python in academic courses in universities?
>
> >>in undergrad comp science courses,  We had scheme language as scheme
> >>is neat and beautiful language to learn programming. We learnt other
> >>languages ourselve with basics set right by scheme..
>
> >>sandip
>
> > They didn't at either of the colleges I went to. They seemed to be
> > focused on C++, COBOL and Visual Basic. All are used all over the
> > place, but only Visual Basic is easy for complete newbs.
>
> And alas one of the worst languages for a beginner - because you'll
> probably need years to unlearn it.

which language? I listed 3...and since you don't actually "learn" a
language at all in a beginner's class, I don't really have anything to
unlearn. All you get in those STUPID classes is a taste of
programming...if you're lucky.


>
> > I hope more
> > colleges adopt Python or Ruby as a teaching language, but I don't
> > think it's a good idea to ignore COBOL or C++ since their used so
> > extensively in big business.
>
> being widely used doesn't imply being a good language for teaching CS
> (nor even being a good language for anything).

I wasn't implying that they were good or bad, but that if you go to
work for most big businesses, than it would probably be beneficial to
know the language(s). For example, most insurance, financial and
government jobs use COBOL to some degree or another.

Mike

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

Arp request to get MAc Adress with IP address

2007-10-30 Thread amjadcsu
Hello,
I have a network on same subnet. I have an ip address of a machine.
but i need to get its MAC Adress.
Sendingf ARP request is the way i am taking.

IS there any other way to get this MAC Adress in python.??

Also does python go down to level 2 of TCP/IP model??


Sorry if i am to naive. Just learning python

thanks

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


Re: A class question

2007-10-30 Thread George Sakkis
On Oct 28, 6:01 am, Donn Ingle <[EMAIL PROTECTED]> wrote:

> Is there a way I can, for debugging, access the instance variable name from
> within a class?

Shouldn't this be in a FAQ somewhere? It's the second time (at least!)
it comes up this week.

George

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


Re: parsing ast nodes help to get callfunc values.

2007-10-30 Thread Peter Otten
Glich wrote:

> If some one could show me how to use something called "visitor"? 

import compiler

module = """
def fun1():
print "Hi"
fun2()
fun4()

def fun2():
pass

def fun4():
pass

fun1()
fun3(fun2())
"""

class Visitor:
def visitCallFunc(self, node):
print node.lineno, node.node.name
for child in node.getChildNodes():
compiler.walk(child, self)

if __name__ == "__main__":
ast = compiler.parse(module)
visitor = Visitor()
compiler.walk(ast, visitor)

> I did not understand the documentation and I am in need of more SIMPLE
> example code.

If my example is not sufficient I encourage you to take a look into the
source code of the compiler package.

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


why did these companies choose Tcl over Python

2007-10-30 Thread chewie54
Hello,

As an electronics engineer I use some very expensive EDA CAD tool
programs that are scriptable using Tcl.  I was wondering why these
companies have choose to use Tcl instead of Python.   Some of these
are:

   Mentor Graphics ModelTech VHDL and Verilog simulator
   Synopsys  Design Compiler and Primetime Static Timing Analyzer
   Actel FPGA tools.

Tcl seems to very popular in my business as the scripting language of
choice.

I'm in the process of deciding to use Tcl or Python for a CAD tool
program that I have been working on.Most of the core of the
program,  the database,   will be done is C as an extension to either
Tcl or Python,   but I intend to use Tk or wxPthon for the GUI.   I do
need publishing quality outputs from drawings done on a graphics
device that are scaled to standard printer paper sizes.


I would prefer to use Python but can't deny how popular Tcl is,  as
mentioned above,  so my question is why wasn't Python selected by
these companies as the choice of scripting languages for their
product?

Are there any obvious advantages like:

performance,
memory footprint,
better cross-platform support,
ease of use,


Thanks in advance for your thoughts about this.

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


  1   2   >