Re: Module imports during object instantiation

2007-08-14 Thread Bruno Desthuilliers
Ritesh Raj Sarraf a écrit :
> Bruno Desthuilliers wrote:
> 
>> Ritesh Raj Sarraf a écrit :
>>
>> The initializer will be called *each time* you instanciate the class.
>> And nothing prevents client code from calling it explicitelly as many
>> times as it wants  - ok, this would be rather strange, but this is still
>> technically possible. What I mean that you have no assurance about the
>> number of times an initializer will be called.
>>
> 
> Yes, it should be called _each time_ I do an instantiation. But the point
> is, I'm doing it only once. And I don't see people instantiating multiple
> times.

You of course don't instanciate the same object more than once !-) What 
I meant is that, while you can be reasonably confident that the 
initializer will be call at least once (on instanciation), nothing 
prevents user code to directly call it as many times he wants.

> And even if you do, it should do separate imports.

Why so ? Using the import statement, modules are only imported once for 
a given process, you know ? And FWIW, what are the chances your running 
process will move from one platform to another ?-)

> log1 = Log()
> log2 = Log()
> 
> Both the objects are separate from each other in every manner and they share
> nothing.

How can you tell ? In the common case, they at least share a pointer to 
the Log class object, and depending on the implementation they can share 
other things too.

>> wrt/ your problem, remember that top-level code is executed when the
>> module is loaded (either as a main program or as an imported module).
>> The canonical solution to os-specific imports is to handle them at the
>> top-level:
>>
>> if os.name == 'posix:
>>from some_posix_module import get_colors
>> elif os.name in ['nt', 'dos']:
>>from some_nt_module import get_windows_color as get_colors
>> else:
>>get_colors = lambda: None # or any other sensible default value...
>>
>> class SomeClass(object):
>>def __init__(self, *args, **kw):
>>  self.colors = get_colors()
> 
> This is what I'm left with to do currently. But I doubt if that makes by
> classes independent and to "Just Work". If someone was to cut/paste just
> the class, it won't work.

Obviously not. But the module is the basic unit of code in Python.

> He'll have to go through the imports and figure
> out which one relates to the class he want's to import and add similar code
> to his.

I'm afraid you're confusing import, include and cut'n'paste (which is 
probably the worst possible code-reuse technic)... If someone wants to 
reuse your code, the normal way is to import your module (and eventually 
subclass yourmodule.SomeClass to extend/customize it).

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


about negative polar plots

2007-08-14 Thread yadin
hi am doing a polar plot of the radiation pattern of an antenna.
the polar plots represents the value of the power in dB's and the dB
go from -40dB to 0dB
as the angle theta changes from 0 to 2*pi rads
the polar plot in python goes with positive values
how can i solve this problem
rough example
example:
power = arange(-40,0,-10)
theta = arange(0, 2pi,pi/12)
polar(power,theta)
title.?
how can i show the step on the polar plot  plot(-40, -30,-20,-10,0)

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


about negative polar plots not defined in python not even matlab

2007-08-14 Thread yadin
high i think everybody has seen dB radiation pattern plots...
well those are done with negative polar plots ...the values of the
magnitude in the axes are
NEGATIVE values...
but i can find a polar plot command that those negative plots not in
python not even in matlab

the polar plots represents the value of the power radiated in dB's and
the dB's go from -40dB to 0dB
as the angle theta changes from 0 to 2*pi rads
the polar plot in python goes with positive values
how can i solve this problem
rough example
example:
power = arange(-40,0,-10)
theta = arange(0, 2pi,pi/12)
polar(power,theta)
title.?
how can i show the step on the polar plot  plot(-40, -30,-20,-10,0)

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


Re: Module imports during object instantiation

2007-08-14 Thread Bruno Desthuilliers
Ritesh Raj Sarraf a écrit :
> Bruno Desthuilliers wrote:
> 
>> Ritesh Raj Sarraf a écrit :
>>> if lock is None or lock != 1:
>>> self.DispLock = False
>>> else:
>>> self.DispLock = threading.Lock()
>>> self.lock = True
>>>
>>> if os.name == 'posix':
>>>self.platform = 'posix'
>>>self.color = get_colors()
>>>
>>> elif os.name in ['nt', 'dos']:
>>> self.platform = 'microsoft'
>>> 
>>> try:
>>> import SomeModule
>>> except ImportError:
>>> self.Set_Flag = None
>>> 
>>> if self.Set_Flag is not None:
>>> self.color = SomeModule.get_colors_windows()
>>>
>>> else:
>>> self.platform = None
>>> self.color = None
>>>
>>> When I create an object the "import" part never gets executed. Is there a
>>> reason behind it ?
>> what does "print os.name" yields ?
> 
> On Windows: nt
> On Linux: posix

Mmm... I guess you didn't understood my question. I do know the os 
module. You assert the "import" is never executed. Since it's only 
executed on a non-posix platform, I asked on what platform you where 
testing.


> 
>>> I mean I'd like to keep my class as independent as I want. So that when
>>> later I need to use it somewhere else, I don't need to know if it depends
>>> on any modules.
>>  >
>>
>> Then pass the module to the initializer. Python's modules are objects...
>>
> 
> Yes, that's an option. But is that the only one?

No.

> To me it looks like an ugly way of doing.

Really ? Why so ? You say you want to keep your class "as independant" 
(you don't say from what, but...). Can you imagine a way to get less 
coupling than passing appropriate parameters to the initializer ?


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


Re: about negative polar plots

2007-08-14 Thread Erik Max Francis
yadin wrote:

> hi am doing a polar plot of the radiation pattern of an antenna.
> the polar plots represents the value of the power in dB's and the dB
> go from -40dB to 0dB
> as the angle theta changes from 0 to 2*pi rads
> the polar plot in python goes with positive values
> how can i solve this problem
> rough example
> example:
> power = arange(-40,0,-10)
> theta = arange(0, 2pi,pi/12)
> polar(power,theta)
> title.?
> how can i show the step on the polar plot  plot(-40, -30,-20,-10,0)

What is arange?  What is polar?  What is plot?  You're going to have to 
give more information about what you're doing, what you're using to do 
it, and where it's giving you unexpected or undesired results if you 
want help solving your problem.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   So look into my eyes / I won't tell you lies
-- Neneh Cherry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about negative polar plots not defined in python not even matlab

2007-08-14 Thread Robin Becker
.
> polar(power,theta)
> title.?
> how can i show the step on the polar plot  plot(-40, -30,-20,-10,0)
> 

I think you need to consider why you want to plot negative values. The 
decibel scales are actually logarithmic ie all power is actually 
positive. Zero power corresponds to -infinity.

In practice, I think your radiation pattern plot might correspond to 
gain (or attenuation). Just relabel your plot and change the values to 
positive. If you do that and the plots look familiar then you have an 
answer.
-- 
Robin Becker
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Eclipse/PyDev question

2007-08-14 Thread king kikapu
Fabio,

thanks for the reply!

Anyway, i saw that i cannot import anything if i use "Source Folders"
in Eclipse/PyDev. The only way i can accomplish that is by using
"PyDev Packages". Thus, i can import whatever i want ant intellisense
is working great! I just cannot understand the usefulness of "PyDev
Source Folders"...

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


Re: about negative polar plots

2007-08-14 Thread special_dragonfly

"Erik Max Francis" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> yadin wrote:
>
>> hi am doing a polar plot of the radiation pattern of an antenna.
>> the polar plots represents the value of the power in dB's and the dB
>> go from -40dB to 0dB
>> as the angle theta changes from 0 to 2*pi rads
>> the polar plot in python goes with positive values
>> how can i solve this problem
>> rough example
>> example:
>> power = arange(-40,0,-10)
>> theta = arange(0, 2pi,pi/12)
>> polar(power,theta)
>> title.?
>> how can i show the step on the polar plot  plot(-40, -30,-20,-10,0)
>
> What is arange?  What is polar?  What is plot?  You're going to have to 
> give more information about what you're doing, what you're using to do it, 
> and where it's giving you unexpected or undesired results if you want help 
> solving your problem.
>
> -- 
> Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
>  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
>   So look into my eyes / I won't tell you lies
>-- Neneh Cherry

I can understand the problem, that when plotting in polar co-ordinates the 
center of the plot is a value of zero. You're wanting a value of -40 at the 
center? Is this a fixed quantity? The lines would then extend out to be zero 
at infinity, presumably by an inverse square law (as it's dB's - unless my 
physics is wrong).
It sounds horrible, but if you know the angle and value, could you not 
convert to cartesian co-ordinates and plot them?
Am I also right in thinking that the example you've given is MATLAB code 
where you have essentially 2 lists and a function?
So power=arange(-40,0,-10) is a list looking like this: [-40,-30,-20,-10,0]
theta is a list from 0 to 2pi increasing in increments of pi/12 and the 
function polar takes the power and theta value and returns... pass (would 
need to look up the function).
http://www.k0gkd.com/fd02.jpg <-- something like this at the end of the day 
is what is wanted - correct?

Now I'm not sure why you can't take your negative value and modulus it with 
40 (or whatever value you want at the center). So -40 becomes 40 becomes 0 
(the center), -30 becomes 30 becomes 10 (the next band out?)
At the end of the day it'll be the labels on the graph you need to change.

Tell me if this helps!
Dominic


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


Re: decorators - more than just syntactic sugar

2007-08-14 Thread BJörn Lindqvist
On 8/13/07, Bjoern Schliessmann
<[EMAIL PROTECTED]> wrote:
> BJörn Lindqvist wrote:
>
> > unpedagogically not separated from ordinary functions.
>
> Decorators _are_ ordinary functions. Remember the "syntactic sugar"
> in this thread?

Remember also "that syntactic sugar is important." Case in point, the
OP did not think of looking at the built-in functions page.

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


[half-off] LAMA - how to I use the news server with thunderbird

2007-08-14 Thread durumdara
Hi!

Is anyone knows about an NNTP servers that containing newsgroups about 
these lists:
- python win32 (python-win32)
- mod_python
- gimp-python
- gimp

I wanna set thes nntp servers in thunderbird so I need correct addresses.

Thanks for your help:
dd
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [half-off] LAMA - how to I use the news server with thunderbird

2007-08-14 Thread Laurent Pointal
durumdara a écrit :
> Hi!
> 
> Is anyone knows about an NNTP servers that containing newsgroups about 
> these lists:
>- python win32 (python-win32)
>- mod_python
>- gimp-python
>- gimp
> 
> I wanna set thes nntp servers in thunderbird so I need correct addresses.
> 
> Thanks for your help:
>dd

In my pythonfr/fr.comp.lang.python "Message de Bienvenue", I reference 
Gmane which mirror via nntp several Python related mailing lists, maybe 
you can find your hope there (or ask them to add mirrors for your 
interrest lists).

See http://news.gmane.org/index.php?prefix=gmane.comp.python

A+

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


Re: Module imports during object instantiation

2007-08-14 Thread Bruno Desthuilliers
Ritesh Raj Sarraf a écrit :
> Steve Holden wrote:

(snip)

>> What's leading you to conclude the import isn't being executed? You
>> realise, I trust, that the module's code will only be executed on the
>> first call to __init__()?
>>
> 
> Well. Putting it in a "try" inside __init__() doesn't do anything.

This would be highly suprising.

> The
> import never happens.

As soon as your running this code on a platform where os.name yields 
either 'nt' or 'dos', the import statement is executed. You can bet your 
ass on this. Now this import can fail for a lot of reasons (imported 
module not in sys.path, error in the imported module, etc), and since 
your catching *and dismissing* the ImportError, you don't know what 
*effectively* happens. It's like someone send you mails, you set your 
filter to trash mails from this person, and then complain this person 
never send you mails !-)

> And thus if I make a call in any of the methods, it
> fails with an error message. A NameError IIRC.

"IIRC" ? Inspecting the traceback may help, you know.

Anyway, there's a simple way to know what happens:

class Log:
 def __init__(self, verbose, lock = None):

 self.VERBOSE = bool(verbose)

 self.lock = bool(lock)
 if self.lock:
 self.dispLock = threading.Lock()
 else:
 self.dispLock = None

 if os.name == 'posix':
self.platform = 'posix'
self.color = get_colors()

 elif os.name in ['nt', 'dos']:
 self.platform = 'microsoft'

 try:
 import SomeModule
 except ImportError, e:
 # comment out next line before going to prod...
 print >> sys.stderr, e
 self.color = None
else:
 self.color = SomeModule.get_colors_windows()

 else:
 self.platform = None
 self.color = None


This should print the exact ImportError message. Which may help. IMHO.


>> You are right in assuming that __init__() is called once per instance
>> created, and it's legitimate to make an import conditional in the way
>> you have because of the "execute code only once" behavior - if the
>> module is already in sys.modules then it won't be re-imported, the
>> existing one will be used.
>>
> 
> This is what even my understanding is. But am afraid to say that this
> understanding is not implemented in Python. 

Do you *really* believe that no one would have noticed if something as 
important as the import mechanism was broken ?

(snip)
> Now I have some questions.
> 
> Going with your point of try/except imports at the top level, I am having
> multiple imports at the top level for the multiple classes that I have in
> the module. Not everything from the top level imports is required for the
> class Log (Say, just one module is what is required).
> So when I do a `from module import Log`, do all the modules at the  top
> level get imported?

Yes.

> My understanding says Yes, and if that's true, that's
> bad IMO. 

No, that's the right thing to do. When a module is loaded, all the 
top-level code is executed. period. How else would the class  and def 
statements be executed ?

FWIW, modules are supposed to have high cohesion. If you put unrelated 
things in a same module, then it's *your* design that's bad.

> My ultimate goal is to make all my classes as independent as possible while
> keeping them as lightweight as possible. If all top level module import
> statements are getting executed during a `from module import class`, this
> is _not_ lightweight IMO.

Since a module is only imported once, this should not be such a concern. 
It's obviously much more "lightweight" than going thru the import each 
time you instanciate the class, just to find out that the module is 
already imported.

But anyway, if two classes should be "totally" independant from each 
other, then what on earth are they doing in the same module ?

> That's what led me to try imports in __init__() but unfortunately I haven't
> seen that working for me even once.

"not working" is not a very useful description of a problem. The import 
mechanism works and it works fine. Your problem is elsewhere, but you 
didn't provide enough information for us to help you.
-- 
http://mail.python.org/mailman/listinfo/python-list


ctypes, windll question

2007-08-14 Thread Tzury
I followed the tutorial about ctypes and I still cannot figure out how
to call a method of a calss within the dll.

For example:
a dll named 'foo' contain a class named 'bar' which expose a method
named 'baz'.

if I either do:

mydll = windll.foo
mycls = mydll.bar

or
mycls = windll.foo.bar

or
mycls = windll.foo.bar()

I get an erros: "function 'bar' not found " which is true since while
bar is a class. Yet, I need to know how to create an instance of this
inner class so I can access its public methods.

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


Re: IDLE path browser not recognizing my PYTHONPATH

2007-08-14 Thread Martin v. Löwis
> I set PYTHONPATH to /home/me/bin in bash.bashrc, however the IDLE path
> browser is not recognizing this.  Not sure why.
> 
> Grateful for any insight.

The file "bash.bashrc" has no relevance. If you meant to set the
variable every time you start bash, put it into ".bashrc", in your
home directory. If that still doesn't work, type "env" before starting
idle, and inspect its output.

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


ctypes windll question

2007-08-14 Thread Tzury
I followed the tutorial about ctypes and I still cannot figure out how
to call a method of a calss within the dll.

For example:
a dll named 'foo' contain a class named 'bar' which expose a method
named 'baz'.

if I either do:

mydll = windll.foo
mycls = mydll.bar

or
mycls = windll.foo.bar

or
mycls = windll.foo.bar()

I get an erros: "function 'bar' not found " which is right, since bar
is a class and not a function. However, I still need to  create an
instance of this inner class (bar) so I can access its public method
(baz).

I cannot find anywhere instructions for that.

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


Re: Jython - variables are stored somehow

2007-08-14 Thread nmin
works perfect ... thanks a lot!

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


Re: Jython - problem import os

2007-08-14 Thread nmin
Thats it ...

Additionally I had to set the python path with sys.path.append to the
Lib folder .. and now it works perfect.

thanks a lot

Simon

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


Re: Assignments and Variable Substitution

2007-08-14 Thread Ali
On Aug 14, 12:45 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> Evan Klitzke wrote:
> > On 8/13/07, brad <[EMAIL PROTECTED]> wrote:
> >> I'd like to do something like this:
>
> >> var = '123'
> >> %s = [], %var

> And why would you want a variable whose name is '123'?

... and thus continues the search for private variables in Python.


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


python & MS Office

2007-08-14 Thread Michael S
http://msherman77.blogspot.com/2007/08/python-com.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Fast kNN from python

2007-08-14 Thread Janto Dreijer
Hi!

I am looking for a Python implementation or bindings to a library that
can quickly find k-Nearest Neighbors given an arbitrary distance
metric between objects. Specifically, I have an "edit distance"
between objects that is written in Python.

I haven't looked at the methods in detail but I think I'm looking for
one of the data structures listed on http://en.wikipedia.org/wiki/Metric_trees
(i.e. vp-trees, cover trees, m-trees or bk trees). But I might be
wrong. An approximate kNN would also work.

If there doesn't exist such an implementation yet, any advice on a
library I can wrap myself would also be appreciated.

Thanks!
Janto

PS Before anyone suggests it, I can't use the library at
http://www.cs.umd.edu/~mount/ANN/ as it assumes Minkowski distance
functions.

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


Re: Assignments and Variable Substitution

2007-08-14 Thread Bruno Desthuilliers
Ali a écrit :
> On Aug 14, 12:45 am, Steve Holden <[EMAIL PROTECTED]> wrote:
>> Evan Klitzke wrote:
>>> On 8/13/07, brad <[EMAIL PROTECTED]> wrote:
 I'd like to do something like this:
 var = '123'
 %s = [], %var
> 
>> And why would you want a variable whose name is '123'?
> 
> ... and thus continues the search for private variables in Python.

I must be tired, but I don't see what this has to do with "private" 
variables.

But if you want private variables, it's quite easy: prefix their names 
with a single underscore.

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


Re: Best programs written completly in Python

2007-08-14 Thread Skip Montanaro
On Aug 5, 5:14 am, Franz Steinhäusler <[EMAIL PROTECTED]>
wrote:
> Hello NG,
>
> wWhat are the best programs in your opinion, written entirly
> in pyhton, divided into categories like:
> a) Games
> b) Utilities/System
> c) Office
> d) Web/Newsreader/Mail/Browser
> ...

Not mentioned so far, here or on the Applications wiki page, is
SpamBayes,
an excellent spam filter: .  It supports
POP3 and
IMAP, and has a plugin for Outlook.  Another group has improved
SpamBayes
integration with Thunderbird by developing a TBird extension called
ThunderBayes.

Skip



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

Re: how to move cursor in Interactive Interpreter

2007-08-14 Thread yan . python
On 8 14 ,   2 44 , Peter Otten <[EMAIL PROTECTED]> wrote:
>  [EMAIL PROTECTED] wrote:
> > i  have a question.
> > when i run Interactive Interpreter in linux command promt,how can i
> > move the cursor.
> > for example,when i enter a string,i often enter the quotation mark ""
> > first,and the move the cursor inside the mark to enter the string,in
> > windows,it is ok.but when i do that in linux,pressing the "left" key
> > will just print "^[[D" in the screen ,but not what i want.
> > so , how can i move the cursor Interactive Interpreter in linux?
> >  i've googled and find nothing useful.who i tell me what to do?
>
> Python uses GNU readline for cursor movements. The Python version that ships
> with your distribution should work out of the box. If you compile Python
> yourself make sure that the development package (not just the binary) is
> installed. For Suse this is readline-devel.
>
> Peter

thanks for your reply
I thought maybe i just didn't install readline correctly,so i deleted
python and tried to re-compile the source code(I downloaded the .bz2
version).This time ,I found in the "./Modules/Setup" the description
for "readline":

# GNU readline. Unlike previous Python incarnations, GNU readline is
# now incorporated in an optional module, configured in the Setup
file
# instead of by a configure script switch. You may have to insert a
# -L option pointing to the directory where libreadline.* lives,
# and you may have to change -ltermcap to -ltermlib or perhaps remove
# it, depending on your system -- see the GNU readline instructions.
# It's okay for this to be a shared library, too.

#readline readline.c -lreadline -ltermcap

dont know exactly what to do,I just delete the "#" mark in the line
"#readline readline.c -lreadline -ltermcap " , then tried to
"configure","make",but errors of readline occor here.
what am i supposed to do to install the module GNU readline correctly
then?
thanks

by the way,my linux is Mandriva 10

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


Re: Module imports during object instantiation

2007-08-14 Thread Ritesh Raj Sarraf
Bruno Desthuilliers wrote:

>>> What's leading you to conclude the import isn't being executed? You
>>> realise, I trust, that the module's code will only be executed on the
>>> first call to __init__()?
>>>
>> 
>> Well. Putting it in a "try" inside __init__() doesn't do anything.
> 
> This would be highly suprising.
>

Yes, it is surprising. Unfortunately. :-(
Or maybe I'm doing something really dumb.
 
>> The
>> import never happens.
> 
> As soon as your running this code on a platform where os.name yields
> either 'nt' or 'dos', the import statement is executed. You can bet your
> ass on this. Now this import can fail for a lot of reasons (imported
> module not in sys.path, error in the imported module, etc), and since
> your catching *and dismissing* the ImportError, you don't know what
> effectively happens. It's like someone send you mails, you set your
> filter to trash mails from this person, and then complain this person
> never send you mails !-)
> 
>> And thus if I make a call in any of the methods, it
>> fails with an error message. A NameError IIRC.
> 
> "IIRC" ? Inspecting the traceback may help, you know.

There's no traceback because the import never happens.

Here's what I've captured for you exactly I see on my terminal


[EMAIL PROTECTED]:/tmp$ cat rick.py
class Log:
def __init__(self, verbose, lock = None):
self.VERBOSE = bool(verbose)
self.lock = bool(lock)

if self.lock:
self.dispLock = threading.Lock()
else:
self.dispLock = None

if os.name == 'posix':
try:
import foobar
except ImportError, e:
print >> sys.stderr, e

self.platform = 'posix'
self.color = get_colors()

elif os.name in ['nt', 'dos']:
self.platform = 'microsoft'
try:
import SomeModule
except ImportError, e:
# comment out next line before going to prod...
print >> sys.stderr, e

self.color = None
else:
self.color = SomeModule.get_colors_windows()
else:
self.platform = None
self.color = None
[EMAIL PROTECTED]:/tmp$ python
Python 2.4.4 (#2, Jul 21 2007, 11:00:24)
[GCC 4.1.3 20070718 (prerelease) (Debian 4.1.2-14)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, sys
>>> os.path.abspath(os.curdir)
'/tmp'
>>> from rick import Log
>>> import rick
>>> os.name
'posix'
>>> import foobar
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named foobar
>>>



For the 'posix' OS, I'm doing an erratic import which should fail and print
the error message.

See, it prints nothing. This _is_ what has made me conclude that imports
aren't executed in __init__(). But hey, they will get executed if you put
them in any of the methods (which is again illogical because methods
can/are called multiple times).

Ritesh
-- 
If possible, Please CC me when replying. I'm not subscribed to the list.

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


Re: ctypes windll question

2007-08-14 Thread Tzury
I discovered pywin32-210.win32-py2.5 package which does all the work
for me.

Open Software world is a great place to live by

On Aug 14, 12:45 pm, Tzury <[EMAIL PROTECTED]> wrote:
> I followed the tutorial about ctypes and I still cannot figure out how
> to call a method of a calss within the dll.
>
> For example:
> a dll named 'foo' contain a class named 'bar' which expose a method
> named 'baz'.
>
> if I either do:
>
> mydll = windll.foo
> mycls = mydll.bar
>
> or
> mycls = windll.foo.bar
>
> or
> mycls = windll.foo.bar()
>
> I get an erros: "function 'bar' not found " which is right, since bar
> is a class and not a function. However, I still need to  create an
> instance of this inner class (bar) so I can access its public method
> (baz).
>
> I cannot find anywhere instructions for that.


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


Re: Module imports during object instantiation

2007-08-14 Thread Neil Cerutti
On 2007-08-14, Ritesh Raj Sarraf <[EMAIL PROTECTED]> wrote:
> Bruno Desthuilliers wrote:
>
 What's leading you to conclude the import isn't being executed? You
 realise, I trust, that the module's code will only be executed on the
 first call to __init__()?

>>> 
>>> Well. Putting it in a "try" inside __init__() doesn't do anything.
>> 
>> This would be highly suprising.
>>
>
> Yes, it is surprising. Unfortunately. :-(
> Or maybe I'm doing something really dumb.
>  
>>> The
>>> import never happens.
>> 
>> As soon as your running this code on a platform where os.name yields
>> either 'nt' or 'dos', the import statement is executed. You can bet your
>> ass on this. Now this import can fail for a lot of reasons (imported
>> module not in sys.path, error in the imported module, etc), and since
>> your catching *and dismissing* the ImportError, you don't know what
>> effectively happens. It's like someone send you mails, you set your
>> filter to trash mails from this person, and then complain this person
>> never send you mails !-)
>> 
>>> And thus if I make a call in any of the methods, it
>>> fails with an error message. A NameError IIRC.
>> 
>> "IIRC" ? Inspecting the traceback may help, you know.
>
> There's no traceback because the import never happens.
>
> Here's what I've captured for you exactly I see on my terminal
>
>
> [EMAIL PROTECTED]:/tmp$ cat rick.py
> class Log:
> def __init__(self, verbose, lock = None):
> self.VERBOSE = bool(verbose)
> self.lock = bool(lock)
>
> if self.lock:
> self.dispLock = threading.Lock()
> else:
> self.dispLock = None
>
> if os.name == 'posix':
> try:
> import foobar
> except ImportError, e:
> print >> sys.stderr, e
>
> self.platform = 'posix'
> self.color = get_colors()
>
> elif os.name in ['nt', 'dos']:
> self.platform = 'microsoft'
> try:
> import SomeModule
> except ImportError, e:
> # comment out next line before going to prod...
> print >> sys.stderr, e
>
> self.color = None
> else:
> self.color = SomeModule.get_colors_windows()
> else:
> self.platform = None
> self.color = None
> [EMAIL PROTECTED]:/tmp$ python
> Python 2.4.4 (#2, Jul 21 2007, 11:00:24)
> [GCC 4.1.3 20070718 (prerelease) (Debian 4.1.2-14)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 import os, sys
 os.path.abspath(os.curdir)
> '/tmp'
 from rick import Log
 import rick
 os.name
> 'posix'
 import foobar
> Traceback (most recent call last):
>   File "", line 1, in ?
> ImportError: No module named foobar

>
>
>
> For the 'posix' OS, I'm doing an erratic import which should fail and print
> the error message.
>
> See, it prints nothing. This _is_ what has made me conclude
> that imports aren't executed in __init__(). But hey, they will
> get executed if you put them in any of the methods (which is
> again illogical because methods can/are called multiple times).

If you want an import inside an __init__ to run, you must call
the __init__ function that contains it.

>>> log = rick.Log()

You'll get another surprise when you do this, though. ;)

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


Opinions about this new Python book?

2007-08-14 Thread Dick Moores
I'd appreciate opinions about this new Python book.

Title: Python Power!: The Comprehensive Guide
Author:  Matt Telles
Publisher:  Course Technology
Pub. Date:  Jul 27, 2007
Edition:  1st edition
Binding:  Paperback
Pages:  508
ISBN:  1598631586
List Price:  34.99 USD

The book on the publisher's website: 

And at BestBookDeal.com:
< http://www.bestbookdeal.com/book/compare/1598631586>

Thanks,

Dick Moores 

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


Re: Drawing a graph

2007-08-14 Thread Larry Bates
Ghirai wrote:
> Hello list,
> 
> I need to draw a graph, 2 axes, 2D, nothing fancy.
> One of the axes is time, the other one is a series of integers.
> 
> I don't care much about the output format.
> 
> Are there any specialized libraries for this, or should i use PIL?
> 
> Thanks.
> 
ReportLab graphics works for me.

www.reportlab.org

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


Re: chmod g+ Equivalent

2007-08-14 Thread milan_sanremo
On Aug 13, 8:06 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> milan_sanremo wrote:
> > I've read the documentation on os.chmod() and can implement all the
> > standard commands, but what is the syntax for the equivalent of chmod g
> > + to set the group id?
>
> I assume when you say "to set the group id" you actually mean "to assert
> the setgid bit"? I further presume that when you say "chmod g+" you
> actually mean "chmod g+s".

The g+s was an omission on my part.  I can see how it would confuse
the issue.

I'm not sure if I mean "to assert the setgid bit".  My SUN docs refer
to it being 'on'.
http://docs.sun.com/app/docs/doc/819-3321/6n5i4b767?l=en&a=view&q=setgid+bit

>
> You can't have read the documentation very thoroughly. It says right at
> the top:
>
> S_ISUID
> S_ISGID

I did see this in the documentation:

Change the mode of path to the numeric mode. mode may take one of the
following values (as defined in the stat module) or bitwise or-ed
combinations of them:

* S_ISUID
* S_ISGID

Which refers to:
http://docs.python.org/lib/module-stat.html

After which it was still unclear.

My question is in the command os.chmod(myDirectory, ?) what is the
value for ? to turn on the setgid bit.

Contrary to your presumption, I did read the documentation
thoroughly.  It is inability to understand the concept which prompted
me to post the question here.

>
> Of course, your process needs to have root privilege in order to be able
> to do that.
>
> regards
>   Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenweb  http://del.icio.us/steve.holden
> --- Asciimercial --
> Get on the web: Blog, lens and tag the Internet
> Many services currently offer free registration
> --- Thank You for Reading -


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


LEGB rule, totally confused ...

2007-08-14 Thread stef mientki
hello,

I've thought many times I finally understood the import / namespace rules,
but again I'm totally lost :-(

This is my library file

# Module lib_test.py

X = 1

def Init():
global X
X = 3
print 'Init', X

def Run ():
print X <=== UnboundLocalError: local variable
'X' referenced before assignment
X = X + 1
print ' Run', X



And this my main program in another file:

import lib_test
lib_test.Init()
print lib_test.X

lib_test.Run()
print lib_test.X

Why do I get the error ?
Printing isn't assigning anything or am I missing something.
Now if I remove "X = X + 1" I don't get an error ???
Is this a problem of the traceback procedure or the IDE,
or is Python not completely an interpreter, that reads line by line ???

Please explain this to me.

thanks,
Stef Mientki


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


Script to copy database

2007-08-14 Thread Tony
I'm new at this and would like to know how set up a script to copy a 
database from a local computer to a network at a certain time everyday. 
Should be simple enough, but, as of now I am unfamiliar with how to do this. 
Would this be done by writing a script and setting up a  scheduled task to 
run the script?  Can anyone help me with the script?  Just need it to copy 
an Access database from the local C: drive to a network F: drive.

Thanks,
Tony 


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


Re: JPype - passing to Java main

2007-08-14 Thread unlikeablePorpoise
>
> Try this:
> com.JPypeTest.main("arg")
>
> Ian

Thanks for your suggestion, but it doesn't work (produces an error).

Does anybody else have any ideas?

Thanks,
Sarah

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


Re: wxPython before MainLoop

2007-08-14 Thread Chris Mellon
On 8/13/07, [david] <[EMAIL PROTECTED]> wrote:
> Well yes, I have tried this app with native windows,
> and I know how to do it.
>

I don't believe you. If you meant "I copied something that does this
off of code project", that I'll believe.

> But if all wxPython can offer is a poor imitation
> of MFC, I'm better off using MFC aren't I?
>

MFC offers no special support at all for anything you're doing.
wxPython actually does have some, but that may or may not be helpful
since you haven't been exactly clear as to what your needs are (Show()
should never be slow, and if it is you're doing something wrong) and
you've got an egregiously bad attitude that cuts my interest in
helping you down rather a lot.

> And too all those people who wrote back to insist
> that users MUST explicitly build a multi-threaded
> framework for wxPython:
>
> It's supposed to already be a framework :~)
>

wxPython doesn't *need* a multi-threading framework. It's got a
threadsafe way to schedule events, and the Python standard library has
all the other synchronization primitives you need, including a queue.
There's nothing special that needs to be done to it. Nobody told you
to "build a multi-threaded framework", they told you to use the
threading framework which already exists.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Opinions about this new Python book?

2007-08-14 Thread kyosohma
On Aug 14, 7:05 am, Dick Moores <[EMAIL PROTECTED]> wrote:
> I'd appreciate opinions about this new Python book.
>
> Title: Python Power!: The Comprehensive Guide
> Author:  Matt Telles
> Publisher:  Course Technology
> Pub. Date:  Jul 27, 2007
> Edition:  1st edition
> Binding:  Paperback
> Pages:  508
> ISBN:  1598631586
> List Price:  34.99 USD
>
> The book on the publisher's website: 
>
> And at BestBookDeal.com:
> 
>
> Thanks,
>
> Dick Moores

I just got this book over the weekend. I'll start reading/skimming
through it this week and hopefully remember to get back to you. By the
way, why do you want to know?

Mike

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


Class problems.

2007-08-14 Thread special_dragonfly
Hello,
I'm having problems retrieving data I think I've put into my program. I have 
a class and a function. I'm reading in from a personally made text file of 
the data needed for the class. The FieldsDictionary needs to be accesable 
outside the function, but my problem is this:
the print FieldsDictionary[key].Fieldname (which I should have just created 
because of the line above), returns:
AttributeError: 'list' object has no attribute 'Fieldname'
am I just accessing it wrongly?
I was under the impression that Fields Dictionary should contain a key 
referencing to a list of instances of the class. i.e. 
FieldsDictionary{key:[instance1, instance2, instance 3]}
Is this not what I've programmed?

class FieldClass(object):
def 
__init__(self,Fieldname="",Fieldlength=0,Type=["A","S","N"],Location=["D","C","L","H","TBA"]):
self.Fieldname=Fieldname
self.Fieldlength=Fieldlength
self.Type=Type
self.Location=Location

def 
EnterDictionary(FieldsDictionary,key,myfile,FIELD_QUANTITY_OFFSET,LINE_START,LINE_END):
data=myfile.readline().strip()
for i in range(int(data[FIELD_QUANTITY_OFFSET:])):
args =myfile.readline().strip()[LINE_START:LINE_END].split(",")
print args
FieldsDictionary.setdefault(key, []).append(FieldClass(*args))
print FieldsDictionary[key].Fieldname 


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


Re: JPype - passing to Java main

2007-08-14 Thread Laurent Pointal
[EMAIL PROTECTED] a écrit :
>> Try this:
>> com.JPypeTest.main("arg")
>>
>> Ian
> 
> Thanks for your suggestion, but it doesn't work (produces an error).

This is where you should have copy/pasted the error.

;-)

> 
> Does anybody else have any ideas?

Sorry, no.

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


Re: Icons for GUI development

2007-08-14 Thread Uwe Grauer
Benjamin wrote:
> I'm developing a mail client. Since GUI are usually improved with some
> icons, I'm looking for some. Because I'm not a very gifted artist I'm
> searching for a library of GPL or public domain icons. Any suggestions?
> 

http://tango.freedesktop.org/Tango_Icon_Library
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fast kNN from python

2007-08-14 Thread Tim Churches
Janto Dreijer wrote:
> I am looking for a Python implementation or bindings to a library that
> can quickly find k-Nearest Neighbors given an arbitrary distance
> metric between objects. Specifically, I have an "edit distance"
> between objects that is written in Python.

Orange? See http://www.ailab.si/orange/ - not sure about speed, but
quite a few parts of it are written in C, and it does kNN.

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


Re: Script to copy database

2007-08-14 Thread Laurent Pointal
Tony a écrit :
> I'm new at this and would like to know how set up a script to copy a 
> database from a local computer to a network at a certain time everyday. 
> Should be simple enough, but, as of now I am unfamiliar with how to do this. 
> Would this be done by writing a script and setting up a  scheduled task to 
> run the script?  Can anyone help me with the script?  Just need it to copy 
> an Access database from the local C: drive to a network F: drive.
> 
> Thanks,
> Tony 
> 
> 

As you wrote about c: and f:, I imagine you are working under Windows.
IMHO you dont need Python for that.

domybackup.bat

copy c:\mypathtothefile\thefile.xxx F:\mypathdobackudir\


And use your "planificateur de taches" (its corresponding english 
control panel) to setup a periodic call to this batch file, eventually 
associate an ad-hoc account to the task, so that the batch can access 
the file to backup.


If you need more (ie. network access to setup/clean), here is a copy of 
a script I use to export (using a Python script) an Access database. 
Just replace the call to the Python script by a simple call to copy xxx 
.



@echo off
REM LANCEMENT DE L'EXPORT DE LA BASE ADMINISTRATIVE EN MODE TACHE
REM DE FOND (BATCH).

SET EXPORTS_BATCH=1
REM Parametres pour se connecter a la machine de transfert.
SET EXPORTS_HOST=thecomputer
SET EXPORTS_SHARE=data
SET EXPORTS_DRIVE=O:
SET EXPORTS_USER=theremotuser
SET EXPORTS_PASSWD=theremotepasswd
REM Montage du volume.
REM le start pour permettre d'attendre que le montage soit effectif.
START /wait NET USE %EXPORTS_DRIVE% \\%EXPORTS_HOST%\%EXPORTS_SHARE% 
%EXPORTS_PASSWD% /USER:%EXPORTS_USER% /PERSISTENT:No
IF ERRORLEVEL 1 GOTO erreur_montage

REM Parametres pour le script Python.
SET SCRIPT_EXPORT="C:\Documents and Settings\myaccount\My 
Documents\mybexport.py"
SET DSN_BASE_ADMIN=mydbaccound
SET LOGIN_BASE_ADMIN=mydbpasswd
SET PATH_FICHIERS_EXPORTS=%EXPORTS_DRIVE%\
REM Variables d'environnement eventuellement utiles...
SET TEMP=%PATH_FICHIERS_EXPORTS%
SET TMP=%PATH_FICHIERS_EXPORTS%
REM Lancement du script Python qui realise l'export.
C:\Tools\Python24\python.exe %SCRIPT_EXPORT%

REM Deconnexion du volume.
NET USE %EXPORTS_DRIVE% /DELETE

goto termine

:erreur_montage
ECHO "Erreur %ERROR_LEVEL% au montage de 
\\%EXPORTS_HOST%\%EXPORTS_SHARE% en lecteur %EXPORTS_DRIVE%."

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


Re: Class problems.

2007-08-14 Thread special_dragonfly
Just ignore this, I was being an idiot...

"special_dragonfly" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hello,
> I'm having problems retrieving data I think I've put into my program. I 
> have a class and a function. I'm reading in from a personally made text 
> file of the data needed for the class. The FieldsDictionary needs to be 
> accesable outside the function, but my problem is this:
> the print FieldsDictionary[key].Fieldname (which I should have just 
> created because of the line above), returns:
> AttributeError: 'list' object has no attribute 'Fieldname'
> am I just accessing it wrongly?
> I was under the impression that Fields Dictionary should contain a key 
> referencing to a list of instances of the class. i.e. 
> FieldsDictionary{key:[instance1, instance2, instance 3]}
> Is this not what I've programmed?
>
> class FieldClass(object):
>def 
> __init__(self,Fieldname="",Fieldlength=0,Type=["A","S","N"],Location=["D","C","L","H","TBA"]):
>self.Fieldname=Fieldname
>self.Fieldlength=Fieldlength
>self.Type=Type
>self.Location=Location
>
> def 
> EnterDictionary(FieldsDictionary,key,myfile,FIELD_QUANTITY_OFFSET,LINE_START,LINE_END):
>data=myfile.readline().strip()
>for i in range(int(data[FIELD_QUANTITY_OFFSET:])):
>args =myfile.readline().strip()[LINE_START:LINE_END].split(",")
>print args
>FieldsDictionary.setdefault(key, []).append(FieldClass(*args))
>print FieldsDictionary[key].Fieldname
> 


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


Re: LEGB rule, totally confused ...

2007-08-14 Thread Diez B. Roggisch
stef mientki wrote:

> hello,
> 
> I've thought many times I finally understood the import / namespace rules,
> but again I'm totally lost :-(
> 
> This is my library file
> 
> # Module lib_test.py
> 
> X = 1
> 
> def Init():
> global X
> X = 3
> print 'Init', X
> 
> def Run ():
> print X <=== UnboundLocalError: local variable
> 'X' referenced before assignment
> X = X + 1
> print ' Run', X
> 
> 
> 
> And this my main program in another file:
> 
> import lib_test
> lib_test.Init()
> print lib_test.X
> 
> lib_test.Run()
> print lib_test.X
> 
> Why do I get the error ?
> Printing isn't assigning anything or am I missing something.
> Now if I remove "X = X + 1" I don't get an error ???
> Is this a problem of the traceback procedure or the IDE,
> or is Python not completely an interpreter, that reads line by line ???
> 
> Please explain this to me.

This are the scoping-rules of python. A variable name on the left side of an
name-binding/assignment operator (including augmented assignments, vulgo:
+= and brothers) will make the variable name a function-local.

So 

x = 10
def foo():
   print x
   x = 100

makes x a local variable to foo, which of course can't be accessed in 

print x

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


Re: Assignments and Variable Substitution

2007-08-14 Thread brad
Steve Holden wrote:
> Evan Klitzke wrote:
>> On 8/13/07, brad <[EMAIL PROTECTED]> wrote:
>>> I'd like to do something like this:
>>>
>>> var = '123'
>>> %s = [], %var
>>>
>>> So that, in the end, var is '123' and an empty list is named '123' as
>>> well. The list assignments are created during a loop.
>>
>> You can't assign a variable whose name is 123, but you can do this
>> sort of thing with setattr.
>>
> And why would you want a variable whose name is '123'?

Just an example.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: LEGB rule, totally confused ...

2007-08-14 Thread Laurent Pointal
stef mientki a écrit :
> hello,
> 
> I've thought many times I finally understood the import / namespace rules,
> but again I'm totally lost :-(
> 
> This is my library file
> 
># Module lib_test.py
> 
>X = 1
> 
>def Init():
>global X
>X = 3
>print 'Init', X
> 
>def Run ():
>print X <=== UnboundLocalError: local variable
>'X' referenced before assignment
>X = X + 1
>print ' Run', X
> 
> 
> 
> And this my main program in another file:
> 
>import lib_test
>lib_test.Init()
>print lib_test.X
> 
>lib_test.Run()
>print lib_test.X
> 
> Why do I get the error ?
> Printing isn't assigning anything or am I missing something.

If you use a global to *modify* it, you MUST declare "global X", either 
Python consider using a local.
So for your error: at compile time, in Run(), it see that it must use a 
local X (because you set it) and generate ad-hoc bytecode, but when 
running X is not defined locally, so the error.

> Now if I remove "X = X + 1" I don't get an error ???

If you remove the "X =..." statement, then the compiler dont know 
a-priori if its local or global, so it search X in both namespaces.

> Is this a problem of the traceback procedure or the IDE,
> or is Python not completely an interpreter, that reads line by line ???

Its compiled to buyte-code then interpreted from the byte-code.

> 
> Please explain this to me.
> 
> thanks,
> Stef Mientki

A+

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


Re: JPype - passing to Java main

2007-08-14 Thread unlikeablePorpoise
Good point Laurent. Here is the error produced when I try to access
main() using
'com.JPypeTest.main("arg")'

The original code is pasted at the top of this thread. I only added
'com.JPypeTest.main("arg")' which causes the error below

-ERROR_-
  File "tester.py", line 10, in 
com.JPypeTest.main("arg")
RuntimeError: No matching overloads found. at src/native/common/
jp_method.cpp:121
--END ERROR-

Thanks,
Sarah

On Aug 14, 8:03 am, Laurent Pointal <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] a écrit :
>
> >> Try this:
> >> com.JPypeTest.main("arg")
>
> >> Ian
>
> > Thanks for your suggestion, but it doesn't work (produces an error).
>
> This is where you should have copy/pasted the error.
>
> ;-)
>
>
>
> > Does anybody else have any ideas?
>
> Sorry, no.


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

Re: how to move cursor in Interactive Interpreter

2007-08-14 Thread Peter Otten
 [EMAIL PROTECTED] wrote:

> what am i supposed to do to install the module GNU readline correctly
> then?

> by the way,my linux is Mandriva 10

Use the package manager of your distribution to install the readline
development package -- after some struggle with Mandriva's website I came
to suppose that it's libreadline5-devel for you:

urpmi libreadline5-devel.rpm

After you have successfully installed that package unpack the python archive
into a fresh directory and do the configure/make/install dance. No manual
changes should be necessary.

Peter

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


Re: Class problems.

2007-08-14 Thread Diez B. Roggisch
special_dragonfly wrote:

> Hello,
> I'm having problems retrieving data I think I've put into my program. I
> have a class and a function. I'm reading in from a personally made text
> file of the data needed for the class. The FieldsDictionary needs to be
> accesable outside the function, but my problem is this:
> the print FieldsDictionary[key].Fieldname (which I should have just
> created because of the line above), returns:
> AttributeError: 'list' object has no attribute 'Fieldname'
> am I just accessing it wrongly?
> I was under the impression that Fields Dictionary should contain a key
> referencing to a list of instances of the class. i.e.
> FieldsDictionary{key:[instance1, instance2, instance 3]}
> Is this not what I've programmed?
> 
> class FieldClass(object):
> def
>
__init__(self,Fieldname="",Fieldlength=0,Type=["A","S","N"],Location=["D","C","L","H","TBA"]):
> self.Fieldname=Fieldname
> self.Fieldlength=Fieldlength
> self.Type=Type
> self.Location=Location
> 
> def
>
EnterDictionary(FieldsDictionary,key,myfile,FIELD_QUANTITY_OFFSET,LINE_START,LINE_END):
> data=myfile.readline().strip()
> for i in range(int(data[FIELD_QUANTITY_OFFSET:])):
> args =myfile.readline().strip()[LINE_START:LINE_END].split(",")
> print args
> FieldsDictionary.setdefault(key, []).append(FieldClass(*args))

Here you create a list or expect one, and append a new FieldClass-object to
it.
> print FieldsDictionary[key].Fieldname

Here you access the LIST, but then expect it to be a FieldClass-object?!? 

print FieldsDictionary[key][-1].Fieldname

will work.

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


Re: LEGB rule, totally confused ...

2007-08-14 Thread Neil Cerutti
On 2007-08-14, stef mientki <[EMAIL PROTECTED]> wrote:
> I've thought many times I finally understood the import /
> namespace rules, but again I'm totally lost :-(
>
> This is my library file
>
> # Module lib_test.py
>
> X = 1
>
> def Init():
> global X
> X = 3
> print 'Init', X
>
> def Run ():
> print X <=== UnboundLocalError: local variable
> 'X' referenced before assignment
> X = X + 1
> print ' Run', X

>From _Python Language Reference Manual_ see: '4.1 Naming and
Binding' and '6.13 The global statement'.

  If a name is bound [assigned] in a block, it is a local
  variable of that block.

  ...

  The global statement is a declaration which holds for the
  entire current code block. It means that the listed identifiers
  are to be interpreted as globals. It would be impossible to
  assign to a global variable without global, although free
  variables may refer to globals without being declared global. 

Since your Init and Run functions both assign (bind) a value to
X, X is assumed to be a local variable unless you say otherwise
with a global statement.

Note that the global statement in Init applies only in Init's
code block. Run must have it's own 'global X' statement, if
applicable.

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


Re: Script to copy database

2007-08-14 Thread Tony
Thanks Laurent.  That was very helpful.  Pretty easy too.

Thanks again for your help.
Tony



"Laurent Pointal" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Tony a écrit :
>> I'm new at this and would like to know how set up a script to copy a 
>> database from a local computer to a network at a certain time everyday. 
>> Should be simple enough, but, as of now I am unfamiliar with how to do 
>> this. Would this be done by writing a script and setting up a  scheduled 
>> task to run the script?  Can anyone help me with the script?  Just need 
>> it to copy an Access database from the local C: drive to a network F: 
>> drive.
>>
>> Thanks,
>> Tony
>
> As you wrote about c: and f:, I imagine you are working under Windows.
> IMHO you dont need Python for that.
>
> domybackup.bat
>
> copy c:\mypathtothefile\thefile.xxx F:\mypathdobackudir\
>
>
> And use your "planificateur de taches" (its corresponding english control 
> panel) to setup a periodic call to this batch file, eventually associate 
> an ad-hoc account to the task, so that the batch can access the file to 
> backup.
>
>
> If you need more (ie. network access to setup/clean), here is a copy of a 
> script I use to export (using a Python script) an Access database. Just 
> replace the call to the Python script by a simple call to copy xxx .
>
>
>
> @echo off
> REM LANCEMENT DE L'EXPORT DE LA BASE ADMINISTRATIVE EN MODE TACHE
> REM DE FOND (BATCH).
>
> SET EXPORTS_BATCH=1
> REM Parametres pour se connecter a la machine de transfert.
> SET EXPORTS_HOST=thecomputer
> SET EXPORTS_SHARE=data
> SET EXPORTS_DRIVE=O:
> SET EXPORTS_USER=theremotuser
> SET EXPORTS_PASSWD=theremotepasswd
> REM Montage du volume.
> REM le start pour permettre d'attendre que le montage soit effectif.
> START /wait NET USE %EXPORTS_DRIVE% \\%EXPORTS_HOST%\%EXPORTS_SHARE% 
> %EXPORTS_PASSWD% /USER:%EXPORTS_USER% /PERSISTENT:No
> IF ERRORLEVEL 1 GOTO erreur_montage
>
> REM Parametres pour le script Python.
> SET SCRIPT_EXPORT="C:\Documents and Settings\myaccount\My 
> Documents\mybexport.py"
> SET DSN_BASE_ADMIN=mydbaccound
> SET LOGIN_BASE_ADMIN=mydbpasswd
> SET PATH_FICHIERS_EXPORTS=%EXPORTS_DRIVE%\
> REM Variables d'environnement eventuellement utiles...
> SET TEMP=%PATH_FICHIERS_EXPORTS%
> SET TMP=%PATH_FICHIERS_EXPORTS%
> REM Lancement du script Python qui realise l'export.
> C:\Tools\Python24\python.exe %SCRIPT_EXPORT%
>
> REM Deconnexion du volume.
> NET USE %EXPORTS_DRIVE% /DELETE
>
> goto termine
>
> :erreur_montage
> ECHO "Erreur %ERROR_LEVEL% au montage de \\%EXPORTS_HOST%\%EXPORTS_SHARE% 
> en lecteur %EXPORTS_DRIVE%."
>
> :termine 


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

Re: Fast kNN from python

2007-08-14 Thread Janto Dreijer
On Aug 14, 3:11 pm, Tim Churches <[EMAIL PROTECTED]> wrote:
> Janto Dreijer wrote:
> > I am looking for a Python implementation or bindings to a library that
> > can quickly find k-Nearest Neighbors given an arbitrary distance
> > metric between objects. Specifically, I have an "edit distance"
> > between objects that is written in Python.
>
> Orange? Seehttp://www.ailab.si/orange/- not sure about speed, but
> quite a few parts of it are written in C, and it does kNN.
>
> Tim C

Thanks, but I'm actually thinking of "fast" as in computer science
terms. e.g. O(log(n)) lookup time. I'll probably have tens of
thousands of objects to search and the distance calculation is
relatively slow.

>From the documentation it looks like Orange does a brute force search
for the nearest k items.

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


Question about FutureWarning

2007-08-14 Thread Steven W. Orr
I have module M1 which has the following line in it:

   StartTime   = safe_dict_get ( dic, 'starttime', 0x )

It gets imported by modules M2 and M3. And finally, M4 imports both M2 and 
M3.

M4
  |\M3
  | |\M1
  |\M2
  | |\M1

I'm building a .deb file which means I have to compile the modules into 
.pyc and .pyo files.

The compile command I use is

python=/usr/bin/python2.3
i_python ()
{
 $python -c "import $1"
 $python -O -c "import $1"
}
i_python M1
i_python M2
i_python M3
i_python M4

When M1 is compiled, there's no problem. The same for when I compile M2 
and M3. But when M4 is compiled, I get the following message:

M1.py:268: FutureWarning: hex/oct constants > sys.maxint will 
return positive values in Python 2.4 and up
   StartTime   = safe_dict_get ( dic, 'starttime', 0x )

I get the message twice, ostensibly because of M3 and M2.

I was able to shut off the warning by adding the following lines *before* 
the import in M4.

import warnings
warnings.filterwarnings('ignore', category=FutureWarning)

My question is this: Why can the warning not be shut off by putting the 
two lines in M1?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Module imports during object instantiation

2007-08-14 Thread Ritesh Raj Sarraf
Neil Cerutti wrote:

> If you want an import inside an __init__ to run, you must call
> the __init__ function that contains it.

Doesn't __init__ get called automatically ?
I thought __init__ was required to be called explicitly only when you were
doing inheritance and wanted to pass separate values to the base class.

Ritesh
-- 
If possible, Please CC me when replying. I'm not subscribed to the list.

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


Re: (sort of) deterministic timing in Python

2007-08-14 Thread Hendrik van Rooyen
"John Fisher"  wrote:

import time
period_time = TIME_CONSTANT  # The time of a period in seconds - 0.001 is a
millisec

>mark start time

start_time = time.time()

>start event
>event finishes

event_time = time.time() - start_time
wait_time = period_time-event_time

>count time until next interval

if wait_time > 0:
time.sleep(wait_time)

>start second event…

that should (sort of) do it.

HTH - Hendrik


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

Re: Script to copy database

2007-08-14 Thread brad
Laurent Pointal wrote:
> As you wrote about c: and f:, I imagine you are working under Windows.
> IMHO you dont need Python for that.

Unless you need error handling, reporting, etc.

Bat scripts only go so far.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Module imports during object instantiation

2007-08-14 Thread Neil Cerutti
On 2007-08-14, Ritesh Raj Sarraf <[EMAIL PROTECTED]> wrote:
> Neil Cerutti wrote:
>
>> If you want an import inside an __init__ to run, you must call
>> the __init__ function that contains it.
>
> Doesn't __init__ get called automatically ?

It gets called automatically when you construct an instance of
the class in which it's defined.

> I thought __init__ was required to be called explicitly only
> when you were doing inheritance and wanted to pass separate
> values to the base class.

You don't have to call it explicitly to get it to run.

-- 
Neil Cerutti
Customers who consider our waitresses uncivil ought to see the manager --sign
at New York restaurant
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to move cursor in Interactive Interpreter

2007-08-14 Thread yan . python
On 8 14 ,   9 20 , Peter Otten <[EMAIL PROTECTED]> wrote:
>  [EMAIL PROTECTED] wrote:
> > what am i supposed to do to install the module GNU readline correctly
> > then?
> > by the way,my linux is Mandriva 10
>
> Use the package manager of your distribution to install the readline
> development package -- after some struggle with Mandriva's website I came
> to suppose that it's libreadline5-devel for you:
>
> urpmi libreadline5-devel.rpm
>
> After you have successfully installed that package unpack the python archive
> into a fresh directory and do the configure/make/install dance. No manual
> changes should be necessary.
>
> Peter



i've re-install python as you said,and it works now
i really appreciate your help
thanks!

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


Re: Icons for GUI development

2007-08-14 Thread Jason
On Aug 13, 8:22 pm, Benjamin <[EMAIL PROTECTED]> wrote:
> I'm developing a mail client. Since GUI are usually improved with some
> icons, I'm looking for some. Because I'm not a very gifted artist I'm
> searching for a library of GPL or public domain icons. Any suggestions?

Try out the Silk icon set, too.
http://www.famfamfam.com/lab/icons/silk/

  --Jason

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


Re: Script to copy database

2007-08-14 Thread kyosohma
On Aug 14, 7:30 am, "Tony" <[EMAIL PROTECTED]> wrote:
> I'm new at this and would like to know how set up a script to copy a
> database from a local computer to a network at a certain time everyday.
> Should be simple enough, but, as of now I am unfamiliar with how to do this.
> Would this be done by writing a script and setting up a  scheduled task to
> run the script?  Can anyone help me with the script?  Just need it to copy
> an Access database from the local C: drive to a network F: drive.
>
> Thanks,
> Tony

You could use Python's shutil module too!

Mike

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


Callback functions with httplib.HTTPSConnection

2007-08-14 Thread David Morris
Is there a way to give a progress or status message while a file it
uploading using httplib.HTTPSConnection? Here is some sample code that I
would like to add a progress message to when run from the commandline:

server = httplib.HTTPSConnection(upload_host)
 server.request('POST', upload_uri, body, headers)
 resp = server.getresponse()
 server.close()

 if resp.status == 201:
   location = resp.getheader('Location', None)
 else:
   location = None
 return resp.status, resp.reason, location

It looks like ftplib has support for callback functions for things like
listing the contents of a directory, but I don't see callback support
anywhere in httplib. Would it only be possible to show an estimated duration
based on file size, or would the better answer be to break the file up into
chunks? I'm pretty new to Python, so I'm not quite sure how to handle
something like this...

Thanks for the help,

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

Re: Python script for mobile platforms -- suggested?

2007-08-14 Thread Robert Dailey
Hi Jay,

I apologize for not having been detailed enough. Right now I'm using a C++
library known as TinyXML to parse my XML files. When a menu is to be
displayed, the XML is parsed and the appropriate images, text, etc that will
display on the menu is loaded based on the data in that XML. Note that the
XML parsing happens before the menu is drawn and only happens once per menu
as to avoid performance overhead during the menu drawing.

For example, to create a menu that has an image in the center of the screen,
the XML would be this:










The "Origin" and "Justification" elements act sort of like function calls,
and the "Frame" element defines an "Object" kind of. Each Frame is a visual
element in the Menu.

I'm not sure if you'll agree or not, but even in this simple example it's
very hard to read just given the nature of the XML syntax. Secondly, I'm not
using XML as it was intended to be used. I'm using it as a script instead of
a representation of data. Most of the real menus are 600+ lines of XML much
like above, however it is not nearly as simplistic. I will paste a real
example of a menu below this email for those curious to look at it.

I haven't decided on what the Python version of the example above would look
like, that would probably happen sometime after I decided to go with Python
for a menu scripting replacement (If I do, that is). I might mix XML and
Python much like World of Warcraft mixes XML with LUA script. Again, this
all depends on design. The important points I wanted to get across is that
the Python script wont' be executed past the construction of a menu. The
Python/XML script would be simply there to allow the game to create the menu
and other important things.

I hope I've given enough examples and details. If I haven't, please let me
know and I'll answer any questions you may have. Thanks for following up.

On 8/13/07, Jay Loden <[EMAIL PROTECTED]> wrote:
>
> Robert Dailey wrote:
> > I'm currently developing a game for a cell phone. The game has a GUI
> > system that's currently using XML to define the individual menus.
> > Basically this means that for every single menu the user goes to, it
> > loads and parses an XML file. Would using Python Script instead of
> > XML be a reasonable replacement, or would it be even slower? I've
> > read various articles online but I'm still curious to hear what
> > everyone has to say here.
>
> A number of questions come to mind...for starters:
>
> 1) What is parsing the XML now? C code? Python?
> 2) What is the proposed python script supposed to do when they load the
> menu? without knowing that or seeing some sample code or details, that's an
> impossible question to answer, since an arbitrary Python script might take
> milliseconds, seconds, hours, or days to complete running.
>
> It might help if you give a concrete example (code is always welcome!) and
> explained exactly what the options are that you're considering and why. Then
> the folks on the list can try to give you a rough estimate or possibly
> suggest alternative methods you may not have considered.
>
> -Jay
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Opinions about this new Python book?

2007-08-14 Thread Dick Moores
At 05:57 AM 8/14/2007, [EMAIL PROTECTED] wrote:
>On Aug 14, 7:05 am, Dick Moores <[EMAIL PROTECTED]> wrote:
> > I'd appreciate opinions about this new Python book.
> >
> > Title: Python Power!: The Comprehensive Guide
> > Author:  Matt Telles
> > Publisher:  Course Technology
> > Pub. Date:  Jul 27, 2007
> > Edition:  1st edition
> > Binding:  Paperback
> > Pages:  508
> > ISBN:  1598631586
> > List Price:  34.99 USD
> >
> > The book on the publisher's website: 
> >
> > And at BestBookDeal.com:
> > 
> >
> > Thanks,
> >
> > Dick Moores
>
>I just got this book over the weekend. I'll start reading/skimming
>through it this week and hopefully remember to get back to you.

Thanks!

>  By the
>way, why do you want to know?

If the experts like it, I'll buy it.

Dick


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


module: zipfile.writestr - line endings issue

2007-08-14 Thread towers

Hi

I'm probably doing something stupid but I've run into a problem
whereby I'm trying to add a csv file to a zip archive - see example
code below.

The csv just has several rows with carriage return line feeds (CRLF).

However after adding it to an archive and then decompressing the line
endings have been converted to just line feeds (LF).

Does anyone know if this is a bug or am I just doing something wrong?

Many Thanks,
Damon


import zipfile


zipFile = zipfile.ZipFile('LocalZipFile.zip', 'a',
zipfile.ZIP_DEFLATED)
dfile = open('LocalCSVFile.csv', 'r')
zipFile.writestr('test.csv',dfile.read())
dfile.close()
zipFile.close()


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


negative values on polar plot (decibels polar plots )

2007-08-14 Thread yadin

hi every one can you please
can you help me to fix these polar plot in db's
so that the center is at the minimun negative number in voltagedb
about [-50]
and the maximun is at zero
how can i see values on the axies like showing that the axes start at
-40 -30 .0
than you


import wx
import os
from wx.lib.colourdb import *
from pylab import*
angteta =  [ 4.36332313e-003, 3.18522588e-001, 6.32681854e-001,
9.46841119e-001,
 1.26100038e+000, 1.57515965e+000, 1.88931892e+000,
2.20347818e+000,
 2.51763745e+000, 2.83179671e+000, 3.14595598e+000,
3.46011524e+000,
 3.77427451e+000, 4.08843377e+000, 4.40259304e+000,
4.71675230e+000,
 5.03091157e+000, 5.34507083e+000, 5.65923010e+000,
5.97338936e+000,]

voltage =  [ 0.00363471, 0.26569155, 0.52562334, 0.76330428,
0.93673361, 1.,
 0.93321713, 0.75733232, 0.5185449 , 0.25840091,
0.00363471, 0.26569155,
 0.52562334, 0.76330428, 0.93673361, 1.,
0.93321713, 0.75733232,
 0.5185449 , 0.25840091,]

#voltagedb = 20*log10(voltage)


voltagedb =  [-48.7906044 ,-11.51244516, -5.58650713, -2.34604603,
-0.56767793,  0.,
  -0.60034598, -2.41427014,
-5.7042726 ,-11.75411924,-48.7906044 ,
  -11.51244516, -5.58650713, -2.34604603, -0.56767793,
0.,
  -0.60034598, -2.41427014, -5.7042726 ,-11.75411924,]
polar(angteta,voltagedb)

show()

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


Simple python iteration question

2007-08-14 Thread Bryan
Hi,

I just started with python, and have a for loop question

In c++ (or a number of other languages) I can do this:

for (int i=0, j=0; i < i_len, j< j_len; ++i, ++j) {}

If I have this in python:
l = ['a', 'b', 'c']

I want to get the value and also an iterator:
for i,v in len(l), l:
print v
print i

Or something like this without declaring the iterator outside my loop...

How do I do this?
Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


pure python gaussian blur

2007-08-14 Thread Gerdus van Zyl
Does anyone have a relatively fast gaussian blur implemented in pure
python? Below is my attempt but it takes 2.9 seconds for a 320x240
image. Image comes from byte string: self.array =
array.array('B',srcstring). Would some sort of matrix multiplication
be faster? I don't have experience in that.

I don't want to use PIL or http://filters.sourceforge.net/ to avoid
the 300kb dll just for a simple blur.


def blur(self):
# Convolution Kernels
blurFilter = [[0,1,2,1,0],
  [1,2,4,2,1],
  [2,4,8,4,2],
  [1,2,4,2,1],
  [0,1,2,1,0]]
blurDiv = 48
blurFilterSize = len(blurFilter) #5
blurFilterSize2 = blurFilterSize * blurFilterSize

pixels = self.array

stride = self.width * 4
w = self.width
h = self.height
red = 0
green = 0
blue = 0
sx = 0
ex = 0
sy = 0
ey = 0
ss = 0
f1 = 0
f2 = 0
ff = 0
idx = 0
samplesize = 0

offset1 = blurFilterSize/2
offset2 = blurFilterSize/2+2

clr = array.array('B',[255,255,255,255])
px = array.array('B',[255,255,255,255])

for x in xrange(0,w): #w

sx = x - offset1
ex = x + offset2
if sx < 0: sx = x
if ex > w:  ex = w

for y in xrange(0,h):
sy = y - offset1
ey = y + offset2

if sy < 0: sy = y

if ey > h:  ey = h

samplesize = (ex-sx) * (ey-sy)
if samplesize > 0:
ss = blurFilterSize2 / samplesize
if ss > blurFilterSize - 2:
ss = blurFilterSize - 2
else:
ss = 0


idx = 0
ffx = 0
red = 0
green = 0
blue = 0

for vx in xrange(sx,ex):
for vy in xrange(sy,ey):
offset = vy * stride + vx * 4

px = pixels[offset:offset
+4]

f1 = idx / 5
f2 = (idx - f1) % 5
f1 += ss
if f1 > 4:
f1 = 4

ff = blurFilter[f1]
[f2]
#ff = 1
ffx += ff
red   += px[0] * ff
green += px[1] * ff
blue  += px[2] * ff
idx += 1


if samplesize > 0:
red   = red / ffx
green = green / ffx
blue  = blue / ffx
if red > 255: red = 255
if green > 255: green = 255
if blue > 255: blue = 255

clr[0] = red
clr[1] = green
clr[2] = blue

self.setPixel(x, y, clr)

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


Re: Simple python iteration question

2007-08-14 Thread [EMAIL PROTECTED]
On Aug 14, 10:22 am, Bryan <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I just started with python, and have a for loop question
>
> In c++ (or a number of other languages) I can do this:
>
> for (int i=0, j=0; i < i_len, j< j_len; ++i, ++j) {}
>
> If I have this in python:
> l = ['a', 'b', 'c']
>
> I want to get the value and also an iterator:
> for i,v in len(l), l:
> print v
> print i
>
> Or something like this without declaring the iterator outside my loop...
>
> How do I do this?
> Thanks!

this will get index and item at index,

for i in range(0, len(l)):
print i
print l[i]


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


Re: Simple python iteration question

2007-08-14 Thread Lawrence Oluyede
Bryan <[EMAIL PROTECTED]> wrote:
> How do I do this?

for i, item in enumerate(l):
print i, item


-- 
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand 
something when his salary depends on not
understanding it" - Upton Sinclair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple python iteration question

2007-08-14 Thread Will Maier
On Tue, Aug 14, 2007 at 12:22:04PM -0400, Bryan wrote:
> I just started with python, and have a for loop question
> 
> In c++ (or a number of other languages) I can do this:
> 
> for (int i=0, j=0; i < i_len, j< j_len; ++i, ++j) {}
> 
> If I have this in python:
> l = ['a', 'b', 'c']
> 
> I want to get the value and also an iterator:
> for i,v in len(l), l:
>   print v
>   print i
> 
> Or something like this without declaring the iterator outside my loop...
> 
> How do I do this?

Use the enumerate() builtin.

>>> l = ['a', 'b', 'c']
>>> for i, v in enumerate(l):
... print i, v
... 
0 a
1 b
2 c

-- 

[Will [EMAIL PROTECTED]|http://www.lfod.us/]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple python iteration question

2007-08-14 Thread [EMAIL PROTECTED]
On Aug 14, 11:27 am, [EMAIL PROTECTED] (Lawrence Oluyede) wrote:
> Bryan <[EMAIL PROTECTED]> wrote:
> > How do I do this?
>
> for i, item in enumerate(l):
> print i, item
>

^^ That is the `most-correct` answer.  But because you're new, I'll
take this time to introduce you to help(), just in case you're too
lazy to RTFM (like me ;)).  help works on objects, and things you may
not expect  - try help(2).  Oh and welcome to `fun` programming!

>>> help(enumerate)

class enumerate(object)
 |  enumerate(iterable) -> iterator for index, value of iterable
 |
 |  Return an enumerate object.  iterable must be an other object that
supports
 |  iteration.  The enumerate object yields pairs containing a count
(from
 |  zero) and a value yielded by the iterable argument.  enumerate is
useful
 |  for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2,
seq[2]), ...

.. and a bunch of stuff I clipped ...

hth,
jw

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


Re: Simple python iteration question

2007-08-14 Thread Shawn Milochik
On 8/14/07, Bryan <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I just started with python, and have a for loop question
>
> In c++ (or a number of other languages) I can do this:
>
> for (int i=0, j=0; i < i_len, j< j_len; ++i, ++j) {}
>
> If I have this in python:
> l = ['a', 'b', 'c']
>
> I want to get the value and also an iterator:
> for i,v in len(l), l:
> print v
> print i
>
> Or something like this without declaring the iterator outside my loop...
>
> How do I do this?
> Thanks!
> --
> http://mail.python.org/mailman/listinfo/python-list
>


If I understand properly, maybe enumerate will help you:



>>> a = ['a','b','c']
>>> for i,v in enumerate(a):
... print i
... print v
...
0
a
1
b
2
c
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple python iteration question

2007-08-14 Thread i3dmaster
or use its builtin enumerate function:

for i, j in enumerate(list):
 print i, j

--Jim

On Aug 14, 2007, at 9:26 AM, [EMAIL PROTECTED] wrote:

> On Aug 14, 10:22 am, Bryan <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> I just started with python, and have a for loop question
>>
>> In c++ (or a number of other languages) I can do this:
>>
>> for (int i=0, j=0; i < i_len, j< j_len; ++i, ++j) {}
>>
>> If I have this in python:
>> l = ['a', 'b', 'c']
>>
>> I want to get the value and also an iterator:
>> for i,v in len(l), l:
>> print v
>> print i
>>
>> Or something like this without declaring the iterator outside my  
>> loop...
>>
>> How do I do this?
>> Thanks!
>
> this will get index and item at index,
>
> for i in range(0, len(l)):
> print i
> print l[i]
>
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Simple python iteration question

2007-08-14 Thread Shawn Milochik

> this will get index and item at index,
>
> for i in range(0, len(l)):
> print i
> print l[i]
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Enumerate is better here -- it provides the same result and that's
what it's for. However, if you do use range, the zero is unnecessary
-- beginning at zero is the default.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: LEGB rule, totally confused ...

2007-08-14 Thread Sion Arrowsmith
stef mientki  <[EMAIL PROTECTED]> wrote:
>def Run ():
>print X <=== UnboundLocalError: local variable
>'X' referenced before assignment
>X = X + 1
>
>Why do I get the error ?
>Printing isn't assigning anything or am I missing something.
>Now if I remove "X = X + 1" I don't get an error ???

Several people have already explained the scoping rules acting
here, but let's just look at how that error message is telling
you everything you need to know to fix the problem.

"local variable 'X' referenced before assignment"

"local variable 'X'" immediately tells you that the 'X' in
question is not your global 'X'.

"referenced before assignment": well, 'print X' is surely a
reference to 'X', and 'X = X + 1' is an assignment to it,
and 'print X' appears before 'X = X + 1'. That this is the
key you have confirmed experimentally.

The question to ask here is "Why does Python think 'X' is
local?" Everything else is answered by the error message.

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

Re: module: zipfile.writestr - line endings issue

2007-08-14 Thread [EMAIL PROTECTED]
On Aug 14, 11:04 am, towers <[EMAIL PROTECTED]> wrote:
> Hi
>
> I'm probably doing something stupid but I've run into a problem
> whereby I'm trying to add a csv file to a zip archive - see example
> code below.
>
> The csv just has several rows with carriage return line feeds (CRLF).
>
> However after adding it to an archive and then decompressing the line
> endings have been converted to just line feeds (LF).
>
> Does anyone know if this is a bug or am I just doing something wrong?
>
> Many Thanks,
> Damon
>
> 
> import zipfile
>
> zipFile = zipfile.ZipFile('LocalZipFile.zip', 'a',
> zipfile.ZIP_DEFLATED)
> dfile = open('LocalCSVFile.csv', 'r')
> zipFile.writestr('test.csv',dfile.read())
> dfile.close()
> zipFile.close()
> 

Line endings will drive you up the wall.  Anyway, the python zipfile
library does not seem to be doing any translations.  The code below
works for me.

# begin code
import zipfile
import os.path

# First create some work data...
csv_data = '1,2\r\n3,4\r\n5,6\r\n'

# Now, create the zipfile
zip_file = zipfile.ZipFile(r'c:\tmp\test.zip', 'w',
zipfile.ZIP_DEFLATED)
zip_file.writestr('test.csv',csv_data)
zip_file.close()

# Now, extract the info
zip_file = zipfile.ZipFile(r'c:\tmp\test.zip')
assert len(zip_file.read('test.csv')) == len(csv_data)
# end code

Something else must be tweaking your line endings.
HTH!

jw

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


Re: Simple python iteration question

2007-08-14 Thread Shawn Milochik

> Use the enumerate() builtin.
>
> >>> l = ['a', 'b', 'c']
> >>> for i, v in enumerate(l):
> ... print i, v
> ...
> 0 a
> 1 b
> 2 c
>
> --


Just for my own sanity: Isn't this the third response advocating the
use of enumerate()? Did the other responses not get through, or was
this a time-delay thing?

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


Re: Opinions about this new Python book?

2007-08-14 Thread James Matthews
i got to say that the best python book i bought was Core Python Programming
(2nd)  by Wesly Chun! Aside for all the spelling mistakes and syntax errors
that there are i feel that the book really explained the language well for
someone coming from another programming language!


On 8/14/07, Dick Moores <[EMAIL PROTECTED]> wrote:
>
> At 05:57 AM 8/14/2007, [EMAIL PROTECTED] wrote:
> >On Aug 14, 7:05 am, Dick Moores <[EMAIL PROTECTED]> wrote:
> > > I'd appreciate opinions about this new Python book.
> > >
> > > Title: Python Power!: The Comprehensive Guide
> > > Author:  Matt Telles
> > > Publisher:  Course Technology
> > > Pub. Date:  Jul 27, 2007
> > > Edition:  1st edition
> > > Binding:  Paperback
> > > Pages:  508
> > > ISBN:  1598631586
> > > List Price:  34.99 USD
> > >
> > > The book on the publisher's website: 
> > >
> > > And at BestBookDeal.com:
> > > 
> > >
> > > Thanks,
> > >
> > > Dick Moores
> >
> >I just got this book over the weekend. I'll start reading/skimming
> >through it this week and hopefully remember to get back to you.
>
> Thanks!
>
> >  By the
> >way, why do you want to know?
>
> If the experts like it, I'll buy it.
>
> Dick
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://www.goldwatches.com/
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

pil_usm for python 2.5?

2007-08-14 Thread Dieter Vanderelst
Hi list, 
Does anybody have a version of pil_usm (module for gaussian blurring) 
that is compiled for Python 2.5?
 
Regards,
Dieter
 
-- 
Dieter Vanderelst
[EMAIL PROTECTED]
Department of Industrial Design
Designed Intelligence
-- 
  Dieter Vanderelst
  [EMAIL PROTECTED]

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


Re: pure python gaussian blur

2007-08-14 Thread Patrick Doyle
On 8/14/07, Gerdus van Zyl <[EMAIL PROTECTED]> wrote:
> Does anyone have a relatively fast gaussian blur implemented in pure
> python? Below is my attempt but it takes 2.9 seconds for a 320x240
> image. Image comes from byte string: self.array =
> array.array('B',srcstring). Would some sort of matrix multiplication
> be faster? I don't have experience in that.
>
> I don't want to use PIL or http://filters.sourceforge.net/ to avoid
> the 300kb dll just for a simple blur.
>
The one time I tried something similar (implementing a signal
processing function in Python), I found NumPy to be _significantly_
faster -- which makes sense, since all of the matrix arithmetic was
implemented in hard coded, compiled C code instead of interpreted byte
code.

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


Re: module: zipfile.writestr - line endings issue

2007-08-14 Thread towers
Thanks - your code works for me also.

But I still get the issue when I read the file directly and add it to
the archive.

Say if I:

1. Use the test.csv file created with your code - currently the line
endings look good (viewed in notepad on Win XP)
2. Run the following code:

# begin code
import zipfile
import os.path

# Now, create the zipfile
dfile = open('test.csv', 'r')
zip_file = zipfile.ZipFile(r'C:\temp\ice\line endings\test.zip', 'w',
zipfile.ZIP_DEFLATED)
zip_file.writestr('test.csv',dfile.read())
dfile.close()
zip_file.close()

3. Then extract the file and the file endings have been corrupted. Now
one long line in notepad. (Other programs interpret correctly though.)

Maybe the issue lies with this way (i.e. dfile.read()) of writing the
file to the archive...possibly.

Damon





On 14 Aug, 17:55, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> On Aug 14, 11:04 am, towers <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi
>
> > I'm probably doing something stupid but I've run into a problem
> > whereby I'm trying to add a csv file to a zip archive - see example
> > code below.
>
> > The csv just has several rows with carriage return line feeds (CRLF).
>
> > However after adding it to an archive and then decompressing the line
> > endings have been converted to just line feeds (LF).
>
> > Does anyone know if this is a bug or am I just doing something wrong?
>
> > Many Thanks,
> > Damon
>
> > 
> > import zipfile
>
> > zipFile = zipfile.ZipFile('LocalZipFile.zip', 'a',
> > zipfile.ZIP_DEFLATED)
> > dfile = open('LocalCSVFile.csv', 'r')
> > zipFile.writestr('test.csv',dfile.read())
> > dfile.close()
> > zipFile.close()
> > 
>
> Line endings will drive you up the wall.  Anyway, the python zipfile
> library does not seem to be doing any translations.  The code below
> works for me.
>
> # begin code
> import zipfile
> import os.path
>
> # First create some work data...
> csv_data = '1,2\r\n3,4\r\n5,6\r\n'
>
> # Now, create the zipfile
> zip_file = zipfile.ZipFile(r'c:\tmp\test.zip', 'w',
> zipfile.ZIP_DEFLATED)
> zip_file.writestr('test.csv',csv_data)
> zip_file.close()
>
> # Now, extract the info
> zip_file = zipfile.ZipFile(r'c:\tmp\test.zip')
> assert len(zip_file.read('test.csv')) == len(csv_data)
> # end code
>
> Something else must be tweaking your line endings.
> HTH!
>
> jw


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


Re: LEGB rule, totally confused ...

2007-08-14 Thread stef mientki
Sion Arrowsmith wrote:
> stef mientki  <[EMAIL PROTECTED]> wrote:
>   
>>def Run ():
>>print X <=== UnboundLocalError: local variable
>>'X' referenced before assignment
>>X = X + 1
>>
>> Why do I get the error ?
>> Printing isn't assigning anything or am I missing something.
>> Now if I remove "X = X + 1" I don't get an error ???
>> 
>
> Several people have already explained the scoping rules acting
> here, but let's just look at how that error message is telling
> you everything you need to know to fix the problem.
>
> "local variable 'X' referenced before assignment"
>
> "local variable 'X'" immediately tells you that the 'X' in
> question is not your global 'X'.
>
> "referenced before assignment": well, 'print X' is surely a
> reference to 'X', and 'X = X + 1' is an assignment to it,
> and 'print X' appears before 'X = X + 1'. That this is the
> key you have confirmed experimentally.
>
> The question to ask here is "Why does Python think 'X' is
> local?" Everything else is answered by the error message.
>
>   
Thanks guys, I beginning to see the light again,
and if X is mutual the story is completely different,
I still have to get used to these differences.

cheers,
Stef Mientki

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


Re: Opinions about this new Python book?

2007-08-14 Thread Shawn Milochik
Yes, please post back to the list. I saw this book on Amazon, but
there's no table of contents listed, nor is there one on the
publisher's site.

Thanks,
Shawn




On 8/14/07, James Matthews <[EMAIL PROTECTED]> wrote:
> i got to say that the best python book i bought was Core Python Programming
> (2nd)  by Wesly Chun! Aside for all the spelling mistakes and syntax errors
> that there are i feel that the book really explained the language well for
> someone coming from another programming language!
>
>
> On 8/14/07, Dick Moores <[EMAIL PROTECTED]> wrote:
> > At 05:57 AM 8/14/2007, [EMAIL PROTECTED] wrote:
> > >On Aug 14, 7:05 am, Dick Moores <[EMAIL PROTECTED]> wrote:
> > > > I'd appreciate opinions about this new Python book.
> > > >
> > > > Title: Python Power!: The Comprehensive Guide
> > > > Author:  Matt Telles
> > > > Publisher:  Course Technology
> > > > Pub. Date:  Jul 27, 2007
> > > > Edition:  1st edition
> > > > Binding:  Paperback
> > > > Pages:  508
> > > > ISBN:  1598631586
> > > > List Price:  34.99 USD
> > > >
> > > > The book on the publisher's website: < http://tinyurl.com/2dkhzg>
> > > >
> > > > And at BestBookDeal.com:
> > > > 
> > > >
> > > > Thanks,
> > > >
> > > > Dick Moores
> > >
> > >I just got this book over the weekend. I'll start reading/skimming
> > >through it this week and hopefully remember to get back to you.
> >
> > Thanks!
> >
> > >  By the
> > >way, why do you want to know?
> >
> > If the experts like it, I'll buy it.
> >
> > Dick
> >
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
>
>
> --
> http://www.goldwatches.com/
> http://www.jewelerslounge.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Please read:
http://milocast.com/2007/07/31/this-i-believe/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (Re)announcing APL 2007

2007-08-14 Thread Bob Armstrong
On Aug 6, 7:20 am, Paul Mansour <[EMAIL PROTECTED]> wrote:
> APL2007 Roll Call: Is anyone going to this?

 I'm thinking of going also , setting up some arrangement to provide
an introductory tutorial to my free and open 4th.CoSy .

My website is transiting between hosts so I don't recommend even
looking at it right now . But by the end of the month I should be
uploading a system with the Forth integrated and usable multiple
windows ala K's "electric gui" .

Hopefully by conference time , I'll have my recursive , quite APLish
syntax , interpreter working .

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


Re: JPype - passing to Java main

2007-08-14 Thread Alan Kennedy
> -ERROR_-
>   File "tester.py", line 10, in 
> com.JPypeTest.main("arg")
> RuntimeError: No matching overloads found. at src/native/common/
> jp_method.cpp:121
> --END ERROR-

I haven't used jpype, but the signature for java main functions is

public static void main (String [] args)

So try com.JPypeTest.main(["arg"])

Note the addition of square brackets to create a *list* of arguments,
which presumably jpype will transform into a java String[].

Alan.

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


curses library

2007-08-14 Thread Ghirai
Hello list,

I need to write a console application.

Are there any wrappers around curses/ncurses?
Or any other similar libraries?

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


Re: curses library

2007-08-14 Thread Neil Cerutti
On 2007-08-14, Ghirai <[EMAIL PROTECTED]> wrote:
> I need to write a console application.
>
> Are there any wrappers around curses/ncurses?
> Or any other similar libraries?

The answer depends on your chosen platform. Python hasn't got a
cross-platform console library as one of its included batteries.

First try the curses module. It does come with Python on systems
with a curses port.

For Windows, there's the Effbot's console module.
http://effbot.org/zone/console-index.htm

Or go to plan B: Use a Tkinter or other GUI interface's text
widget.

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


Re: Opinions about this new Python book?

2007-08-14 Thread kyosohma
On Aug 14, 12:46 pm, "Shawn Milochik" <[EMAIL PROTECTED]> wrote:
> Yes, please post back to the list. I saw this book on Amazon, but
> there's no table of contents listed, nor is there one on the
> publisher's site.
>
> Thanks,
> Shawn
>
> On 8/14/07, James Matthews <[EMAIL PROTECTED]> wrote:
>
>
>
> > i got to say that the best python book i bought was Core Python Programming
> > (2nd)  by Wesly Chun! Aside for all the spelling mistakes and syntax errors
> > that there are i feel that the book really explained the language well for
> > someone coming from another programming language!
>
> > On 8/14/07, Dick Moores <[EMAIL PROTECTED]> wrote:
> > > At 05:57 AM 8/14/2007, [EMAIL PROTECTED] wrote:
> > > >On Aug 14, 7:05 am, Dick Moores <[EMAIL PROTECTED]> wrote:
> > > > > I'd appreciate opinions about this new Python book.
>
> > > > > Title: Python Power!: The Comprehensive Guide
> > > > > Author:  Matt Telles
> > > > > Publisher:  Course Technology
> > > > > Pub. Date:  Jul 27, 2007
> > > > > Edition:  1st edition
> > > > > Binding:  Paperback
> > > > > Pages:  508
> > > > > ISBN:  1598631586
> > > > > List Price:  34.99 USD
>
> > > > > The book on the publisher's website: 
>
> > > > > And at BestBookDeal.com:
> > > > > 
>
> > > > > Thanks,
>
> > > > > Dick Moores
>
> > > >I just got this book over the weekend. I'll start reading/skimming
> > > >through it this week and hopefully remember to get back to you.
>
> > > Thanks!
>
> > > >  By the
> > > >way, why do you want to know?
>
> > > If the experts like it, I'll buy it.
>
> > > Dick
>
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list
>
> > --
> >http://www.goldwatches.com/
> >http://www.jewelerslounge.com
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> --
> Please read:http://milocast.com/2007/07/31/this-i-believe/

Here's an abbreviated Table of Contents...just chapter titles. The
book's table of contents also lists section headers.

Chapter 1: About Python
Chapter 2: Python Language Overview
Chapter 3: Tools
Chapter 4: Data Types
Chapter 5: Control Flow
Chapter 6: Input & Output
Chapter 7: Functions & Modules
Chapter 8: Exception Handling
Chapter 9: Object-Oriented Programming
Chapter 10: Classes and Objects in Python
Chapter 11: The Python Library
Chapter 12: The GUI - Tkinter
Chapter 13: The Web Server - Apache
Chapter 14: Working with Databases
Chapter 15: Putting It All Together
Chapter 16: Python and Graphics


Mike

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


Re: Fast kNN from python

2007-08-14 Thread Miki
Hello,

> I am looking for a Python implementation or bindings to a library that
> can quickly find k-Nearest Neighbors given an arbitrary distance
> metric between objects. Specifically, I have an "edit distance"
> between objects that is written in Python.
First Google search for "k-Nearest Neighbors python", yielded
http://people.revoledu.com/kardi/tutorial/KNN/resources.html  which
pointed to http://biopython.org/DIST/docs/api/public/Bio.kNN-module.html

HTH,
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com

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


Re: curses library

2007-08-14 Thread Ghirai
On Tue, 14 Aug 2007 18:27:16 GMT
Neil Cerutti <[EMAIL PROTECTED]> wrote:

> On 2007-08-14, Ghirai <[EMAIL PROTECTED]> wrote:
> > I need to write a console application.
> >
> > Are there any wrappers around curses/ncurses?
> > Or any other similar libraries?
> 
> The answer depends on your chosen platform. Python hasn't got a
> cross-platform console library as one of its included batteries.
> 
> First try the curses module. It does come with Python on systems
> with a curses port.
> 
> For Windows, there's the Effbot's console module.
> http://effbot.org/zone/console-index.htm
> 
> Or go to plan B: Use a Tkinter or other GUI interface's text
> widget.

Forgot to say, i don't need it to work on windows :)

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


Re: curses library

2007-08-14 Thread Shawn Milochik
You should try Google -- you'll get results faster:

http://www.amk.ca/python/howto/curses/

http://docs.python.org/lib/module-curses.html





On 8/14/07, Ghirai <[EMAIL PROTECTED]> wrote:
> Hello list,
>
> I need to write a console application.
>
> Are there any wrappers around curses/ncurses?
> Or any other similar libraries?
>
> Thanks.
> --
> Regards,
> Ghirai.
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Please read:
http://milocast.com/2007/07/31/this-i-believe/
-- 
http://mail.python.org/mailman/listinfo/python-list


post xml payload with urllib

2007-08-14 Thread brad
Has anyone sent an xml payload via post using urllib? I'd like to do 
something like this:

logon_request = """
   "the_password"
   "the_user"
"""

logon = urllib.urlopen("https://127.0.0.1/api/version/xml";, logon_request)
print logon.read()
logon.close()

127.0.0.1 expects xml via a https connection post.
-- 
http://mail.python.org/mailman/listinfo/python-list


try/finally exceptions dying

2007-08-14 Thread stephen . y4ng
Hello all,

In order to churn through a whole bunch of data sets (some good, some
bad..) and get all the errors at the end, (the data will be updated to
make it all good later on) I implemented a try/finally block with a
higher level handler to catch errors before they propagate to the
default handler and crash the program. Something like this:

def doStuff(args):
  if(args says we should keep going):
try:
   stuff
finally:
   update args
   doStuff(updated args)

 def runWithErrorHandling():
   try:
 doStuff(args)
   except (exception1, exception2), data:
   
   append exception data to a list of errors

 runWithErrorHandling()

unfortunately, this churns through all the data and I only get the
last exception that occurred in the error list, not all of them, as I
expected. What is going on? I thought finally always propagated the
exception all the way up the stack until it was handled.

Any thoughts are appreciated.

Stephen

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


Re: post xml payload with urllib

2007-08-14 Thread mirandacascade
On Aug 14, 11:57 am, brad <[EMAIL PROTECTED]> wrote:
> Has anyone sent an xml payload via post using urllib?

Haven't used urllib, but have used urllib2 to do a POST.

Might something like this work...

import urllib2

logon_request = """
"the_password"
"the_user"
 """

req = urllib2.Request("https://127.0.0.1/api/version/xml";,
data=logon_request)
openObj = urllib2.urlopen(req)
response = openObj.read()




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


Re: Fast kNN from python

2007-08-14 Thread Sean Davis
On Aug 14, 6:16 am, Janto Dreijer <[EMAIL PROTECTED]> wrote:
> Hi!
>
> I am looking for a Python implementation or bindings to a library that
> can quickly find k-Nearest Neighbors given an arbitrary distance
> metric between objects. Specifically, I have an "edit distance"
> between objects that is written in Python.
>
> I haven't looked at the methods in detail but I think I'm looking for
> one of the data structures listed onhttp://en.wikipedia.org/wiki/Metric_trees
> (i.e. vp-trees, cover trees, m-trees or bk trees). But I might be
> wrong. An approximate kNN would also work.
>
> If there doesn't exist such an implementation yet, any advice on a
> library I can wrap myself would also be appreciated.
>
> Thanks!
> Janto

Have you looked at using Rpy and R?  There are probably several knn
implementations that then become accessible to you (although I haven't
checked recently).

Sean


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


Re: curses library

2007-08-14 Thread Jean-Paul Calderone
On Tue, 14 Aug 2007 21:45:51 +0300, Ghirai <[EMAIL PROTECTED]> wrote:
>On Tue, 14 Aug 2007 18:27:16 GMT
>Neil Cerutti <[EMAIL PROTECTED]> wrote:
>
>> On 2007-08-14, Ghirai <[EMAIL PROTECTED]> wrote:
>> > I need to write a console application.
>> >
>> > Are there any wrappers around curses/ncurses?
>> > Or any other similar libraries?
>>
>> The answer depends on your chosen platform. Python hasn't got a
>> cross-platform console library as one of its included batteries.
>>
>> First try the curses module. It does come with Python on systems
>> with a curses port.
>>
>> For Windows, there's the Effbot's console module.
>> http://effbot.org/zone/console-index.htm
>>
>> Or go to plan B: Use a Tkinter or other GUI interface's text
>> widget.
>
>Forgot to say, i don't need it to work on windows :)

You might be interested in insults:

API docs:

  http://twistedmatrix.com/documents/current/api/twisted.conch.insults.html

Examples:

  http://twistedmatrix.com/projects/conch/documentation/examples/

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


Form-Through-Script Nightmare

2007-08-14 Thread tonylabarbara
Hi;
I originally submitted this to the Zope list, but after no replies and 
realizing it's probably better suited for the python list, I'm submitting it 
here.


I have a form where purchasers can deselect items they've added to their 
shopping cart. All the hidden fields have been numbered according to the items 
they *originally* selected. If they deselect an item, then it will probably 
necessitate a renumbering of all those hidden fields, since PayPal doesn't 
tolerate misnumbering: everything must be numbered "1" for all the hidden 
fields of the first product, "2" for the second, etc. If the customer selects 5 
products and deletes the 3rd, then I need to renumber. I wrote a script that 
can do that. Now, I have to send the form to that script, with all its lovely 
hidden fields, then reproduce it somewhere so I can send it off to PP. That is, 
the form must return from the called script to a new page and deliver all the 
renumbered hidden fields. 

?

Let me summarize what I've written before to put in one post exactly what's 
going on:


1)?I have a form that I need to send to a script and then send off to a URL 
(PayPal). I need to process it through the script to renumber things for PP. 
How do I do this? I imagine I add an element to the PT like so:



but I need to pass a parameter "doc", which, of course, is the document I'm 
submitting. So I tried this:




which renders my page fine, but throws an error when I submit the form:

Cannot locate object at: 
http://example.com/s/c/x/j/en-us/s/renumberTheCart%28here

meaning, of course, that it didn't receive the required parameter.

2) I changed it to an absolute URL just to double-check, and got basically the 
same error:
?

Invalid request

The parameter, doc, was omitted from the request. 


How do I pass the parameter, which in my case is quite long and stashed neatly 
away in a PT macro?


http://example.com/s/renumberTheCart?doc=docs"; method="post">?
?



Now, Tom Von Lahndorff suggested the following:


Sounds like the script should check to see if the user is removing something 
like:






if remove

remove the item

redirect back to the udpated form page

else

send to PP




this way once the item is removed and the same script is called, since there's 
no remove this time, it'll go to PP.


I would LOVE to do that...if I knew how! Any ideas?
TIA,
Tony




?

Invalid request

The parameter, doc, was omitted from the request. 


How do I pass the parameter, which in my case is quite long and stashed neatly 
away in a PT macro?


http://example.com/s/renumberTheCart?doc=docs"; method="post">?
?



Now, Tom Von Lahndorff suggested the following:


Sounds like the script should check to see if the user is removing something 
like:






if remove

remove the item

redirect back to the udpated form page

else

send to PP




this way once the item is removed and the same script is called, since there's 
no remove this time, it'll go to PP.


I would LOVE to do that...if I knew how! Any ideas?
TIA,
Tony




AOL now offers free email to everyone.  Find out more about what's free from 
AOL at AOL.com.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: module: zipfile.writestr - line endings issue

2007-08-14 Thread Paul Carter
On Aug 14, 1:32 pm, towers <[EMAIL PROTECTED]> wrote:
> Thanks - your code works for me also.
>
> But I still get the issue when I read the file directly and add it to
> the archive.
>
> Say if I:
>
> 1. Use the test.csv file created with your code - currently the line
> endings look good (viewed in notepad on Win XP)
> 2. Run the following code:
>
> # begin code
> import zipfile
> import os.path
>
> # Now, create the zipfile
> dfile = open('test.csv', 'r')
> zip_file = zipfile.ZipFile(r'C:\temp\ice\line endings\test.zip', 'w',
> zipfile.ZIP_DEFLATED)
> zip_file.writestr('test.csv',dfile.read())
> dfile.close()
> zip_file.close()
>
> 3. Then extract the file and the file endings have been corrupted. Now
> one long line in notepad. (Other programs interpret correctly though.)
>
> Maybe the issue lies with this way (i.e. dfile.read()) of writing the
> file to the archive...possibly.
>
> Damon
>

Please don't top post.

The problem is with how you are opening the file. You need to open in
binary mode if you wish to read your file unaltered. Also, file() is
preferred over open() these days I think. Use:

dfile = file('test.csv', 'rb')

--
Paul Carter

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


Re: chmod g+ Equivalent

2007-08-14 Thread Bjoern Schliessmann
milan_sanremo wrote:
> The group ownership is set by chown,

Yes -- by storing a group's gid (group ID) in the file metadata. The
group ID is an int from /etc/group.

> but the group id (setgid bit) is set by chmod.

"group id" is not "setgid bit".

The "setgid bit" is one bit in the file metadata that tells the OS
to change the group ID based privileges for a process.

Regards,


Björn

-- 
BOFH excuse #412:

Radial Telemetry Infiltration

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


Re: import * is not allowed ??

2007-08-14 Thread O.R.Senthil Kumaran
* stef mientki <[EMAIL PROTECTED]> [2007-08-14 02:14:04]:

>   import * is not allowed in function 'JAL_MAIN_RUN' because it contains 
> a nested function with free variables (JAL_simulation_file.py, line 22)
> 
What is the actual error message you are getting?
Can you paste the stack trace or a link to the program?

-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython before MainLoop

2007-08-14 Thread Bjoern Schliessmann
[david] wrote:

> Well yes, I have tried this app with native windows,
> and I know how to do it.

Then I wonder why you complained about concurrency problems (solved
by using a worker thread, or using wx.Yield) in the first place.
Windows has the same solutions, just as about every GUI framework.

http://msdn2.microsoft.com/en-us/library/69644x60(VS.80).aspx
 
> But if all wxPython can offer is a poor imitation of MFC,

>From what did you conclude this? As already stated, almost ALL GUI
toolkits available function in a similar way (using an event loop).
To say that every such toolkit was just an imitation of MFC is
quite childish, IMHO. 

Same niveau would be to say that all other cars are poor imitations
of Ford cars because they all have four wheels.

> I'm better off using MFC aren't I? 

That depends on your demands. If you don't want it cross platform
you may be right, especially if you require very special Windows
features.

> And too all those people who wrote back to insist
> that users MUST explicitly build a multi-threaded
> framework for wxPython:

Could you please cite one posting where this is claimed? I can't
find this claim.

> It's supposed to already be a framework :~)

wxWidgets _has_ cross-platform threads implemented on its own:

http://www.wxwidgets.org/manuals/stable/wx_wxthread.html#wxthread

It has just been dropped from wxPython because cross-platform
threads are already part of the Python library. C++, the basis for
wxWidgets, has no multithreading support in STL.

Regards,


Björn

-- 
BOFH excuse #61:

not approved by the FCC

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


Re: wxPython before MainLoop

2007-08-14 Thread Bjoern Schliessmann
[david] wrote:
> Steve, it wasn't me that raised the comparison
> with MFC. If you don't think that's a helpful
> comparison, why not reply to that post instead?

It _was_ a comparison, saying that they follow similar principles.
You twisted this comparison by saying wxPython was an imitation of
MFC. You ignored the fact that your problem is solved by MFC in a
similar way, just as in every other GUI toolkit other posters here
and me know of.

> I don't mind Björn's suggestion that I don't
> know what I'm talking about,

Where did I write this?

> because I started it by telling him he was wrong.

Excuse me, where am I wrong?


Björn

-- 
BOFH excuse #163:

no "any" key on keyboard

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


Re: try/finally exceptions dying

2007-08-14 Thread Matt McCredie
> I thought finally always propagated the
> exception all the way up the stack until it was handled.

Finally will propagate the exception up, unless another exception
occurs within the finally block. Since there is not (yet:
http://www.python.org/dev/peps/pep-3134/) exception chaining in
Python, only the last exception to be raised is held onto.

The finally block combined with the recursion makes it impossible to
catch every exception that way.

Something like this might work:

[code]
def dostuff(args):
   stuff
   return status

def run_with_error_handling():
exceptions = []
done = False
while 1:
try:
  status = dostuff(args)
except (exception1, exception2), data:
exceptions.append(data)
modify status
 finally:
update args based on status
break if done
[/code]

Note that in the above example, status could be just a tuple of args.
Then you just need to figure out how to modify the args in the
exception case.

The above leaves a lot of holes though. If you want more help you will
have to send a more complete example.

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


  1   2   >