[OT]: The Python Fan

2008-01-25 Thread Paddy
http://www.brightcove.tv/title.jsp?title=1390821847

:-)

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


Re: Doesn't know what it wants

2008-01-25 Thread John Machin
On Jan 26, 6:25 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Fri, 25 Jan 2008 22:53:16 -0800, John Machin wrote:
> > On Jan 26, 5:32 pm, Jeroen Ruigrok van der Werven <[EMAIL PROTECTED]
> > nomine.org> wrote:
> >> -On [20080126 06:26], Tim Rau ([EMAIL PROTECTED]) wrote:
>
> >> >Line 147 reads:
> >> >moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
>
> >> I think it expects something like:
>
> >> # badly named variable, pick something better depending on context
> >> temp = vec2d(0, 0)
> >> cp.cpMomentForCircle(self.mass, .2, 0, temp)
>
> > That *cannot* give a different result in Python. The called function
> > will be presented with *exactly* the same object as the OP's code does.
>
> Not quite. Look carefully at the difference.
>
> The OP's code calls vec2d with a single tuple argument (0,0). Jeroen's
> version calls vec2d with two int arguments, 0 and 0.
>
> We don't know whether vec2d will treat those two things the same or not.

That was Jeroen's 2nd problem; I was addressing his first problem
(thinking that introducing a temp variable would work some magic).

Google is your friend:
"""
class vec2d(ctypes.Structure):
"""2d vector class, supports vector and scalar operators,
   and also provides a bunch of high level functions
   """
__slots__ = ['x', 'y']

def __init__(self, x_or_pair, y = None):

if y == None:
self.x = x_or_pair[0]
self.y = x_or_pair[1]
else:
self.x = x_or_pair
self.y = y
"""
-- 
http://mail.python.org/mailman/listinfo/python-list


Pickling dynamically generated classes

2008-01-25 Thread George Sakkis
The Fine Manual mentions that pickle works for classes that are
defined at the top level of a module. Is there a way to extend this
behavior so that I can pickle and unpickle instances of dynamically
generated classes ?

Longer version: I have a function RecordTypeFactory(fields, ...) that
dynamically generates and caches a record-like class based on the
passed fields and other info (or returns the cached class if it has
been created before). Although I am able to pickle instances of the
various generated classes (records) by writing the gen. class in
globals(), I cannot unpickle them from a different process unless
RecordTypeFactory is called with the same arguments so that "the same"
class is generated in the other process as well. Essentially what I'm
missing is a hook to call RecordTypeFactory with the same fields when
an instance of the gen. class is to be unpickled.

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


Re: Index of maximum element in list

2008-01-25 Thread Paul Rubin
"Terry Reedy" <[EMAIL PROTECTED]> writes:
> | > What's about l.index(max(l)) ?
> 
> Both of these methods scan the list twice.  The two given by RH and SDD do 
> so just once.  Both of those will give the index of the of the last maximum 
> value.  If you want the index of the first max value (you did not specify 
> ;-), write an explicit loop. 

How about (corrected but still untested):

  -max((v,-i) for i,v in enumerate(l))[1]

I may have still missed something.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Testing whether something is of type Exception

2008-01-25 Thread Terry Reedy

"John Nagle" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|How can I tell whether an object is of type Exception?
| At least in Python 2.4, "Exception" is an old-style class, and
| the "type" of Exception objects is "instance".
|
|Clearly "repr" knows; it returns:
| 

Actually, repr does not know.  repr(x) calls x.__repr__.  Each object know 
how to represent itself.

In 2.4 and before, look for 'Exception' in repr(x).



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


Re: getting values from cache

2008-01-25 Thread nodrogbrown
also
if i were to write unit test for this method ,how shd i do it? shd i
be checking all values in the matrix created inside and so on?

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


Re: python and multithreading problem

2008-01-25 Thread Diez B. Roggisch
whatazor schrieb:
> Hi all,
> I made an application that use multithreading (indifferently importing
> thread or  threading module) , but when I call some wrapped modules
> (with swig) from my application they run like there is only a single
> thread (and my application gui ,made with wxPython, freezes). If I use
> other modules not wrapped, but created for test that multithread
> works, and gui is not freezing are ok.
> Modules that wrap DLL are not my product but are created by another
> developer with VS.NET, and the only thing I can think is that they're
> builded without multithreaded compiler option. Can it be another cause
> for this behaviour, can this explanation be correct? maybe also swig
> have a multithreading option.


There is something called Global Interpreter Lock (GIL) that causes such 
behavior. It will ensure that python-code won't interfere with each 
other in multiple threads.

However, for C-extensions it is common to release that GIL when a thread 
enters the extenison, and grab it again when finished. I don't know if 
SWIG does so, but to me it looks as if that is the problem. You might 
consider googling swig + gil or something to learn more about it.

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


Re: Index of maximum element in list

2008-01-25 Thread Terry Reedy

"Henry Baxter" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Thanks Hexamorph and Neal. Somehow I didn't make the connection with 
using
| 'index', but I'm all sorted out now :)
|
| On Jan 25, 2008 1:47 PM, Hexamorph <[EMAIL PROTECTED]> wrote:
|
| > Henry Baxter wrote:
| > > Oops, gmail has keyboard shortcuts apparently, to continue:
| > >
| > > def maxi(l):
| > > m = max(l)
| > > for i, v in enumerate(l):
| > > if m == v:
| > > return i
| > >
| >
| > What's about l.index(max(l)) ?

Both of these methods scan the list twice.  The two given by RH and SDD do 
so just once.  Both of those will give the index of the of the last maximum 
value.  If you want the index of the first max value (you did not specify 
;-), write an explicit loop. 



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


Re: Doesn't know what it wants

2008-01-25 Thread Steven D'Aprano
On Fri, 25 Jan 2008 22:53:16 -0800, John Machin wrote:

> On Jan 26, 5:32 pm, Jeroen Ruigrok van der Werven <[EMAIL PROTECTED]
> nomine.org> wrote:
>> -On [20080126 06:26], Tim Rau ([EMAIL PROTECTED]) wrote:
>>
>> >Line 147 reads:
>> >moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
>>
>> I think it expects something like:
>>
>> # badly named variable, pick something better depending on context 
>> temp = vec2d(0, 0)
>> cp.cpMomentForCircle(self.mass, .2, 0, temp)
> 
> That *cannot* give a different result in Python. The called function
> will be presented with *exactly* the same object as the OP's code does.

Not quite. Look carefully at the difference.

The OP's code calls vec2d with a single tuple argument (0,0). Jeroen's 
version calls vec2d with two int arguments, 0 and 0.

We don't know whether vec2d will treat those two things the same or not.

Personally, my bet is that the OP has shadowed vec2d, and has got two 
different classes floating around with the same class.__name__.

Either that, or a bug in cp.cpMomentForCircle. I'd really like to see the 
code of that function in phyInit. I'm suspicious about the exception 
raised:

ArgumentError: argument 4: : expected vec2d 
instance instead of vec2d

What's with the TypeError in there? I'm guessing it's not a hard coded 
string.



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


Re: Generational Interfaces

2008-01-25 Thread Carl Banks
On Jan 26, 12:32 am, Paul Rubin  wrote:
> Carl Banks <[EMAIL PROTECTED]> writes:
> > AirplaneInterface = InterfaceTracker("Airplane")
> > ...
> > set_up_initial_state()
> > ...
> > AirplaneInterface.report(self)
> > Thoughts?  (Surely someone's thought to do this before.)
>
> A decorator might express the idea a little more naturally.

Details.  I didn't thoroughly map out the whole system in my head or
anything.


> Also, I'd say the interface tracker really should be told explicitly
> when something is part of the interface and when it's specific to a
> particular class implementing the interface.  It shouldn't try to
> guess this based on some operation appearing in more than one class.

Well, that kind of defeats the purpose, doesn't it?

If you're going to all that trouble, it's probably not too much more
trouble to just manually specify the whole interface and be done with
it.  Anyways you don't always know what's going to end up as part of
the interface in early stages.

It goes without saying there should be ways to manually override the
interface tracker's decision, but that falls more into the category
"So your interface tracker has guessed wrong".


> Maybe there's some operation done on all jet planes and on no
> propeller planes, that shouldn't be part of the top level airplane
> interface.

Well, then the interface tracker would see that some member (say,
"set_mixture") exists on some objects and not others, and would
consider it not part of the interface.  Only members that are defined
universally or nearly universally would be considered part of the
interface.

Now if you're concerned that you could implement a bunch of prop
planes, and then suddenly you throw a jet in there and it breaks
everything, there's a simple solution: convert the AirplaneInterface
to PropAirplaneInterface.  (Yeah, suck it up and replace it
everywhere.  If you haven't implemented any jets you shouldn't have
released the damn thing yet.)  Create a new JetAirplaneInterface
tracker and (if useful) define Airplane as the union of the two.

Obviously something like this could get really intelligent--it could
perhaps work out the difference between props and jets itself (using,
say, statistical correlation).  I bet there are some high-end code
analysis tools for various languages that do stuff like that.  (But I
doubt many of them factor time into it; my idea was to incorporate
time into it somehow.  Something does not become part of an interface
until it's universally used AND has been around for awhile.)


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


getting values from cache

2008-01-25 Thread nodrogbrown
hi
i am writing code to check a folder containing images and then process
thir vals using PIL and do some calc to create a matrix of values .if
the folder has any new imgs added the program will do all calc again
and dump the values into a cachefile.If the folder contents remain
unaltered the program should not do calc but load the vals from
cachefile..it is assumed that malicious alterations are not made on
the folder and so i wont be doing any thorogh check but just checking
if contents of folder have changed..i do something like this


def checkCache(self):
   filenameslist=getfilenameslist() # made by parsing folder before
this
   try:
  f=open(cachefile)

   except IOError:
#no cache found ,do all calc
mynumpymatrix1,imgwdth,imght=docalculations()
f2=open(cachefile,"w")
#dump values as tuple
pickle.dump((filenameslist,imgwdth,imght,mynumpymatrix1),f2)
f2.close()
   else:
#cache exists, need to check if folder contents changed
oldfilenameslist,wd,ht, mynumpymatrix1=pickle.load(f)
f.close()

if(filenamelist==oldfilelist):
#if oldfilenamelst same,it means folder hasn't changed
#use the vals from cache.
else:
#folder changed
mynumpymatrix1,imgwdth,imght=docalculations()
f3=open(cachefile,"w")
 
pickle.dump((filenameslist,imgwdth,imght,mynumpymatrix1),f3)
f3.close()

 this works and does what i need in my code..but i want to know if a
more elegant solution is possible
 i am not worried about someone deliberately renaming files like
.jpeg to aaa.jped and a.jpeg to deceive the checking
 since it is assumed that noone has permission to modify the folder
except a trusted admin/code

 will be grateful for your suggestions
 tia
-- 
http://mail.python.org/mailman/listinfo/python-list


wx.EVT_RIGHT_UP strangeness?

2008-01-25 Thread JimT
I'm playing with wxPython 2.8.7.1 on OS X 10.4.11 with MacPython 2.5

I ran the demo program found what may be a bug with the right mouse 
button up event.

The demo is ShapedWindow.py. Everthing thing seems to work fine except 
that right
clicking does not close the window. Tracing the program shows that the 
event never
fires.

Upon closer scrutiny I discovered if you bind the wx.EVT_RIGHT_DOWN event, the
wx.EVT_RIGHT_UP now fires. I tried this in a couple programs and the 
behavior is
consistent.

Is this the way it is supposed to work? If not, am I the only one with 
this problem?


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


Mobile Phones, iPods EQ100 www.enmac.com.hk

2008-01-25 Thread Farooq
www.enmac.com.hk
GSM Mobile Phones, Digital iPods, Digital Clocks, Digital Pens,
Digital Quran. Enjoy these products with Islamic Features (Complete
Holy Quran with Text and Audio, Tafaseer books, Ahadees Books, Daily
Supplications, Universal Qibla Direction, Prayer Timing and much more)
visit our website for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doesn't know what it wants

2008-01-25 Thread John Machin
On Jan 26, 5:32 pm, Jeroen Ruigrok van der Werven <[EMAIL PROTECTED]
nomine.org> wrote:
> -On [20080126 06:26], Tim Rau ([EMAIL PROTECTED]) wrote:
>
> >Line 147 reads:
> >moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
>
> I think it expects something like:
>
> # badly named variable, pick something better depending on context
> temp = vec2d(0, 0)
> cp.cpMomentForCircle(self.mass, .2, 0, temp)

That *cannot* give a different result in Python. The called function
will be presented with *exactly* the same object as the OP's code
does.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doesn't know what it wants

2008-01-25 Thread Tim Rau
On Jan 26, 1:41 am, John Machin <[EMAIL PROTECTED]> wrote:
> On Jan 26, 4:20 pm, Tim Rau <[EMAIL PROTECTED]> wrote:
>
>
>
> > Traceback (most recent call last):
> >   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> > \sandbox.py", line 242, in 
> > player = ship()
> >   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> > \sandbox.py", line 121, in __init__
> > self.phyInit()
> >   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> > \sandbox.py", line 147, in phyInit
> > moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
> > ArgumentError: argument 4: : expected
> > vec2d instance instead of vec2d
>
> > As far as I can tell, It's getting a vec2d, and it wants a vec2d. I't
> > seems like it doesn't know what it wants, but I thought only teenagers
> > did that, no programming languages.
>
> It possibly means that it is expecting an instance of a class whose
> name is "vec2d"  but you have given it an instance of some *other*
> class whose name just happens to be "vec2d".
>
> > clearly, Im missing something.
>
> Yes, some information:
> 1. what is vec2d, class or function?
> 2. what do you believe vec2d((0, 0)) should return?
> 3. what is this belief based on?
> 4. what has it actually returned this time?
> 5. what do you believe that cp.cpMomentForCircle expects as argument
> 4?
> 6. what is this belief based on?
>
> The ArgumentError exception is raised by ctypes "when a foreign
> function call cannot convert one of the passed arguments". Based on
> guessin'n'googlin' the cp thing is a set of Python bindings to a
> library written in C++ ... have you considered asking the author of
> the bindings?

1. vec2d is a class, designed to hold and manipulte 2d vectors
2. it should return a vector with x=0 and y=0
3. That's what it's done before.
4. trying it in the interpreter seems to show that it returns a vec2d
with zero length. as it should.
5.cp.cpMomentForCircle seems to expect a vec2d. I'm baseing that on a
functioning demo that uses the exact same line.

I guess that the vec2d I've got is not the one it wants. How do I tell
the difference? I'll go look at all the imports.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doesn't know what it wants

2008-01-25 Thread Tim Rau
On Jan 26, 1:32 am, Jeroen Ruigrok van der Werven <[EMAIL PROTECTED]
nomine.org> wrote:
> -On [20080126 06:26], Tim Rau ([EMAIL PROTECTED]) wrote:
>
> >Line 147 reads:
> >moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
>
> I think it expects something like:
>
> # badly named variable, pick something better depending on context
> temp = vec2d(0, 0)
> cp.cpMomentForCircle(self.mass, .2, 0, temp)
>
> I am curious about your use of double braces for vec2d though. Why ((0,0)) and
> not (0, 0)?

the double parens are a tuple being passed as an argument. vec2d is
not a constructor that cares whether it gets a tuple or a pair of
ints. I choose tuple for consistency with the rest of my code.  Isn't
what it gets the value returned by the constructor, no matter whether
you assign it to an intermediate value first? I tried it, and the
result is the same.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doesn't know what it wants

2008-01-25 Thread John Machin
On Jan 26, 4:20 pm, Tim Rau <[EMAIL PROTECTED]> wrote:
> Traceback (most recent call last):
>   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> \sandbox.py", line 242, in 
> player = ship()
>   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> \sandbox.py", line 121, in __init__
> self.phyInit()
>   File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
> \sandbox.py", line 147, in phyInit
> moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
> ArgumentError: argument 4: : expected
> vec2d instance instead of vec2d
>
> As far as I can tell, It's getting a vec2d, and it wants a vec2d. I't
> seems like it doesn't know what it wants, but I thought only teenagers
> did that, no programming languages.

It possibly means that it is expecting an instance of a class whose
name is "vec2d"  but you have given it an instance of some *other*
class whose name just happens to be "vec2d".

> clearly, Im missing something.

Yes, some information:
1. what is vec2d, class or function?
2. what do you believe vec2d((0, 0)) should return?
3. what is this belief based on?
4. what has it actually returned this time?
5. what do you believe that cp.cpMomentForCircle expects as argument
4?
6. what is this belief based on?

The ArgumentError exception is raised by ctypes "when a foreign
function call cannot convert one of the passed arguments". Based on
guessin'n'googlin' the cp thing is a set of Python bindings to a
library written in C++ ... have you considered asking the author of
the bindings?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doesn't know what it wants

2008-01-25 Thread Jeroen Ruigrok van der Werven
-On [20080126 06:26], Tim Rau ([EMAIL PROTECTED]) wrote:
>Line 147 reads:
>moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))

I think it expects something like:

# badly named variable, pick something better depending on context
temp = vec2d(0, 0)
cp.cpMomentForCircle(self.mass, .2, 0, temp)

I am curious about your use of double braces for vec2d though. Why ((0,0)) and
not (0, 0)?

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
We have met the enemy and they are ours...
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: eucledian dist calculations

2008-01-25 Thread nodrogbrown
sorry..the last post didn't appear!

> Are you sure? What happens if the vector with the smallest
> sum(distance) is the first one?
>

initially i will set imgindex =0  so if the first one is of smallest
sum..,the image will be reteived by imgindex 0




> (a) Can't you replace the inner loop with something like this:
>distance = abs(input_weight - weights[image, :])

good suggestion ..was doing it java way!

> (b) I doubt that you need the .copy()
> 5. Lose the hard-wired numbers like 30 and 100

those nums were only for clarification..

> 6. Put it inside a function and *TEST* it
>
will do...
thanx john  ,your post really helped
gordon
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Index of maximum element in list

2008-01-25 Thread Scott David Daniels
Hexamorph wrote:
> ...
> What's about l.index(max(l)) ?
What about
max((x,i) for i,x in enumerate(lst))[1]
-- 
http://mail.python.org/mailman/listinfo/python-list


finding child cpu usage of a running child

2008-01-25 Thread Karthik Gurusamy
Hi,

Wondering if there is a way to measure a child process's cpu usage
(sys and user) when the child is still running. I see os.times()
working fine in my system (Linux 2.6.9-42.7.ELsmp), but it gives valid
data only after the child has exited. When the child is alive,
os.times() data for child is zero for both child-sys and child-user
cpu.

My script (process P1) launches child process P2 (using
popen2.Popen3). P2 is a long running process (big compilation). Every
minute or so, from P1, I want to measure how much cpu P2 has consumed
and based on that I can make some estimate on the completion time of
P2 (I have a rough idea how much total cpu P2 needs to complete).

I understand it may be too expensive to update this information to the
parent process when any of the child/grand-child completes; but
wondering if any there is any way to get this info; the expensive
operations is on-demand only when the request is made.

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


Re: Puzzled by behaviour of class with empty constructor

2008-01-25 Thread Tim Rau
On Jan 25, 5:54 pm, [EMAIL PROTECTED] wrote:
> On Jan 25, 5:46 pm, Bjoern Schliessmann 
>
>
> [EMAIL PROTECTED]> wrote:
> > [EMAIL PROTECTED] wrote:
> > > print x.ends,y.ends,z.ends
> > > #
> > > Running the following code outputs:
> >  [(0, 2)] [(0, 2)] [(0, 2)]
>
> > > Can anyone explain this?
>
> > Yes. You bound a single list to the name "ends" inside the class.
> > This name is shared by all instances.
>
> > If you want the instances to each have separate lists, delete
> > the "ends" definition from class declaration and insert "self.ends
> > = []" into __init__.
>
> > I also suggest you to have a look at the tutorial.
>
> > Regards,
>
> > Björn
>
> > --
> > BOFH excuse #49:
>
> > Bogon emissions
>
> Björn,
>
> Thanks for the help.  I had misguidedly defined the members of all of
> my classes as in the example above; I never noticed the issue with any
> of the others because they did not have empty constructors.
>
> Thanks again for the correction.

Yeah! thanks all. I did not realize the distinction either.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generational Interfaces

2008-01-25 Thread Paul Rubin
Carl Banks <[EMAIL PROTECTED]> writes:
> AirplaneInterface = InterfaceTracker("Airplane")
> ...
> set_up_initial_state()
> ...
> AirplaneInterface.report(self)

> Thoughts?  (Surely someone's thought to do this before.)

A decorator might express the idea a little more naturally.  

Also, I'd say the interface tracker really should be told explicitly
when something is part of the interface and when it's specific to a
particular class implementing the interface.  It shouldn't try to
guess this based on some operation appearing in more than one class.
Maybe there's some operation done on all jet planes and on no
propeller planes, that shouldn't be part of the top level airplane
interface.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread Tim Rau
On Jan 25, 10:25 pm, [EMAIL PROTECTED] wrote:
> > I agree that SDL is probably the best choice but for the sake of
> > completeness, Gtk can (at least in theory - I've never tried it) be
> > built against directfb and run without X.
>
> from the Pygame Introduction: Pygame is a Python extension library
> that wraps the SDL library and it's helpers. So you mean, Pygame can
> run without X?
>
> BTW I have nothing against X, I just have not experiences on the GUI
> field, so my feeling was it can run faster without X on the 500MHz AMD
> Geode CPU.
>
> Petr

The problem is not with x: you should be able to run x just fine with
only 133MHZ and a few megs of ram. The performance issues on such a
machine come from things like kde and gnome. use one of the simpler
window managers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Doesn't know what it wants

2008-01-25 Thread Tim Rau
Traceback (most recent call last):
  File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
\sandbox.py", line 242, in 
player = ship()
  File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
\sandbox.py", line 121, in __init__
self.phyInit()
  File "C:\Documents and Settings\Owner\My Documents\NIm's code\sandbox
\sandbox.py", line 147, in phyInit
moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
ArgumentError: argument 4: : expected
vec2d instance instead of vec2d

As far as I can tell, It's getting a vec2d, and it wants a vec2d. I't
seems like it doesn't know what it wants, but I thought only teenagers
did that, no programming languages. clearly, Im missing something.

Line 147 reads:
moi = cp.cpMomentForCircle(self.mass, .2, 0, vec2d((0,0)))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I use the up and down, left and right arrow keys to control a Python Pgm

2008-01-25 Thread Tim Rau
On Jan 25, 10:48 pm, "jitrowia" <[EMAIL PROTECTED]> wrote:
> I was wondering what kind of python code I would need to enable me to
> use the up and down, left and right arrow keys to control software
> programming decisions within a Python Program.
>
> Any direction and advice would be greatly appreciated,
>
> Thank You,
> Rodney

"software programming decisions" is awfully vague. COuld oyu narrow
down exactly what you want to do?
-- 
http://mail.python.org/mailman/listinfo/python-list


Generational Interfaces

2008-01-25 Thread Carl Banks
While thinking about generational garbage collection, the thought of
generational interfaces occurred to me.  I'd thought I'd run it by you
guys.  I'm curious if there are any examples of this out there.

I've opined on this chat room before that interfaces are more often
cumbersome than helpful, especially in the early stages of a project
where lots of refactoring is (or ought to be) happening.  But as
projects mature, interfaces do too, and that made me think interfaces
could be generated automatically by monitoring the software over time.

As an example, say I'm writing a flight simulator, and I have a
abstract base class Airplane, that I want to have an interface
someday, but I don't know what it is yet.  So I define an

AirplaneInterface = InterfaceTracker("Airplane")

What this does is to open a sort of persistent database called
Airplane (details aren't important now).  The database tracks all
objects that claim to implement the interface.

So say the first airplane is a Piper Cherokee.  I'd write a class like
this:

class PiperCherokeeX1(object):
wingspan = 52.2
wingchord = 7.9
...
def __init__(self):
self.x = 0.0
self.y = 0.0
self.z = 0.0
...
set_up_initial_state()
...
AirplaneInterface.report(self)
def move_stick(self,dx,dy):
...
def move_thottle(self,ds):
...
def move_rudder_pedals(self,ddr):
...
def camera_matrix(self):
return self._quat_to_matrix(self.q0,self.q1,self.q2,self.q3)
def step(self,dt):
...

The key here is the call to AirplaneInterface.report() at the end of
__init__; this tells the interface tracker that, as of this call, this
object is implementing the Aircraft interface.

At this point, the interface tracker notes that PiperCherokeeX1 object
has certain methods (move_stick, move_throttle, etc), certain class
attributes, and certain instance attributes.  And that's all it does--
at first.  It just writes information into the database.

As time passes, and development continues, methods and data are added,
changed, reconfigured.  For instance, I might split up move_stick()
into move_stick_x() and move_stick_y() for some reason.  Then I might
get rid of these functions altogether in favor of a
move_control(self,n,dx).  And so on.  I add more classes that
implement the Aircraft interface, too.  They look almost nothing like
the original interface.

However, through all that, the class attribute "wingspan" remains
there.  Until one day when the project is quite mature I add a new
class, say Airbus380, that fails to define "wingspan".  When this
class calls AirplaneInterface.report(), it raises an
InterfaceException.

Basically, the InterfaceTracker decides, after some threshold of
nearly universal usage of a certain method or attribute, that it has
become a required part of the interface and starts raising exceptions
when it's not there.

Make sense?  Details can vary, but that's the basic idea.  In this
way, you can combine some of the openness that helps in early
development, but also have some of the benefits of stricter typing
when things mature and turn out to be pretty strictly useful, without
much effort.

Thoughts?  (Surely someone's thought to do this before.)


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


Re: translating Python to Assembler

2008-01-25 Thread Grant Edwards
On 2008-01-26, ajaksu <[EMAIL PROTECTED]> wrote:
> On Jan 25, 11:10 pm, [EMAIL PROTECTED] wrote:
>> Once a python py file is compiled into a pyc file, I can disassemble
>> it into assembler. Assembler is nothing but codes, which are
>> combinations of 1's and 0's. You can't read a pyc file in a hex
>> editor, but you can read it in a disassembler. It doesn't make a lot
>> of sense to me right now, but if I was trying to trace through it with
>> a debugger, the debugger would disassemble it into assembler, not
>> python.
>
> Please, tell me you're kidding...

I think we've been trolled.  Nobody could be that stubbornly
ignorant.

-- 
Grant Edwards   grante Yow!  This is PLEASANT!
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: translating Python to Assembler

2008-01-25 Thread Grant Edwards
On 2008-01-26, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Once a python py file is compiled into a pyc file, I can disassemble
> it into assembler.

No you can't.  It's not native machine code.  It's byte code
for a virtual machine.

> Assembler is nothing but codes, which are combinations of 1's
> and 0's. You can't read a pyc file in a hex editor, but you
> can read it in a disassembler.

NO YOU CAN'T.

> It doesn't make a lot of sense to me right now,

That's because IT'S NOT MACHINE CODE.

> but if I was trying to trace through it with a debugger,

That wouldn't work.

> the debugger would disassemble it into assembler,
> not python.

You can "disassemble" random bitstreams into assembler.  That
doesn't make it a useful thing to do.

[Honestly, I think you're just trolling.]


-- 
Grant Edwards   grante Yow!  Yow! Is this sexual
  at   intercourse yet?? Is it,
   visi.comhuh, is it??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression negate a word (not character)

2008-01-25 Thread Mark Tolonen

"Summercool" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> somebody who is a regular expression guru... how do you negate a word
> and grep for all words that is
>
>  tire
>
> but not
>
>  snow tire
>
> or
>
>  snowtire
>
> so for example, it will grep for
>
>  winter tire
>  tire
>  retire
>  tired
>
> but will not grep for
>
>  snow tire
>  snow   tire
>  some snowtires
>
> need to do it in one regular expression
>

What you want is a negative lookbehind assertion:

>>> re.search(r'(?>> re.search(r'(?

Unfortunately you want variable whitespace:

>>> re.search(r'(?", line 1, in 
  File "C:\dev\python\lib\re.py", line 134, in search
return _compile(pattern, flags).search(string)
  File "C:\dev\python\lib\re.py", line 233, in _compile
raise error, v # invalid expression
error: look-behind requires fixed-width pattern
>>>

Python doesn't support lookbehind assertions that can vary in size.  This 
doesn't work either:

>>> re.search(r'(?

Here's some code (not heavily tested) that implements a variable lookbehind 
assertion, and a function to mark matches in a string to demonstrate it:

### BEGIN CODE ###

import re

def finditerexcept(pattern,notpattern,string):
for matchobj in 
re.finditer('(?:%s)|(?:%s)'%(notpattern,pattern),string):
if not re.match(notpattern,matchobj.group()):
yield matchobj

def markexcept(pattern,notpattern,string):
substrings = []
current = 0

for matchobj in finditerexcept(pattern,notpattern,string):
substrings.append(string[current:matchobj.start()])
substrings.append('[' + matchobj.group() + ']')
current = matchobj.end() #

substrings.append(string[current:])
return ''.join(substrings)

### END CODE ###

>>> sample='''winter tire
... tire
... retire
... tired
... snow tire
... snowtire
... some snowtires
... '''
>>> print markexcept('tire','snow\s*tire',sample)
winter [tire]
[tire]
re[tire]
[tire]d
snow tire
snowtire
some snowtires

--Mark

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


Re: Index of maximum element in list

2008-01-25 Thread Raymond Hettinger
On Jan 25, 1:47 pm, Hexamorph <[EMAIL PROTECTED]> wrote:
> Henry Baxter wrote:
> > Oops, gmail has keyboard shortcuts apparently, to continue:
>
> > def maxi(l):
> >     m = max(l)
> >     for i, v in enumerate(l):
> >         if m == v:
> >             return i
>
> What's about l.index(max(l)) ?

from itertools import izip, count
answer  = max(izip(l, count()))[1]


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


How can I use the up and down, left and right arrow keys to control a Python Pgm

2008-01-25 Thread jitrowia
I was wondering what kind of python code I would need to enable me to 
use the up and down, left and right arrow keys to control software 
programming decisions within a Python Program.

Any direction and advice would be greatly appreciated,

Thank You,
Rodney

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


Re: "just like Java" (was :Re: translating Python to Assembler)

2008-01-25 Thread Christian Heimes
Paul Boddie wrote:
> Well, it is important to make distinctions when people are wondering,
> "If Python is 'so slow' and yet everyone tells me that the way it is
> executed is 'just like Java', where does the difference in performance
> come from?" Your responses seemed to focus more on waving that issue
> away and leaving the whole topic in the realm of mystery. The result:
> "Python is just like Java apparently, but it's slower and I don't know
> why."

Short answer: Python doesn't have a Just In Time (JIT) compiler. While
Java's JIT optimizes the code at run time Python executes the byte code
without additional optimizations.

Christian

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


Re: regular expression negate a word (not character)

2008-01-25 Thread Ben Morrow
[newsgroups line fixed, f'ups set to clpm]

Quoth Summercool <[EMAIL PROTECTED]>:
> On Jan 25, 5:16 pm, Summercool <[EMAIL PROTECTED]> wrote:
> > somebody who is a regular expression guru... how do you negate a word
> > and grep for all words that is
> >
> >   tire
> >
> > but not
> >
> >   snow tire
> >
> > or
> >
> >   snowtire
> 
> i could think of something like
> 
>   /[^s][^n][^o][^w]\s*tire/i
> 
> but what if it is not snow but some 20 character-word, then do we need
> to do it 20 times to negate it?  any shorter way?

This is no good, since 'snoo tire' fails to match even though you want
it to. You need something more like

/ (?: [^s]... | [^n].. | [^o]. | [^w] | ^ ) \s* tire /ix

but that gets *really* tedious for long strings, unless you generate it.

Ben

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


Re: translating Python to Assembler

2008-01-25 Thread Chris Mellon
On Jan 25, 2008 9:09 PM, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> On Wed, 23 Jan 2008 08:49:20 +0100, Christian Heimes wrote:
>
> > It's even
> > possible to write code with Python assembly and compile the Python
> > assembly into byte code.
>
> Really? How do you do that?
>
> I thought it might be compile(), but apparently not.
>

There are tools for it in the undocumented compiler.pyassem module.
You have to pretty much know what you're doing already to use it - I
spent a fun (but unproductive) week figuring out how to use it and
generated customized bytecode for certain list comps. Malformed
hand-generated bytecode stuffed into code objects is one of the few
ways I know of to crash the interpreter without resorting to calling C
code, too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread petr . jakes . tpc

> I agree that SDL is probably the best choice but for the sake of
> completeness, Gtk can (at least in theory - I've never tried it) be
> built against directfb and run without X.

from the Pygame Introduction: Pygame is a Python extension library
that wraps the SDL library and it's helpers. So you mean, Pygame can
run without X?

BTW I have nothing against X, I just have not experiences on the GUI
field, so my feeling was it can run faster without X on the 500MHz AMD
Geode CPU.

Petr


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


Re: translating Python to Assembler

2008-01-25 Thread Steven D'Aprano
On Wed, 23 Jan 2008 08:49:20 +0100, Christian Heimes wrote:

> It's even
> possible to write code with Python assembly and compile the Python
> assembly into byte code.

Really? How do you do that?

I thought it might be compile(), but apparently not.



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


Re: ElementTree.fromstring(unicode_html)

2008-01-25 Thread John Machin
On Jan 26, 1:11 pm, globophobe <[EMAIL PROTECTED]> wrote:
> This is likely an easy problem; however, I couldn't think of
> appropriate keywords for google:
>
> Basically, I have some raw data that needs to be preprocessed before
> it is saved to the database e.g.
>
> In [1]: unicode_html = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f
> \u3044\r\n'
>
> I need to turn this into an elementtree, but some of the data is
> japanese whereas the rest is html. This string contains a .

>>> import unicodedata as ucd
>>> s = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f\u3044\r\n'
>>> [ucd.name(c) if ord(c) >= 128 else c for c in s]
['HIRAGANA LETTER SA', 'HIRAGANA LETTER MU', 'HIRAGANA LETTER I',
'FULLWIDTH SOLIDUS', u'\r', u'\n', 'HIRAGANA LETTER TU', 'HIRAGANA
LETTER ME', 'HIRAGANA LETTER TA', 'HIRAGANA LETTER I', u'\r', u'\n']
>>>

Where in there is the  ??

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


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread Chris Mellon
On Jan 25, 2008 5:17 PM, Paul Boddie <[EMAIL PROTECTED]> wrote:
> On 25 Jan, 22:06, "Lorenzo E. Danielsson"
> <[EMAIL PROTECTED]> wrote:
> >
> > What you need then is something like SVGAlib (http;//svgalib.org). Only
> > really old people like myself know that it exists. I've never heard of
> > any Python bindings for it, but that might be where you come in. I
> > haven't looked at SVGAlib for years, and I'm not sure about the state of
> > the video drivers. I suggest you look at that first.
>
> I believe that SVGAlib was superseded by GGI and other projects, and I
> recall that SVGAlib was considered to be something of a nightware with
> respect to how it handles various resources. Certainly, I haven't been
> very impressed by the behaviour of software using it.
>
> > You could also look at GGI (http://ggi-project.org). GGI has different
> > output targets. IIRC, one of them is directfb. To tell you the truth
> > I've never really used GGI. There seems to be a python wrapper for GGI,
> > although it is fairly old. Maybe you could look at the code for some ideas.
>
> I've had to build software using GGI, and the biggest problem has been
> getting packages for it. That said, it seemed to work fairly
> acceptably once built and installed. Meanwhile, some people favour
> Allegro [1] for this kind of work, and I've been confronted with newly
> developed software which uses Allegro, so it's arguably in a different
> maintenance state than something like SVGAlib or GGI.
>
> > You should also be able to compile SDL to be able to use directfb as a
> > target. If your libSDL handles it, then that should apply to wrapper
> > libraries as well, including pygame. I've never tried running SDL apps
> > this way, but if it works well, that would probably be your 'best' option.
>
> I'd agree with these sentiments; SDL seems to be the best supported
> technology of this kind in the Python universe, and one of the most
> widely deployed in general; I've felt quite comfortable building
> software against it. It would be very interesting to see whether a
> framebuffer-based SDL could support Pygame, and I imagine that the
> Pygame mailing list might already have some answers in its archives on
> this topic.
>


I agree that SDL is probably the best choice but for the sake of
completeness, Gtk can (at least in theory - I've never tried it) be
built against directfb and run without X.
-- 
http://mail.python.org/mailman/listinfo/python-list


pyfov Package Index link broken

2008-01-25 Thread Martin Manns
Hi,

I am looking for the code of pyfov, which is on the Package Index.
However, the link is broken and the author does not seem to respond to
e-mails.

Any chance to get hands on the code?

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


ElementTree.fromstring(unicode_html)

2008-01-25 Thread globophobe
This is likely an easy problem; however, I couldn't think of
appropriate keywords for google:

Basically, I have some raw data that needs to be preprocessed before
it is saved to the database e.g.

In [1]: unicode_html = u'\u3055\u3080\u3044\uff0f\r\n\u3064\u3081\u305f
\u3044\r\n'

I need to turn this into an elementtree, but some of the data is
japanese whereas the rest is html. This string contains a .

In [2]: e = ET.fromstring('%s' % unicode_html)
In [2]: e.text
Out[3]: u'\u3055\u3080\u3044\uff0f\n\u3064\u3081\u305f\u3044\n'
In [4]: len(e)
Out[4]: 0

How can I decode the unicode html  into a string that
ElementTree can understand?

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


Re: translating Python to Assembler

2008-01-25 Thread ajaksu
On Jan 25, 11:36 pm, ajaksu <[EMAIL PROTECTED]> wrote:
> On Jan 25, 11:10 pm, [EMAIL PROTECTED] wrote:
[...]

Gaah, is this what's going on?

[EMAIL PROTECTED]:~$ cat error.txt
This is not assembler...

[EMAIL PROTECTED]:~$ ndisasm error.txt
  54push sp
0001  686973push word 0x7369
0004  206973and [bx+di+0x73],ch
0007  206E6Fand [bp+0x6f],ch
000A  7420  jz 0x2c
000C  61popa
000D  7373  jnc 0x82
000F  656D  gs insw
0011  626C65bound bp,[si+0x65]
0014  722E  jc 0x44
0016  2Edb 0x2E
0017  2Edb 0x2E
0018  0Adb 0x0A

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


Re: translating Python to Assembler

2008-01-25 Thread ajaksu
On Jan 25, 11:10 pm, [EMAIL PROTECTED] wrote:
> Once a python py file is compiled into a pyc file, I can disassemble
> it into assembler. Assembler is nothing but codes, which are
> combinations of 1's and 0's. You can't read a pyc file in a hex
> editor, but you can read it in a disassembler. It doesn't make a lot
> of sense to me right now, but if I was trying to trace through it with
> a debugger, the debugger would disassemble it into assembler, not
> python.


Please, tell me you're kidding...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: translating Python to Assembler

2008-01-25 Thread over
On Thu, 24 Jan 2008 08:02:06 GMT, Tim Roberts <[EMAIL PROTECTED]> wrote:

>Bjoern Schliessmann <[EMAIL PROTECTED]> wrote:
>
>>Grant Edwards wrote:
>>
>>> Trying to find assembly language stuff to look at is futile.
>>> Python doesn't get compiled into assembly language.
>>
>>So, how do processors execute Python scripts? :)
>
>Is that a rhetorical question?  Grant is quite correct; Python scripts (in
>the canonical CPython) are NOT compiled into assembly language.  Scripts
>are compiled to an intermediate language.  Processors execute Python
>scripts when the interpreter, written in a high-level language and compiled
>to assembly, interprets the intermediate language created by the Python
>"compiler".

Intel processors can only process machine language, which is
essentially binary 1's and 0's. All  a processor understands is
voltages, either 0 Volts or 5 volts on older systems, or 3.3 volts and
less on newer systems. Generally, a positive voltage is a logical 1
and 0 volts is a logical 0. There's no way for a processor to
understand any higher level language, even assembler, since it is
written with hexadecimal codes and basic instructions like MOV, JMP,
etc. The assembler compiler can convert an assembler file to a binary
executable, which the processor can understand.

If you look at the Python interpreter, Python.exe, or Pythonw, the
Windows interface, or the Python24.dll, the main library for python,
you will see they are normal 32 bit PE files. That means they are
stored on disk in codes of 1's and 0's, and decompile into assembler.
You can't decompile them into Python directly, although I'm sure
someone is trying. No compiled file can be decompiled into it's
original format easily or automatically, although there are
decompilers that will convert them to a reasonable assembler
decompilation. 

If a Python script was understood directly by the processor, no
interpreter would be necessary. Ask yourself what the interpreter is
doing. It's taking the scripting language and converting to the
language of the operating system. However, it's the processor that
dictates how programs are written, not the OS. That's why a Linux OS
will run on an Intel machine, as a Windows OS does. Both Linux and
Windows compile down to binary files, which are essentially 1's and
0's arranged in codes that are meaningful to the processor. 

Once a python py file is compiled into a pyc file, I can disassemble
it into assembler. Assembler is nothing but codes, which are
combinations of 1's and 0's. You can't read a pyc file in a hex
editor, but you can read it in a disassembler. It doesn't make a lot
of sense to me right now, but if I was trying to trace through it with
a debugger, the debugger would disassemble it into assembler, not
python. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: read and readline hanging

2008-01-25 Thread Thomas Bellman
Olivier Lefevre <[EMAIL PROTECTED]> wrote:

>> 1. The subprocess has stopped producing output.

> Indeed, if I do this interactively, I can tell after 3 lines that I've
> gotten all there is to get right now and the fourth readline() call
> hangs.

Can you really?  How do you know if the program has finished or
if it is just taking a very long time to produce the next line in
its response?  Unless there is some way to differentiate between
the last line all the other lines of a response, you can't really
be sure.

> But how can I find out *programmatically* that there is no more
> input?

It is possible to check if there is something more to read at the
moment, but you can't check if the subprocess will produce more
to read in the future.

To check if there is something to read at this very moment, you
can use any of the following methods:

  - select.select()
  - the FIONREAD ioctl (the ioctl() function lives in the fcntl
module, and the FIONREAD constant is in the termios module)
  - set the underlying file descriptor in non-blocking mode:
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NDELAY)
After that, reads on the pipe will raise an IOError exception
with the errorcode EWOULDBLOCK.
  - start a thread that does blocking reads from the pipe, and
puts the chunks it reads on a queue for your main thread to
grab.

For the last approach, you might be interrested in my asyncproc
module, which does exactly that.  You can download it from
.

However, none of these approaches absolves you from the necessity
of knowing when one response ends.  You still need to solve that
problem.

The proper way is to define a protocol between your program and
the subprocess, in which you can clearly tell when you have
reached the end of a response.  Then you need to get the program
you are calling to adher to that protocol, of course...

The SMTP protocol is a good example of how this can look.  In
SMTP, each response to a command consists of a number of lines.
Each line has a three-digit response code, an "end of response"
flag, and a text message.  The "end of response" flag is a space
(" ") for the last line in the response, and a dash ("-") for all
the other lines.  The response to an EHLO command can look like
this:

250-sellafield Hello localhost [127.0.0.1], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-EXPN
250-VERB
250-8BITMIME
250-SIZE
250-DSN
250-ETRN
250-DELIVERBY
250 HELP

Since there is a space instead of a dash after the "250" code in
the last line above, the SMTP client knows that there won't be
any more lines in response to its command.

If you can't get the program you are calling to follow some
protocol like this, then you can only make guesses.  Sometimes
you can make fairly good guesses, and sometimes it will be more
or less impossible...


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"Life IS pain, highness.  Anyone who tells   !  bellman @ lysator.liu.se
 differently is selling something."  !  Make Love -- Nicht Wahr!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: basic output question

2008-01-25 Thread Wildemar Wildenburger
John Deas wrote:
> Hi, I am very new to Python (1 evening...)
> I need to process a series of files (toto-1.txt toto-2.txt toto-3.txt
> toto-4.txt), and as such I created a small program to go through the
> files in a directory. I want to call the script with arguments, like
> 
> python script.py toto- 1 1 4
> 
> my script is as follow :
> 
> import sys
> sys.argv
> header= sys.argv[1]
> start =eval(sys.argv[2])
> step  =eval(sys.argv[3])
> nbit  =eval(sys.argv[4])
> 
Style note: You should probably use int() instead of eval. Not only is 
this safer (as in security), it is also safer (as in robust), because it 
will throw an error early if you feed it something other than an int.


> for i in range(nbit):
>   filename=header+str(start+i*step)+'.txt'
>   f=open(filename,'r')
>   f.read()
>   f.close()
> 
> My problem is that f.read() outputs nothing, and should I print
> filename, I can check that they are well formed, and the files sits in
> the same directory as my script.
> 
f.read() spills the text into nothingness. You may want to write its 
output to a variable. ;)

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


Re: Problem with Tkinter scrollbar callback

2008-01-25 Thread Russell E. Owen
In article <[EMAIL PROTECTED]>,
 "Ivan Van Laningham" <[EMAIL PROTECTED]> wrote:

> Hi All--
> That helps.  Doing a get() on the scrollbar before a set(0.0,0.0)
> returns a 4-tuple:  (0.0, 0.0, 0.0, 0.0)  !  I did the set(0.0,0.0)
> and now the callback gets the correct number of arguments.
> 
> However, I'm still getting the weird behaviour when clicking the
> arrowheads--and the heads are all I want.  They act like they've been
> set to a keybounce timeout of about a millisecond. ...  The arrow
> click increments the number of cells in a table row (effectively), and
> it shoots up from 5 to 26 columns almost instantly (that's the
> internal max I set).

Is the scroll bar's repeatinterval set to a reasonable value?

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


Re: Module/package hierarchy and its separation from file structure

2008-01-25 Thread Carl Banks
On Jan 25, 6:45 pm, Ben Finney <[EMAIL PROTECTED]>
wrote:
> "Gabriel Genellina" <[EMAIL PROTECTED]> writes:
> > You can also put, in animal/__init__.py:
> > from monkey import Monkey
> > and now you can refer to it as org.lib.animal.Monkey, but keep the
> > implementation of Monkey class and all related stuff into
> > .../animal/monkey.py
>
> This (as far as I can understand) is exactly the solution the original
> poster desired to "shoot down", for reasons I still don't understand.

Come on, the OP explained it quite clearly in his original post.  Did
you guys even read it?

The module where org.lib.animal.Monkey is actually defined should be
an implementation detail of the library, but simply importing Monkey
into org.lib.animal doesn't quite make it one.

If a user pickles a Monkey class, and then the OP decides to refactor
the Monkey class into a new module (say
org.lib.animal.primate.monkey), then the user would not be able to
unpickle it.  Because, you see, pickles record the module a class is
defined in.  So, now the user has to worry about where Monkey is
actually defined.  It is not an implementation detail.

The solution is to modify the class's __module__ attribute as well as
importing it, as I've already pointed out:

from org.lib.animal.monkey import Monkey
Monkey.__module__ = 'org.lib.animal'

This should be enough to satisfy the OP's requirements, at least for
classes, without softening the one-to-one module-to-file relationship,
or using "hacks".

In fact, I'd say this is good practice.


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


Re: Email module, how to add header to the top of an email?

2008-01-25 Thread David Erickson
On Jan 25, 5:04 am, "Karlheinz Klingbeil"
<[EMAIL PROTECTED]> wrote:
> Am 25.01.2008, 06:21 Uhr, schrieb David Erickson <[EMAIL PROTECTED]>:
>
> > Bottom of the headers... but I am looking to insert at the top, and re-
> > ordering/inserting does matter depending on what type of header you
> > are, received headers for example must be inserted at the top of the
> > header list so you can watch the progression of the email.  I was
> > unable to find a clean way to do this via the API which seems very
> > strange to me.. but perhaps I am just missing something?
>
> I think your are really missing something. First, Email-headers are
> unordered
> and every relay can, and probably will,  rearrange them, add or delete
> headers.
> You therefore most definitely should not add any headers which are
> position-dependent.
> If you want to track mails somehow, add headers with timestamps.
> This way you can watch the progression of an email without being
> dependend on "sorted" headerlines.

This is incorrect, quoting directly from RFC 2822:

   It is important to note that the header fields are not guaranteed
to
   be in a particular order.  They may appear in any order, and they
   have been known to be reordered occasionally when transported over
   the Internet.  However, for the purposes of this standard, header
   fields SHOULD NOT be reordered when a message is transported or
   transformed.  More importantly, the trace header fields and resent
   header fields MUST NOT be reordered, and SHOULD be kept in blocks
   prepended to the message.  See sections 3.6.6 and 3.6.7 for more
   information.

Trace header fields are not to be ordered, and should be prepended
when added to a message.  Now that said I am not trying to track
anything, I simply want to prepend my additional headers onto the top
of the email, and seem to be unable to do that via the API, which I
think ought to be possible.  If for example I was writing some kind of
an SMTP server with Python and needed to add said trace headers they
would need to be prepended, and currently cannot be (without doing it
by hand).

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


Re: basic output question

2008-01-25 Thread Alan Isaac
John Deas wrote: 
> My problem is that f.read() outputs nothing

Since ``open`` did not give you an IOError,
you did get a handle to the files,
so this suggests that the files you read
are empty...

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


python and multithreading problem

2008-01-25 Thread whatazor
Hi all,
I made an application that use multithreading (indifferently importing
thread or  threading module) , but when I call some wrapped modules
(with swig) from my application they run like there is only a single
thread (and my application gui ,made with wxPython, freezes). If I use
other modules not wrapped, but created for test that multithread
works, and gui is not freezing are ok.
Modules that wrap DLL are not my product but are created by another
developer with VS.NET, and the only thing I can think is that they're
builded without multithreaded compiler option. Can it be another cause
for this behaviour, can this explanation be correct? maybe also swig
have a multithreading option.

thank you in advance
w
-- 
http://mail.python.org/mailman/listinfo/python-list


Exceptions on delete in pysqlite

2008-01-25 Thread Wildemar Wildenburger
Hi there,

Using pysqlite, I'd like to check if some dataset that I removed has 
been in the database at all. Ideally I'd like pysqlite to raise an 
Exception if deleting does nothing. Is that possible?

Codewise, I'd like the following, but without me checking for and 
raising the exception myself:

cur = con.execute("""DELETE FROM SomeTable WHERE id=? AND name=?""",
  (ID, NAME))
if cur.rowcount == 0:
 raise Exception


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


Re: a newbie regex question

2008-01-25 Thread Max Erickson
"Dotan Cohen" <[EMAIL PROTECTED]> wrote:
> Maybe you mean:
> for match in re.finditer(r'\([A-Z].+[a-z])\', contents):
> Note the last backslash was in the wrong place.

The location of the backslash in the orignal reply is correct, it is 
there to escape the closing paren, which is a special character:

>>> import re
>>> s='Abcd\nabc (Ab), (ab)'
>>> re.findall(r'\([A-Z].+[a-z]\)', s)
['(Ab), (ab)']

Putting the backslash at the end of the string like you indicated 
results in a syntax error, as it escapes the closing single quote of 
the raw string literal: 

>>> re.findall(r'\([A-Z].+[a-z])\', s)
   
SyntaxError: EOL while scanning single-quoted string
>>> 


max


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


Re: Module/package hierarchy and its separation from file structure

2008-01-25 Thread Ben Finney
"Gabriel Genellina" <[EMAIL PROTECTED]> writes:

> You can also put, in animal/__init__.py:
> from monkey import Monkey
> and now you can refer to it as org.lib.animal.Monkey, but keep the
> implementation of Monkey class and all related stuff into
> .../animal/monkey.py

This (as far as I can understand) is exactly the solution the original
poster desired to "shoot down", for reasons I still don't understand.

-- 
 \  "Reichel's Law: A body on vacation tends to remain on vacation |
  `\ unless acted upon by an outside force."  -- Carol Reichel |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: find minimum associated values

2008-01-25 Thread Alan Isaac
[EMAIL PROTECTED] wrote:
> I'd use the first solution.

It can be speeded up a bit with
a try/except:

for k,v in kv:
try:
if d[k] > v:
d[k] = v
except KeyError:
d[k] = v

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


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread Paul Boddie
On 25 Jan, 22:06, "Lorenzo E. Danielsson"
<[EMAIL PROTECTED]> wrote:
>
> What you need then is something like SVGAlib (http;//svgalib.org). Only
> really old people like myself know that it exists. I've never heard of
> any Python bindings for it, but that might be where you come in. I
> haven't looked at SVGAlib for years, and I'm not sure about the state of
> the video drivers. I suggest you look at that first.

I believe that SVGAlib was superseded by GGI and other projects, and I
recall that SVGAlib was considered to be something of a nightware with
respect to how it handles various resources. Certainly, I haven't been
very impressed by the behaviour of software using it.

> You could also look at GGI (http://ggi-project.org). GGI has different
> output targets. IIRC, one of them is directfb. To tell you the truth
> I've never really used GGI. There seems to be a python wrapper for GGI,
> although it is fairly old. Maybe you could look at the code for some ideas.

I've had to build software using GGI, and the biggest problem has been
getting packages for it. That said, it seemed to work fairly
acceptably once built and installed. Meanwhile, some people favour
Allegro [1] for this kind of work, and I've been confronted with newly
developed software which uses Allegro, so it's arguably in a different
maintenance state than something like SVGAlib or GGI.

> You should also be able to compile SDL to be able to use directfb as a
> target. If your libSDL handles it, then that should apply to wrapper
> libraries as well, including pygame. I've never tried running SDL apps
> this way, but if it works well, that would probably be your 'best' option.

I'd agree with these sentiments; SDL seems to be the best supported
technology of this kind in the Python universe, and one of the most
widely deployed in general; I've felt quite comfortable building
software against it. It would be very interesting to see whether a
framebuffer-based SDL could support Pygame, and I imagine that the
Pygame mailing list might already have some answers in its archives on
this topic.

Paul

[1] http://www.talula.demon.co.uk/allegro/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Index of maximum element in list

2008-01-25 Thread Henry Baxter
Thanks Hexamorph and Neal. Somehow I didn't make the connection with using
'index', but I'm all sorted out now :)

On Jan 25, 2008 1:47 PM, Hexamorph <[EMAIL PROTECTED]> wrote:

> Henry Baxter wrote:
> > Oops, gmail has keyboard shortcuts apparently, to continue:
> >
> > def maxi(l):
> > m = max(l)
> > for i, v in enumerate(l):
> > if m == v:
> > return i
> >
>
> What's about l.index(max(l)) ?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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

Re: paging in python shell

2008-01-25 Thread gagsl-py2

--- Alex K <[EMAIL PROTECTED]> escribió:

> Thank you for this interesting tip. However I'm not
> sure to know how
> to use it. It seems pydoc.pager('text') just pages
> the text passed in.
> How do I actually make the python shell use a
> different pager?

I'm unsure of what you want. Do you want the print
statement, inside the Python interpreter, to page its
output? Write a function to page the output the way
you like, and assign it to sys.displayhook (see
http://docs.python.org/lib/module-sys.html#l2h-5124 )

-- 
Gabriel Genellina


  Tarjeta de crédito Yahoo! de Banco Supervielle.
Solicitá tu nueva Tarjeta de crédito. De tu PC directo a tu casa. 
www.tuprimeratarjeta.com.ar 
-- 
http://mail.python.org/mailman/listinfo/python-list


How to modify the content of an email

2008-01-25 Thread alejandro . valdez
Hello, I'm trying to make a python script that take an email in (raw)
text format, and add a footer to the text (or html) body of the email.

I'm aware of the email and email.mime modules, but I can't figure out
how to identify 'the main text (or html) content' from the email, and
how to be sure that I don't incorrectly identify a txt (or html)
attach as the main content of the email.

By 'main text (or html) content' I mean the text (or html) that is
showed by a Mail User Agent when it display the email to the
recipient.

Thanks in advance.

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


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> Hi,
> I am working with the Python 2.5 running on the command line version
> of Linux Ubuntu 7.04. This means NO X-windows, NO GTK/Gnome, NO
> computer mouse, on my machine (AMD Geode 500MHz CPU, VGA output).
> 
> I would like to write some really light weighted GU interface. My
> concept is to have just few user screens (about 10) controlled via 4
> or 5 HW buttons connected to the GPIO pins they are available on the
> motherboard (the HW design and the SW concept of reading this buttons
> is already solved).
> 
> After some googling, I have found below mentioned can be usable, but
> first, I would like to ask here for your opinions/experiences/advices.
> 
> Best regards
> 
> Petr Jakes
> 
> http://www.libsdl.org/
> http://pyfltk.sourceforge.net/
> http://www.pygame.org/news.html
> http://pyui.sourceforge.net/
> http://pyglet.org/


pygame is based on sdl, pyui can render to pygame. So if you use that 
stack, it's a question of SDL being capable of directly rendering to 
something like SVGALib.

Pyglet is OpenGL, and fltk seems to need X.

But WHY aren't you just installing X? You don't need to run a 
full-fledged Desktop like gnome or kde on top of it - just use ratpoison 
or anything else as desktop manager & be happy.

After all, my first PC had 16MB of RAM and 133MHz - and ran X w/o any 
problems.

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


Re: Puzzled by behaviour of class with empty constructor

2008-01-25 Thread dbaston
On Jan 25, 5:46 pm, Bjoern Schliessmann  wrote:
> [EMAIL PROTECTED] wrote:
> > print x.ends,y.ends,z.ends
> > #
> > Running the following code outputs:
>  [(0, 2)] [(0, 2)] [(0, 2)]
>
> > Can anyone explain this?
>
> Yes. You bound a single list to the name "ends" inside the class.
> This name is shared by all instances.
>
> If you want the instances to each have separate lists, delete
> the "ends" definition from class declaration and insert "self.ends
> = []" into __init__.
>
> I also suggest you to have a look at the tutorial.
>
> Regards,
>
> Björn
>
> --
> BOFH excuse #49:
>
> Bogon emissions

Björn,

Thanks for the help.  I had misguidedly defined the members of all of
my classes as in the example above; I never noticed the issue with any
of the others because they did not have empty constructors.

Thanks again for the correction.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Puzzled by behaviour of class with empty constructor

2008-01-25 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> Hello,
> 
> I have a class called 'Axis' that I use as a base class for several
> types of axes that can be created by a grid generation program that I
> have written: equally-spaced grids, logarithmic grids, etc.  In any
> case, if I use this base class by itself, I see some puzzling
> behaviour:
> #
> class Axis:
> ends = []
> N = None
> def __init__(self):
> pass
> 
> x = Axis()
> y = Axis()
> z = Axis()
> 
> x.ends.append((0,2))
> 
> print x.ends,y.ends,z.ends
> #
> Running the following code outputs:
 [(0, 2)] [(0, 2)] [(0, 2)]
> 
> Can anyone explain this?

It's simple - you didn't create an instance-variable, but instead a 
class-variable.

You need to do this:

class Axis:

def __init__(self):
self.ends = []


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


Re: Puzzled by behaviour of class with empty constructor

2008-01-25 Thread Tomek Paczkowski
[EMAIL PROTECTED] wrote:

> Hello,
> 
> I have a class called 'Axis' that I use as a base class for several
> types of axes that can be created by a grid generation program that I
> have written: equally-spaced grids, logarithmic grids, etc.  In any
> case, if I use this base class by itself, I see some puzzling
> behaviour:
> #
> class Axis:
> ends = []
> N = None
> def __init__(self):
> pass
> 
> x = Axis()
> y = Axis()
> z = Axis()
> 
> x.ends.append((0,2))
> 
> print x.ends,y.ends,z.ends
> #
> Running the following code outputs:
 [(0, 2)] [(0, 2)] [(0, 2)]
> 
> Can anyone explain this?

Well, you are using a class variable - Axis.ends. It's shared among all
instances of Axis class. To have it separate setup it in __init__ like:

class Axix:
def __init__(self):
self.ends = []
self.N = None

You see, code inside class, but outside methods is executed only once and
any variables are then linked with class, and not instances (more/less).
Take look at: http://docs.python.org/tut/node11.html

   ~TomekP

-- 
Someone whom you reject today, will reject you tomorrow.

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


Re: Puzzled by behaviour of class with empty constructor

2008-01-25 Thread Bjoern Schliessmann
[EMAIL PROTECTED] wrote:
> print x.ends,y.ends,z.ends
> #
> Running the following code outputs:
 [(0, 2)] [(0, 2)] [(0, 2)]
> 
> Can anyone explain this?

Yes. You bound a single list to the name "ends" inside the class.
This name is shared by all instances.

If you want the instances to each have separate lists, delete
the "ends" definition from class declaration and insert "self.ends
= []" into __init__.

I also suggest you to have a look at the tutorial.

Regards,


Björn

-- 
BOFH excuse #49:

Bogon emissions

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


basic output question

2008-01-25 Thread John Deas
Hi, I am very new to Python (1 evening...)
I need to process a series of files (toto-1.txt toto-2.txt toto-3.txt
toto-4.txt), and as such I created a small program to go through the
files in a directory. I want to call the script with arguments, like

python script.py toto- 1 1 4

my script is as follow :

import sys
sys.argv
header= sys.argv[1]
start =eval(sys.argv[2])
step  =eval(sys.argv[3])
nbit  =eval(sys.argv[4])

for i in range(nbit):
filename=header+str(start+i*step)+'.txt'
f=open(filename,'r')
f.read()
f.close()

My problem is that f.read() outputs nothing, and should I print
filename, I can check that they are well formed, and the files sits in
the same directory as my script.

Anyone could help me on this ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Puzzled by behaviour of class with empty constructor

2008-01-25 Thread dbaston
Hello,

I have a class called 'Axis' that I use as a base class for several
types of axes that can be created by a grid generation program that I
have written: equally-spaced grids, logarithmic grids, etc.  In any
case, if I use this base class by itself, I see some puzzling
behaviour:
#
class Axis:
ends = []
N = None
def __init__(self):
pass

x = Axis()
y = Axis()
z = Axis()

x.ends.append((0,2))

print x.ends,y.ends,z.ends
#
Running the following code outputs:
>>> [(0, 2)] [(0, 2)] [(0, 2)]

Can anyone explain this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: find minimum associated values

2008-01-25 Thread Alan Isaac
Alan Isaac wrote:
 
> #sort by id and then value
> kv_sorted = sorted(kv, key=lambda x: (id(x[0]),x[1]))
> #groupby: first element in each group is object and its min value
> d =dict( g.next() for k,g in groupby( kv_sorted, key=lambda x: x[0] ) )
> 
> Yes, that appears to be fastest and is
> pretty easy to read.

On average.
For the specified problem.
;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: find minimum associated values

2008-01-25 Thread Alan Isaac
Paul Rubin wrote: 
> How about something like:
> 
>   kv_sorted = sorted(kv, key=lambda x: (id(x[0]), x[1]))


You mean like this?

#sort by id and then value
kv_sorted = sorted(kv, key=lambda x: (id(x[0]),x[1]))
#groupby: first element in each group is object and its min value
d =dict( g.next() for k,g in groupby( kv_sorted, key=lambda x: x[0] ) )

Yes, that appears to be fastest and is
pretty easy to read.

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


CFP: DATICS 2008 - Design, Analysis and Tools for Integrated Circuits and Systems

2008-01-25 Thread DATICS2008
Apologies for any multiple copies received. We would appreciate it if
you could distribute
the following call for papers to any relevant mailing lists you know
of.

 CALL FOR PAPERS
===
Special Session: Design, Analysis and Tools for Integrated Circuits
and Systems

DATICS 2008

July 22-24, 2008 (Crete Island, Greece)
http://digilander.libero.it/systemcfl/datics
===

Aims and Scope
--
The main target of the Special Session: DATICS 2008 of the WSEAS CSCC
multi-conference
(http://www.wseas.org/conferences/2008/greece/icc/) is to bring
together software/hardware
engineering researchers, computer scientists, practitioners and people
from industry to
exchange theories, ideas, techniques and experiences related to all
areas of design, analysis and
tools for integrated circuits (e.g. digital, analog and mixed-signal
circuits) and
systems (e.g. real-time, hybrid and embedded systems).
The special session also focuses on the field of formal methods and
low power design methodologies for integrated circuits.

Topics
--
Topics of interest include, but are not limited to, the following:
* digital, analog, mixed-signal designs and test
* RF design and test
* design-for-testability and built-in self test methodologies
* reconfigurable system design
* high-level synthesis
* EDA tools for design, testing and verification
* low power design methodologies
* network and system on-a-chip
* application-specific SoCs
* specification languages: SystemC, SystemVerilog and UML
* all areas of modelling, simulation and verification
* formal methods and formalisms (e.g. process algebras, petri-nets,
automaton theory and BDDs)
* real-time, hybrid and embedded systems
* software engineering (including real-time Java, real-time UML and
performance metrics)

Industrial Collaborators:
---
DATICS 2008 is partnered with:
* CEOL: Centre for Efficiency-Oriented Languages "Towards improved
software timing",
  University College Cork, Ireland ( http://www.ceol.ucc.ie)
* International Software and Productivity Engineering Institute, USA
(http://www.intspei.com )
* Intelligent Support Ltd., United Kingdom (http://www.isupport-
ltd.co.uk)
* Solari, Hong Kong ( http://www.solari-hk.com)
* Minteos, Italy (http://www.minteos.com)
* M.O.S.T., Italy (http://www.most.it)

Technical Program Committee:
--
* Prof. Vladimir Hahanov, Kharkov National University of Radio
Electronics, Ukraine
* Prof. Paolo Prinetto, Politecnico di Torino, Italy
* Prof. Alberto Macii, Politecnico di Torino, Italy
* Prof. Joongho Choi, University of Seoul, South Korea
* Prof. Wei Li, Fudan University, China
* Prof. Michel Schellekens, University College Cork, Ireland
* Prof. Franco Fummi, University of Verona, Italy
* Prof. Jun-Dong Cho, Sung Kyun Kwan University, South Korea
* Dr. Emanuel Popovici, University College Cork, Ireland
* Dr. Jong-Kug Seon, Telemetrics Lab., LG Industrial Systems Co. Ltd.,
South Korea
* Dr. Umberto Rossi, STMicroelectronics, Italy
* Dr. Graziano Pravadelli, University of Verona, Italy
* Dr. Vladimir Pavlov, International Software and Productivity
Engineering Institute, USA
* Dr. Jinfeng Huang, Philips & LiteOn Digital Solutions Netherlands,
Advanced Research Centre,
The Netherlands
* Dr. Thierry Vallee, Georgia Southern University, Statesboro,
Georgia, USA
* Dr. Menouer Boubekeur, University College Cork, Ireland
* Dr. Ana Sokolova, University of Salzburg, Austria
* Dr. Sergio Almerares, STMicroelectronics, Italy
* Ajay Patel (Director), Intelligent Support Ltd, United Kingdom
* Monica Donno (Director), Minteos, Italy
* Alessandro Carlo (Manager), Research and Development Centre of FIAT,
Italy
* Yui Fai Lam (Manager), Microsystems Packaging Institute, Hong Kong
University of
   Science and Technology, Hong Kong

Important Dates
---
March 31, 2008: Deadline for submission of completed papers
May 1, 2008: Notification of acceptance/rejection to authors

Please visit our web-site for further information on the hosting
conference of DATICS,
submission guidelines, proceedings and publications and international
technical reviewers.

Best regards,

General Chair of DATICS: Dr. K.L. Man (University College Cork,
Ireland)
and
Organising Committee Chair: Miss Maria O'Keeffe (University College
Cork, Ireland)



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


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread Hexamorph
Lorenzo E. Danielsson wrote:
> [EMAIL PROTECTED] wrote:

>> I think I was not specific/clear enough in my first posting. I know
>> the curses library ( http://pyncurses.sourceforge.net ). It AFIK
>> provides TUI (short for: Text User Interface or Textual User
>> Interface). My needs are GUI, I mean "a nice VGA pictures" on the VGA
>> LCD 10" display.
>>
>> Petr
> 
> What you need then is something like SVGAlib (http;//svgalib.org). Only 
> really old people like myself know that it exists. I've never heard of 
> any Python bindings for it, but that might be where you come in. I 
> haven't looked at SVGAlib for years, and I'm not sure about the state of 
> the video drivers.

I don't think that there's a Python binding for it. Svgalib never 
has gained enough popularity for anybody to write such bindings.
However, as long as the video card supports VGA or VESA it should work.

Another possibility might be using Xvesa (KDrive) which is a really 
tiny self-containing X server for VGA/SVGA/FBdev. With this you can 
atleast use simple GUI toolkits like Athena or TK or even use Xlib 
directly (if you don't fear that adventure)

See:
http://www.xfree86.org/current/Xvesa.1.html
http://www.pps.jussieu.fr/~jch/software/kdrive.html


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


Re: Module/package hierarchy and its separation from file structure

2008-01-25 Thread Gabriel Genellina
En Thu, 24 Jan 2008 11:57:49 -0200, Peter Schuller  
<[EMAIL PROTECTED]> escribió:

> In this case my
> problem is more related to the "file == module" and "directory ==
> module" semantics, since I want to break contents in a single module
> out into several files.

You already can do that, just import the public interfase of those several  
files onto the desired container module. See below for an example.

>> Isn't org.lib.animal a package, reflected as a directory on disk? That's
>> the same both for Java and Python. Monkey.py and Tiger.py would be  
>> modules
>> inside that directory, just like Monkey.java and Tiger.java. Aren't the
>> same thing?
>
> No, because in Java Monkey.java is a class. So we have class Monkey in
> package org.lib.animal. In Python we would have class Monkey in module
> org.lib.animal.monkey, which is redundant and does not reflect the
> intended hierarchy. I have to either live with this, or put Monkey in
> .../animal/__init__.py. Neither option is what I would want, ideally.

You can also put, in animal/__init__.py:
 from monkey import Monkey
and now you can refer to it as org.lib.animal.Monkey, but keep the  
implementation of Monkey class and all related stuff into  
.../animal/monkey.py

-- 
Gabriel Genellina

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


Re: Index of maximum element in list

2008-01-25 Thread Neal Becker
Henry Baxter wrote:

> Oops, gmail has keyboard shortcuts apparently, to continue:
> 
> def maxi(l):
> m = max(l)
> for i, v in enumerate(l):
> if m == v:
> return i
> 
> But it seems like something that should be built in - or at least I should
> be able to write a lambda function for it, but I'm not sure how to do that
> either...Suggestions are very much welcome!
> 

I really think this is a good candidate for a builtin.  I suggest:

max2 (x):
  """ return (minvalue,minindex)"""

This allows efficient usage in all cases, including iterators (not just
sequences).



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


Re: Index of maximum element in list

2008-01-25 Thread Hexamorph
Henry Baxter wrote:
> Oops, gmail has keyboard shortcuts apparently, to continue:
> 
> def maxi(l):
> m = max(l)
> for i, v in enumerate(l):
> if m == v:
> return i
> 

What's about l.index(max(l)) ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: find minimum associated values

2008-01-25 Thread John Machin
On Jan 26, 7:58 am, [EMAIL PROTECTED] wrote:
> I find the first and third solutions simpler to read, and the first
> solution requires less memory, it probably works quite well with
> Psyco, and it's easy to translate to other languages (that is
> important for programs you want to use for a lot of time or in
> different situations), so I'd use the first solution.
>

The first solution, once one changes "d = dict()" to "d = {}", is
quite free of any impediments to ease of reading, uses the minimum
necessary memory to build the required dict [and it's quite obvious by
inspection that this is so], and is the easiest to "translate" to
earlier versions of Python.

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


Re: Index of maximum element in list

2008-01-25 Thread Henry Baxter
Oops, gmail has keyboard shortcuts apparently, to continue:

def maxi(l):
m = max(l)
for i, v in enumerate(l):
if m == v:
return i

But it seems like something that should be built in - or at least I should
be able to write a lambda function for it, but I'm not sure how to do that
either...Suggestions are very much welcome!

On Jan 25, 2008 1:37 PM, Henry Baxter <[EMAIL PROTECTED]> wrote:

> I apologize if this has already been discussed - funnily enough my
> googling did bring up a previous thread about it on this mailing list, but
> despite the promising subject line, seemed to mainly be concerned with
> whether python-list should its own FAQ...so I assume this has been asked
> many times before, but my apologies I cannot find the answer. Here is what I
> have:
>
> def maxi(l):
>
> it
> --
> Henry




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

Index of maximum element in list

2008-01-25 Thread Henry Baxter
I apologize if this has already been discussed - funnily enough my googling
did bring up a previous thread about it on this mailing list, but despite
the promising subject line, seemed to mainly be concerned with whether
python-list should its own FAQ...so I assume this has been asked many times
before, but my apologies I cannot find the answer. Here is what I have:

def maxi(l):

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

Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread Lorenzo E. Danielsson
[EMAIL PROTECTED] wrote:
>>> is already solved).
>> what you are looking for is curse :)
>> http://docs.python.org/lib/module-curses.html
>> http://www.ibm.com/developerworks/linux/library/l-python6.html
>>
>> renaud
> 
> Renaud, thanks for your reply.
> 
> I think I was not specific/clear enough in my first posting. I know
> the curses library ( http://pyncurses.sourceforge.net ). It AFIK
> provides TUI (short for: Text User Interface or Textual User
> Interface). My needs are GUI, I mean "a nice VGA pictures" on the VGA
> LCD 10" display.
> 
> Petr

What you need then is something like SVGAlib (http;//svgalib.org). Only 
really old people like myself know that it exists. I've never heard of 
any Python bindings for it, but that might be where you come in. I 
haven't looked at SVGAlib for years, and I'm not sure about the state of 
the video drivers. I suggest you look at that first.

You could also look at GGI (http://ggi-project.org). GGI has different 
output targets. IIRC, one of them is directfb. To tell you the truth 
I've never really used GGI. There seems to be a python wrapper for GGI, 
although it is fairly old. Maybe you could look at the code for some ideas.

You should also be able to compile SDL to be able to use directfb as a 
target. If your libSDL handles it, then that should apply to wrapper 
libraries as well, including pygame. I've never tried running SDL apps 
this way, but if it works well, that would probably be your 'best' option.

Lorenzo

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


Re: Python ADO Date Time database fields

2008-01-25 Thread John Machin
On Jan 26, 12:48 am, goldtech <[EMAIL PROTECTED]> wrote:
> snip
>
>
>
> > try this:
>
> > val = oRS.Fields(dt).Value
> > print type(val)
>
> this gives:  
>
> > print float(val)
>
> yes, it gives 0.0
>
> But there should be a way to print what is *actually in the field*.

What is "actually in the field" is a bunch of bits -- in this case all
zero. What you *see* is quite another matter.

> When I open the DB table in Access I see: 12:00:00 AM.

And if you were to close Access, go Start / Control Panel / Regional
and Language settings, change the Time display format to HH:mm:ss, and
go back to look at your database, you'd see 00:00:00 ... send a copy
of your database to someone in another country and they'd likely see
something else again.

>
> That's what I want - the value, and the form of the value, exactly as
> seen in the field...

>
> As an aside, the roughly eqivalent code in Perl will print the
> "12:00:00 AM" - (the trick for the date types in Perl is to add: "use
> Win32::OLE::Variant;"
>
> There has to be a way:^)

C:\junk>type goldtech.py
def time_format_12(day_fraction):
assert 0.0 <= day_fraction < 1.0
seconds = int(day_fraction * 60 * 60 * 24)
minutes, second = divmod(seconds, 60)
hour, minute = divmod(minutes, 60)
if hour >= 12:
tag = 'PM'
else:
tag = 'AM'
hour12 = (hour - 1) % 12 + 1
return '%02d:%02d:%02d %s' % (hour12, minute, second, tag)

if __name__ == "__main__":
import sys
args = sys.argv[1:]
if args:
tests = map(float, args)
else:
tests = (
[0.0, 0.5, 0.999]
+ [(h + 0.99) / 24.0 for h in (0, 1, 11, 12, 13, 23)]
)
for test in tests:
print "%8.6f %s" % (test, time_format_12(test))

C:\junk>goldtech.py
0.00 12:00:00 AM
0.50 12:00:00 PM
1.00 11:59:59 PM
0.041250 12:59:24 AM
0.082917 01:59:24 AM
0.499583 11:59:23 AM
0.541250 12:59:24 PM
0.582917 01:59:24 PM
0.999583 11:59:23 PM

C:\junk>goldtech.py 0.1 0.01 0.001
0.10 02:24:00 AM
0.01 12:14:24 AM
0.001000 12:01:26 AM

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


Re: find minimum associated values

2008-01-25 Thread bearophileHUGS
I find the first and third solutions simpler to read, and the first
solution requires less memory, it probably works quite well with
Psyco, and it's easy to translate to other languages (that is
important for programs you want to use for a lot of time or in
different situations), so I'd use the first solution.

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


Re: Operator overloading

2008-01-25 Thread Hexamorph
[EMAIL PROTECTED] wrote:
> 
> Hexamorph wrote:
>> You mean you want the ability to change for example the + operator
>> for ints to something like calculating the cosine instead of doing
>> addition?
> 
> Sure. Cosines are a monadic operation and the monadic '+' is a NOP, so
> why shouldn't I define +45 to return cosine of 45, (presuming I needed
> lots of cosines). I'd even let you define your own operators. Lots of
> programmers really liked '++' and '--', for examples.

Well, OK, the cosine example was badly chosen (it would still be 
very wired in terms of common syntax and semantics), but I think you 
got my point. Changing internal behaviour mostly causes more trouble 
as it's worth.

In the end, you probably can access the parser to do this.

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


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread petr . jakes . tpc
> > is already solved).
>
> what you are looking for is curse :)
> http://docs.python.org/lib/module-curses.html
> http://www.ibm.com/developerworks/linux/library/l-python6.html
>
> renaud

Renaud, thanks for your reply.

I think I was not specific/clear enough in my first posting. I know
the curses library ( http://pyncurses.sourceforge.net ). It AFIK
provides TUI (short for: Text User Interface or Textual User
Interface). My needs are GUI, I mean "a nice VGA pictures" on the VGA
LCD 10" display.

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


Re: read and readline hanging

2008-01-25 Thread Marc 'BlackJack' Rintsch
On Fri, 25 Jan 2008 17:31:16 +0100, Olivier Lefevre wrote:

> Thanks for the answer. Yes this is tricky. I have done it in Java
> before, where you can, e.g., set up a thread to pump stuff out of
> both stderr and stdout continuously but my python is too rudimentary
> for that.

The `trheading` module is modeled after Java's threading API.

> There is a key difference anyway: in Java you can write
> 
>  while (br.readLine() != null) {  }
> 
> where br is the buffered reader in which you've wrapped the stdout
> of the child process and it will not hang. But in python eventually
> stdout.readline() hangs. This is a real nuisance: why can't it just
> return None?

Because that would be quite annoying because most of the time people want
blocking behavior.

>> 1. The subprocess has stopped producing output.
> 
> Indeed, if I do this interactively, I can tell after 3 lines that I've
> gotten all there is to get right now and the fourth readline() call
> hangs. But how can I find out *programmatically* that there is no more
> input?

You can't.

>> If you are only reading its standard output, are you sure that the 
>  > subprocess is flushing its buffers so you can recognize it's time to
>  > provide more input?
> 
> The subprocess in a purely passive position: it is an interpreter: I
> send it commands and I read the answers. The python side is in charge.

This doesn't answer if the interpreter doesn't flush its output buffer
after every line.

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


Re: Operator overloading

2008-01-25 Thread MartinRinehart


Hexamorph wrote:
> You mean you want the ability to change for example the + operator
> for ints to something like calculating the cosine instead of doing
> addition?

Sure. Cosines are a monadic operation and the monadic '+' is a NOP, so
why shouldn't I define +45 to return cosine of 45, (presuming I needed
lots of cosines). I'd even let you define your own operators. Lots of
programmers really liked '++' and '--', for examples.

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


Re: is possible to get order of keyword parameters ?

2008-01-25 Thread rndblnch
On Jan 25, 9:01 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> rndblnch <[EMAIL PROTECTED]> wrote:
> > the following example should also
> > work:
> > size = Point(width=23, height=45)
> > w, h = size
>
> So you want the unpacking to depend on how the Point was initialised!
> Aaargh!

why not?
in

def f(*args):
return iter(args)

the order of the parameters do have a semantic,
i can predict the behaviour of:

x, y = f(1, 2)

to bad it's not possible with:

def g(**kwargs):
return kwargs.itervalues()

x, y = g(x=1, y=2)

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


Re: is possible to get order of keyword parameters ?

2008-01-25 Thread Steven Bethard
Steven Bethard wrote:
> rndblnch wrote:
>> my goal is to implement a kind of named tuple.
>> idealy, it should behave like this:
>> p = Point(x=12, y=13)
>> print p.x, p.y
>> but what requires to keep track of the order is the unpacking:
>> x, y = p
>> i can't figure out how to produce an iterable that returns the values
>> in the right order.
>> relying on a "natural" order of the key names is not possible: x, and
>> y are alphabetically sorted but the following example should also
>> work:
>> size = Point(width=23, height=45)
>> w, h = size
> 
> There are a couple of recipes for named tuples:
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500261
> 
> The latter of these will be in Python 2.6.  Using that recipe, and your 
> example, you would write::
> 
> Point = namedtuple('Point', 'x y')
> p = Point(x=12, y=13)
> x, y = p
> 
> Point = namedtuple('Point', 'width', 'height')

Sorry, typo here.  This should have read

   Point = namedtuple('Point', 'width height')

> size = Point(width=23, height=45)
> w, h = size

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


Re: is possible to get order of keyword parameters ?

2008-01-25 Thread Steven Bethard
rndblnch wrote:
> my goal is to implement a kind of named tuple.
> idealy, it should behave like this:
> p = Point(x=12, y=13)
> print p.x, p.y
> but what requires to keep track of the order is the unpacking:
> x, y = p
> i can't figure out how to produce an iterable that returns the values
> in the right order.
> relying on a "natural" order of the key names is not possible: x, and
> y are alphabetically sorted but the following example should also
> work:
> size = Point(width=23, height=45)
> w, h = size

There are a couple of recipes for named tuples:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500261

The latter of these will be in Python 2.6.  Using that recipe, and your 
example, you would write::

 Point = namedtuple('Point', 'x y')
 p = Point(x=12, y=13)
 x, y = p

 Point = namedtuple('Point', 'width', 'height')
 size = Point(width=23, height=45)
 w, h = size

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


Re: is possible to get order of keyword parameters ?

2008-01-25 Thread Duncan Booth
rndblnch <[EMAIL PROTECTED]> wrote:

> the following example should also
> work:
> size = Point(width=23, height=45)
> w, h = size
> 

So you want the unpacking to depend on how the Point was initialised! 
Aaargh!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Increment Variable Name

2008-01-25 Thread Gabriel Genellina
En Wed, 23 Jan 2008 23:09:36 -0200, David Brochu <[EMAIL PROTECTED]>  
escribió:

> Basically what I am trying to do is pass each value from a list to
> the following line of code (where XXX is where I need to pass each
> value of the list
>
> tests = easygui.multchoicebox(message="Pick the test(s) you would
> like to run from the list below."
>   , title="Validation Tests"
>   ,choices=[XXX])
>
> If i were to manually pass values to this line it would appear like :
> tests = easygui.multchoicebox(message="Pick the test(s) you would
> like to run from the list below."
>   , title="Validation Tests"
>   ,choices=["Test 1","Test 2", "Test 3"])
>
> When I actually pass the list to the line of code, it works, however
> it doesn't really split the list by element. The desired output of
> this line of code would be a GUi that included a list consisting of
> each element from the passed list. Right now I can only get it to
> consist of a single element that contains every part of the list.

You should have posted this in the first place! No answer to your previous  
specific question would have helped you in this case.
See http://catb.org/~esr/faqs/smart-questions.html#goal

Ok, you have a list containing all the possible choices. It doesn't matter  
how did you build that list. Then, just pass *that* *list* as the choices  
parameter to the function. By example:

all_tests = ["Test 1","Test 2", "Test 3"]
tests = easygui.multchoicebox(message="Pick the test(s) you would
like to run from the list below.", title="Validation Tests",  
choices=all_tests)

(If you use [items] you are building a new list with a single element  
which itself is the list of choices, and that's not what multchoicebox  
expects).

-- 
Gabriel Genellina

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


Re: find minimum associated values

2008-01-25 Thread Paul Rubin
Alan Isaac <[EMAIL PROTECTED]> writes:
> print "method 2: groupby"
> t=time.clock()
> d = dict()
> kv_sorted = sorted(kv, key=lambda x: id(x[0]))

How about something like:

  kv_sorted = sorted(kv, key=lambda x: (id(x[0]), x[1]))

Now do your groupby and the first element of each group is the minimum
for that group.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and binary compatibility

2008-01-25 Thread Joshua Kugler
Christian Heimes wrote:
> You can use MinGW32 to compile the extension, too. Or use the free
> toolchain as described at
> http://wiki.python.org/moin/Building_Python_with_the_free_MS_C_Toolkit

That page has a link to the Microsoft Visual C++ Toolkit 2003 page, which
then says it's been discontinued and to use Visual C++ 2005 Express
Edition. Sigh...

j

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


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread rndblnch
On Jan 25, 8:43 pm, [EMAIL PROTECTED] wrote:
> This means NO X-windows, NO GTK/Gnome, NO
> computer mouse, on my machine (AMD Geode 500MHz CPU, VGA output).
>
> I would like to write some really light weighted GU interface. My
> concept is to have just few user screens (about 10) controlled via 4
> or 5 HW buttons connected to the GPIO pins they are available on the
> motherboard (the HW design and the SW concept of reading this buttons
> is already solved).

what you are looking for is curse :)
http://docs.python.org/lib/module-curses.html
http://www.ibm.com/developerworks/linux/library/l-python6.html

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


Re: Sorting Large File (Code/Performance)

2008-01-25 Thread Paul Rubin
Nicko <[EMAIL PROTECTED]> writes:
> # The next line is order O(n) in the number of chunks
> (line, fileindex) = min(mergechunks)

You should use the heapq module to make this operation O(log n) instead.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is possible to get order of keyword parameters ?

2008-01-25 Thread rndblnch

On Jan 25, 5:27 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
> Keyword arguments are normally treaded as "order independent".
> Why do you think you need to find the order?  What problem do
> you wish to solve?
>
> -Larry

On Jan 25, 7:39 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> The question remains, what use is there for this?

my goal is to implement a kind of named tuple.
idealy, it should behave like this:
p = Point(x=12, y=13)
print p.x, p.y
but what requires to keep track of the order is the unpacking:
x, y = p
i can't figure out how to produce an iterable that returns the values
in the right order.
relying on a "natural" order of the key names is not possible: x, and
y are alphabetically sorted but the following example should also
work:
size = Point(width=23, height=45)
w, h = size

if you have any suggestion to implement such a thing...
thank you

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


looking for a light weighted library/tool to write simple GUI above the text based application

2008-01-25 Thread petr . jakes . tpc
Hi,
I am working with the Python 2.5 running on the command line version
of Linux Ubuntu 7.04. This means NO X-windows, NO GTK/Gnome, NO
computer mouse, on my machine (AMD Geode 500MHz CPU, VGA output).

I would like to write some really light weighted GU interface. My
concept is to have just few user screens (about 10) controlled via 4
or 5 HW buttons connected to the GPIO pins they are available on the
motherboard (the HW design and the SW concept of reading this buttons
is already solved).

After some googling, I have found below mentioned can be usable, but
first, I would like to ask here for your opinions/experiences/advices.

Best regards

Petr Jakes

http://www.libsdl.org/
http://pyfltk.sourceforge.net/
http://www.pygame.org/news.html
http://pyui.sourceforge.net/
http://pyglet.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Operator overloading

2008-01-25 Thread Hexamorph
[EMAIL PROTECTED] wrote:
> 
> Diez B. Roggisch wrote:
>> No, there is no way. You would change general interpreter behavior if
>> you could set arbitrary operators for predefined types.
>>
>> Start grumping...
> 
> Thank you, Diez.
> 
> If I ever design a language, please remind me that complete, easy,
> well-documented access to the working of the internals (and the
> ability to change same) would be very, uh, what's the right word?
> Pythonic?


You mean you want the ability to change for example the + operator 
for ints to something like calculating the cosine instead of doing 
addition?

That will break the whole system in general as other parts of the 
language (or modules, libraries and programs) rely on a certain 
inner behaviour.

There are some languages in which you can do this (Lisp/Scheme for 
example) but messing with the internals is almost never done for 
good reasons.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Operator overloading

2008-01-25 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> 
> Diez B. Roggisch wrote:
>> No, there is no way. You would change general interpreter behavior if
>> you could set arbitrary operators for predefined types.
>>
>> Start grumping...
> 
> Thank you, Diez.
> 
> If I ever design a language, please remind me that complete, easy,
> well-documented access to the working of the internals (and the
> ability to change same) would be very, uh, what's the right word?
> Pythonic?

As you say - it's a question of design & thus taste. Python has chosen 
to _not_ allow to change (all) inner workings of itself in favor of not 
introducing subtle bugs that arise from somebody (accidentially or not) 
altering behavior of builtins that might effect code he'd never intended 
to touch.

But you _can_ create subclasses of these builtins and adapt their 
behavior. I for once like it that way. If you don't - to bad for you. It 
won't change, so either you live with it, or start working on your 
lex/yacc skillz and create your own language. Or switch to Ruby, which 
allow for what you desire (AFAIK, not entirely sure though)

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


Re: Operator overloading

2008-01-25 Thread MartinRinehart


Diez B. Roggisch wrote:
> No, there is no way. You would change general interpreter behavior if
> you could set arbitrary operators for predefined types.
>
> Start grumping...

Thank you, Diez.

If I ever design a language, please remind me that complete, easy,
well-documented access to the working of the internals (and the
ability to change same) would be very, uh, what's the right word?
Pythonic?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When is min(a, b) != min(b, a)?

2008-01-25 Thread Robert Kern
Marc 'BlackJack' Rintsch wrote:
> On Fri, 25 Jan 2008 07:57:38 +, Pete Forman wrote:
> 
>> Mark Dickinson <[EMAIL PROTECTED]> writes:
>>
>>  > Any change to Python that made == and != checks involving NaNs raise
>>  > an exception would have to consider the consequences for set, dict,
>>  > list membership testing.
>>  > […]
>>  > and if Python had separate operators for these two purposes it
>>  > wouldn't be Python any more.
>>
>> There are separate Python operators, "==" and "is".
> 
> So what?  ``==`` is used for both ``==`` and set/dict/list membership
> testing and "nested comparison" of those structures.  There is no ``is``
> involved.

Sure, there is. ``is`` is checked before ``==``. But that's just an 
optimization 
for the usual case where "x is x" implies "x == x", to bring this full circle, 
something that is not true for NaNs.


In [48]: class A(object):
 def __init__(self, x):
 self.x = x
 def __eq__(self, other):
 print '%r.__eq__(%r)' % (self, other)
 return self.x == other.x
 def __ne__(self, other):
 return not (self == other)
 def __hash__(self):
 print '%r.__hash__()' % (self,)
 return hash(self.x)
 def __repr__(self):
 return 'A(%r)' % (self.x,)
:
:

In [61]: a = A(1)

In [62]: b = A(2)

In [63]: c = A(1)

In [64]: a is c
Out[64]: False

In [65]: a == c
A(1).__eq__(A(1))
Out[65]: True

In [66]: a == b
A(1).__eq__(A(2))
Out[66]: False

In [67]: L = [a, b, c]

In [68]: a in L
Out[68]: True

In [69]: b in L
A(2).__eq__(A(1))
Out[69]: True

In [70]: c in L
A(1).__eq__(A(1))
Out[70]: True

In [71]: S = set([a, b, c])
A(1).__hash__()
A(2).__hash__()
A(1).__hash__()
A(1).__eq__(A(1))

In [72]: a in S
A(1).__hash__()
Out[72]: True

In [73]: b in S
A(2).__hash__()
Out[73]: True

In [74]: c in S
A(1).__hash__()
A(1).__eq__(A(1))
Out[74]: True

In [75]: D = {a: 1, b: 2, c: 1}
A(1).__hash__()
A(2).__hash__()
A(1).__hash__()
A(1).__eq__(A(1))

In [76]: D
Out[76]: A(2).__eq__(A(1))
{A(1): 1, A(2): 2}

In [77]: a in D
A(1).__hash__()
Out[77]: True

In [78]: b in D
A(2).__hash__()
Out[78]: True

In [79]: c in D
A(1).__hash__()
A(1).__eq__(A(1))
Out[79]: True


-- 
Robert Kern

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

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

Re: find minimum associated values

2008-01-25 Thread Alan Isaac
Steven Bethard wrote:
> [3rd approach] Seems "pretty" enough to me. ;-)

I find it most attractive of the lot.
But its costs would rise if the number
of values per object were large.

Anyway, I basically agree.

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


Re: Sorting Large File (Code/Performance)

2008-01-25 Thread Nicko
On Jan 24, 9:26 pm, [EMAIL PROTECTED] wrote:
> > If you really have a 2GB file and only 2GB of RAM, I suggest that you don't 
> > hold your breath.
>
> I am limited with resources. Unfortunately.

As long as you have at least as much disc space spare as you need to
hold a copy of the file then this is not too hard.  Split the file
into chunks that are small enough to fit in memory, sort each chunk
and write it to a file and then interleave the chunks.  Below is a
cheap and cheesy outline of code to do this, from which you can start.

For files which are hugely larger than your available memory you can
do this recursively but for files which are 10 to 100 times too big
the single-pass code below will probably work just fine.  The
complexity is technically O(n.(log(c)+(n/c))) where n is the size of
input and c is the chunk size; once n/c (the number of chunks) exceeds
log(c) the cost of merging the chunks will start to dominate, though a
recursive version would be slowed by needing a lot more disc access.

#!/usr/bin/env python
from itertools import islice
from tempfile import TemporaryFile
import sys

# Tweak this number to fill your memory
lines_per_chunk = 10

chunkfiles = []
mergechunks = []

while True:
chunk = list(islice(sys.stdin, lines_per_chunk))
if not chunk:
   break
chunk.sort()
f = TemporaryFile()
f.writelines(chunk)
f.seek(0)
mergechunks.append((chunk[0], len(chunkfiles)))
chunkfiles.append(f)

while mergechunks:
# The next line is order O(n) in the number of chunks
(line, fileindex) = min(mergechunks)
mergechunks.remove((line, fileindex))
sys.stdout.write(line)
nextline = chunkfiles[fileindex].readline()
if nextline == "":
chunkfiles[fileindex].close()
else:
mergechunks.append((nextline, fileindex))

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


  1   2   >