Re: Generational Interfaces

2008-01-26 Thread Carl Banks
On Jan 26, 3:04 am, Paddy <[EMAIL PROTECTED]> wrote:
> I thought a major use of an interface is to allow separate development
> that comes together at the interface. If so then such fluid interface
> changing would scupper separate development.


Yes, this wouldn't be appropriate for that particular use.


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


Re: Testing whether something is of type Exception

2008-01-26 Thread Paddy
On Jan 24, 11:14 pm, John Nagle <[EMAIL PROTECTED]> wrote:
> How can I tell whether an object is of type Exception?

Use it as if it is one and catch any exceptions :-)

- Paddy. (Grabs coat, heads for the exit)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding child cpu usage of a running child

2008-01-26 Thread Paddy
On Jan 26, 5:43 am, Karthik Gurusamy <[EMAIL PROTECTED]> wrote:
> 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

I had a similar requirement in December and found:
  http://lilypond.org/~janneke/software/

proc-time.c and proc-time.py poll /proc/ files whilst command
is running to get stats.

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


Re: finding child cpu usage of a running child

2008-01-26 Thread Karthik Gurusamy
On Jan 25, 11:59 pm, Paddy <[EMAIL PROTECTED]> wrote:
> On Jan 26, 5:43 am, Karthik Gurusamy <[EMAIL PROTECTED]> wrote:
>
>
>
> > 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
>
> I had a similar requirement in December and found:
>  http://lilypond.org/~janneke/software/
>
> proc-time.c and proc-time.py poll /proc/ files whilst command
> is running to get stats.

Great, thanks. From proc-time.py looks like all I want are the fields
13 to 16 of /proc//stat. And I see them updated in real
time (probably the kernel does it on a periodic interrupt).

Thanks,
Karthik

>
> Enjoy,  - Paddy.

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


Re: Generational Interfaces

2008-01-26 Thread Paddy
On Jan 26, 5:03 am, Carl Banks <[EMAIL PROTECTED]> wrote:
> 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

I thought a major use of an interface is to allow separate development
that comes together at the interface. If so then such fluid interface
changing would scupper separate development.

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


urllib + Microsoft VBScript

2008-01-26 Thread mag_dex
Hi,
I have a problem, I wanna write script to get result from web tools
http://202.120.37.186/bioinf/Gpos/index.htm
I created script like this:
#!/usr/bin/python

import urllib

def do_GposLoc(job_id,v=1):
seqOfProtein = """>P46748""".strip() + '\r\n'
seqOfProtein +=
"""MKTLSILDTIIKIPEKIEIHPTTTEYIYTITGPLGSSSINLKKLDKNGIACINFDIQNKQ
VLIRSLYPKYNGLYKKLIENKFLGVSRGFCVYLEIVGVGYRAALLSSSLQNSTKDTNDTI
VLKLGHSHDIHYKVPNGVRVFLQSPSEICIFGVDLNQVTQVAHSIRNTRPPSVYKGKGIR
YTNEKIVTKTGKRK
"""
#
print seqOfProtein
address= "http://202.120.37.186/bioinf/Gpos/Gpos-PSLPred-
upload.asp?act=upload"
params = urllib.urlencode(
  {'mode': 'string',
 'S1':seqOfProtein,
 'B1': 'Submit'})
#
f = urllib.urlopen(address, params)

content = f.read()
if v:print content
return 0

if '__main__'==__name__:
job_id='f'
do_GposLoc(job_id)



and I got result like this:
 
Microsoft VBScript �� 
 '800a03f6'

ȱ�� 'End'

/iisHelp/common/500-100.asp242  
Microsoft VBScript ʱ  
'800a0005'

��Ч�Ĺ��̵��û�: 'right'

/bioinf/Gpos/Gpos-PSLPred-upload.asp21

Yeah, I know these strange chars it's from wrong codding.
But I can't get the same result as I would post it 'by hand' opening
http://202.120.37.186/bioinf/Gpos/index.htm
i submit the sequence:
>P46748
MKTLSILDTIIKIPEKIEIHPTTTEYIYTITGPLGSSSINLKKLDKNGIACINFDIQNKQ
VLIRSLYPKYNGLYKKLIENKFLGVSRGFCVYLEIVGVGYRAALLSSSLQNSTKDTNDTI
VLKLGHSHDIHYKVPNGVRVFLQSPSEICIFGVDLNQVTQVAHSIRNTRPPSVYKGKGIR
YTNEKIVTKTGKRK

Maybe sb has idea how to solve this problem.
Regards
Marcin
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: paging in python shell

2008-01-26 Thread Alex K
That seems interesting but it's not quite what I want to do. To take
an example I would like to be able to do something similar to the
mysql shell when its pager is set to less. Displayhook is called
whenever an expression is being evaluated. I'd like to call 'less' on
the ouput of a statement.

Alex

On 26/01/2008, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> --- 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
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Index of maximum element in list

2008-01-26 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> def posmax(seq, key=None):
> """Return the position of the first maximum item of a sequence.
> It accepts the usual key parameter too."""
> if key:
> return max(enumerate(seq), key=lambda k: key(k[1]))[0]
> else:
> return max(enumerate(seq), key=itemgetter(1))[0]

def posmax(seq, key=lambda x:x):
   return max(enumerate(seq), key=lambda k: key(k[1]))[0]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Index of maximum element in list

2008-01-26 Thread bearophileHUGS
> Henry Baxter wrote:
> > def maxi(l):
> > m = max(l)
> > for i, v in enumerate(l):
> > if m == v:
> > return i
>
> What's about l.index(max(l)) ?

The version I use:

def posmax(seq, key=None):
"""Return the position of the first maximum item of a sequence.
It accepts the usual key parameter too."""
if key:
return max(enumerate(seq), key=lambda k: key(k[1]))[0]
else:
return max(enumerate(seq), key=itemgetter(1))[0]

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


Re: Generational Interfaces

2008-01-26 Thread bearophileHUGS
I think they can be called "soft interfaces" or "heuristic
interfaces", it's an example of machine learning. I think it's not
easy to apply such idea to a statically typed language, but probably
it can be done on Java. I presume in the future GUI will learn more
about the usage patterns of their users, data structures of long-
running programs will adapt to their average usage in each specific
point of the program, and maybe class interfaces too will become
smarter, as you say :-)
I think your idea can be implemented in Python too, so you just have
to try to use it in some project of yours developed with some Agile
programming style, so you can tell us if it's nice to use :-)

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


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

2008-01-26 Thread Karlheinz Klingbeil
Am 26.01.2008, 01:46 Uhr, schrieb David Erickson <[EMAIL PROTECTED]>:

>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
You're right on that point, though it says clearly "It is important to
note that the header fields are not guaranteed to be in a particular  
order."

So it's in my opinion a good idea not to expect headers to be ordered and
add headers in a way which doesn't conflict with a *possible* reordering.


-- 
Greetz, lunqual  - http://www.lunqual.de
http://www.42pixels.de - Bilder
http://www.rezeptbuch-pro.de - Software für den Destillateur
-- 
http://mail.python.org/mailman/listinfo/python-list

Hashable

2008-01-26 Thread Simon Pickles
Hi,

The term 'hashable'.

Am I right in thinking it means it can be indexed? like a string or a dict?

Thanks

Si

-- 
Linux user #458601 - http://counter.li.org.



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


Custom class to a dictionary?

2008-01-26 Thread Oliver Beattie
Just wondering if it is possible to pass a custom class instance
instance to dict() by way of using methods like you can for iterators
(__iter__, __getitem__ etc.) I see there is no __dict__ -- is there
anything else I can use to achieve this?

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


Re: Hashable

2008-01-26 Thread Steven D'Aprano
On Sat, 26 Jan 2008 11:10:03 +, Simon Pickles wrote:

> Hi,
> 
> The term 'hashable'.
> 
> Am I right in thinking it means it can be indexed? like a string or a
> dict?


No.


A hash function is a function which takes an arbitrary object and 
generates an integer from it.

Python has a built-in hash function hash(). It says:

help(hash):

hash(...)
hash(object) -> integer

Return a hash value for the object.  Two objects with the same 
value have the same hash value.  The reverse is not necessarily 
true, but likely.


Examples:

>>> hash(5.5)
1476493312
>>> hash('five')
202874452
>>> hash('fivf')
202874455
>>> hash(None)
54045056


Not all objects are hashable:

>>> hash([])
Traceback (most recent call last):
  File "", line 1, in 
TypeError: list objects are unhashable


Python dictionaries are "hash tables". A hash table is a data structure 
that let's you look up a key in (virtually) a constant amount of time no 
matter how many items there are in the table. It does this by calculating 
the hash of the key, then using that hash to calculate the index in the 
table where it expects to find the key's data. A good hash table (like 
Python dicts) is *very* fast.

But notice that the object which _uses_ the hash (the dict) is not 
hashable itself; and that the objects which are hashable (strings, ints, 
floats, etc.) don't necessarily have an index. Strings do, tuples do, but 
ints and floats and other objects don't.



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


Re: Custom class to a dictionary?

2008-01-26 Thread Steven D'Aprano
On Sat, 26 Jan 2008 03:35:18 -0800, Oliver Beattie wrote:

> Just wondering if it is possible to pass a custom class instance
> instance to dict() by way of using methods like you can for iterators
> (__iter__, __getitem__ etc.) I see there is no __dict__ -- is there
> anything else I can use to achieve this?


Just write a method to return (key, value) pairs, and call that:

>>> class Parrot(object):
... def __init__(self):
... self.keys = [1, 2, 3, 4]
... self.values = ["one", "two", "three", "four"]
... def generate_tuples(self):
... for k,v in zip(self.keys, self.values):
... yield (k,v)
...
>>> p = Parrot()
>>> p.generate_tuples()

>>> dict(p.generate_tuples())
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}



Here's another way:

>>> class Foo(object):
... def __getitem__(self, i):
... if i > 4:
... raise IndexError
... return (i, 'foo %d' % i)
...
>>> dict(Foo())
{0: 'foo 0', 1: 'foo 1', 2: 'foo 2', 3: 'foo 3', 4: 'foo 4'}



Bonus marks if you can explain why they both work :)

(Hint: consider the "sequence protocol" and the "iterator protocol".)



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


raw_input(), STRANGE behaviour

2008-01-26 Thread Dox33
I ran into a very strange behaviour of raw_input().
I hope somebody can tell me how to fix this.
(Or is this a problem in the python source?)

I will explain the problem by using 3 examples. (Sorry, long email)
The first two examples are behaving normal, the thirth is
strange...

I wrote the following flabbergasting code:
#-
print "1: This is the print statement."

# Now halt the program until someone hits enter
raw_input("2: This is the raw_input prompt.")

import sys
print "3: This is a possible solution. ",
sys.stdout.flush()
command = sys.stdin.readline()
#-
and saved it in the file 'script.py'.

*** First, normal behaviour to stdout
Now, I open a command line and run the following command:
python script.py

On screen appears, after a few 'enter' keys:
1: This is the print statement.
2: This is the raw_input prompt.
3: This is a possible solution.
All works fine..

*** Second, redirected stdout to file, normal behaviour.
>From the command prompt I run:
python script.py > stdout_catch.txt
The screen stays empty, and after a few 'enter' keys the prompt
reapears.

In the file 'stdout_catch.txt' are the lines:
1: This is the print statement.
2: This is the raw_input prompt.
3: This is a possible solution.
And again, all works fine..

*** Thirst, redirect stderr to file, STRANGE behaviour..
>From the command prompt I run:
python script.py 2> stderr_catch.txt
This should redirect strerr to the file and stdout should stay on the
screen.

But. What happens?
After a few 'enter' keys, on screen apears:
1: This is the print statement.
3: This is a possible solution.

WHERE IS THE SECOND LINE?
It is in the file stderr_catch.txt!!!

 See the problem?
Please Tell me? Why is the prompt produced by raw_input() printed to
the error channel? It should be stdout, just as the print statement
does.

Looking at the python source code on
http://svn.python.org/view/python/tags/r251/Python/bltinmodule.c?rev=54864&view=auto
[found: 'builtin_raw_input(PyObject *self, PyObject *args)'].

One thing that I notice is that the code checks whether stdin and
stdout are connected to a terminal ("isatty" function), but I do not
know why the prompt ends up on stderr then.

 What is the solution?
I have noticed this behaviour under DOS in Windows XP, Windows 2000,
Windows 2003 Server, Windows vista, and Linux. How do I get
raw_input() to send it's prompt to stdout?

Friendly greetings

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


Re: is possible to get order of keyword parameters ?

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

> 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?

You have to ask?

Because either you always initialise your Point with parameters in the same 
order, in which case just use positional parameters which is cleaner 
anyway, or when you have a function f(somePoint) you also need to know 
whether it takes a Point(width,height) or a Point(height,width) and if you 
get it wrong your code breaks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Custom class to a dictionary?

2008-01-26 Thread Oliver Beattie
On Jan 26, 12:01 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sat, 26 Jan 2008 03:35:18 -0800, Oliver Beattie wrote:
> > Just wondering if it is possible to pass a custom class instance
> > instance to dict() by way of using methods like you can for iterators
> > (__iter__, __getitem__ etc.) I see there is no __dict__ -- is there
> > anything else I can use to achieve this?
>
> Just write a method to return (key, value) pairs, and call that:
>
> >>> class Parrot(object):
>
> ...     def __init__(self):
> ...             self.keys = [1, 2, 3, 4]
> ...             self.values = ["one", "two", "three", "four"]
> ...     def generate_tuples(self):
> ...             for k,v in zip(self.keys, self.values):
> ...                     yield (k,v)
> ...>>> p = Parrot()
> >>> p.generate_tuples()
>
> >>> dict(p.generate_tuples())
>
> {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>
> Here's another way:
>
> >>> class Foo(object):
>
> ...     def __getitem__(self, i):
> ...             if i > 4:
> ...                     raise IndexError
> ...             return (i, 'foo %d' % i)
> ...>>> dict(Foo())
>
> {0: 'foo 0', 1: 'foo 1', 2: 'foo 2', 3: 'foo 3', 4: 'foo 4'}
>
> Bonus marks if you can explain why they both work :)
>
> (Hint: consider the "sequence protocol" and the "iterator protocol".)
>
> --
> Steven

Sure, I get what you're saying here and thanks for the advice; but I
don't want the keys as the iterator indices -- They should have custom
names (latitude, longitude and elevation). Is this possible (outside
of the custom method to generate two-tuples?) Sorry to be a pain!

The class looks like the below; I just whipped this up real quick but
it can generate the iterators it should -- just the dictionaries
should be different -- {'latitude': 0.0, 'longitude': 0.0,
'elevation': 0.0} or whatever):

class Coordinates(object):
"""Basic object for storing co-ordinate data."""
latitude = 0.0
longitude = 0.0
elevation = 0.0

def __unicode__(self):
return u'Coordinate (%s, %s, %s)' % (self.latitude, 
self.longitude,
self.elevation)

def __repr__(self):
return '' % 
(self.latitude,
self.longitude, self.elevation)

def __iter__(self):
return iter((self.latitude, self.longitude, self.elevation))

I guess it's just easier to have a dict() method to this end; just
wondered if there was a more 'Pythonic' way to do this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doesn't know what it wants

2008-01-26 Thread marek . rocki
> 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

I may be way off here, but why does vec2d inherit from
ctypes.Structure if it doesn't observe the protocol for Structures
(they're supposed to have _fields_, not __slots__)?
-- 
http://mail.python.org/mailman/listinfo/python-list


nayanthara nake out

2008-01-26 Thread sathish . suray
nayanthara nake out
namitha hot photos
trisha bathing videos

http://www.geocities.com/terfavet/
http://www.geocities.com/terfavet/
http://www.geocities.com/terfavet/

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


Re: translating Python to Assembler

2008-01-26 Thread Marc 'BlackJack' Rintsch
On Sat, 26 Jan 2008 03:09:05 +, Steven D'Aprano 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.

Maybe `bytecodehacks`_ + `psyco`, or PyPy!?

.. _bytecodehacks: http://sourceforge.net/projects/bytecodehacks/

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


trisha nake out

2008-01-26 Thread suray . sathish
trisha nake out
asin hot photos
namitha bathing videos

http://www.geocities.com/terfavet/
http://www.geocities.com/terfavet/
http://www.geocities.com/terfavet/

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


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

2008-01-26 Thread Jeroen Ruigrok van der Werven
-On [20080125 14:07], Bruno Desthuilliers ([EMAIL PROTECTED]) wrote:
>I'm surprised you've not been flamed to death by now - last time I 
>happened to write a pretty similar thing, I got a couple nut case 
>accusing me of being a liar trying to spread FUD about Java vs Python 
>respective VMs inner working, and even some usually sensible regulars 
>jumping in to label my saying as "misleading"...

I think your attitude in responding did not help much Bruno, if you want a
honest answer. And now you are using 'nut case'. What's with you using ad
hominems so readily?

Just an observation from peanut gallery. :)

-- 
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: translating Python to Assembler

2008-01-26 Thread Bjoern Schliessmann
[EMAIL PROTECTED] wrote:

> Intel processors can only process machine language[...] 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.

This may be true, but I think it's not bad to assume that machine
language and assembler are "almost the same" in this context, since
the translation between them is non-ambiguous (It's
just "recoding"; this is not the case with HLLs).

> 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.

(Not really -- object code files are composed of header data and
different segments, data and code, and only the code segments are
really meaningful to the processor.)

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

But you _do_ know that pyc files are Python byte code, and you could
only directly disassemble them to Python byte code directly?

> Assembler is nothing but codes, which are combinations of 1's and
> 0's. 

No, assembly language source is readable text like this (gcc):

.LCFI4:
movl$0, %eax
popl%ecx
popl%ebp
leal-4(%ecx), %esp
ret

Machine language is binary codes, yes.

> You can't read a pyc file in a hex editor, 

By definition, you can read every 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.

Not at all. Again: It's Python byte code. Try experimenting with
pdb.

Regards,


Björn

-- 
BOFH excuse #340:

Well fix that in the next (upgrade, update, patch release, service
pack).

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


Re: Doesn't know what it wants

2008-01-26 Thread Jeroen Ruigrok van der Werven
-On [20080126 08:31], Steven D'Aprano ([EMAIL PROTECTED]) wrote:
>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.

Yes, but it was not what I intended at all.

I guess I am just a bit too used to tacking on a , to denote a tuple since in
almost every other language seeing (()) is just an additional layer of braces.
I had totally forgotten Python would make it a tuple.

And I guess my head was still stuck with some other languages as well when I
made my other suggestion. Mea culpa.

-- 
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

Python System information

2008-01-26 Thread Clement
Hi friends,
How can i get system information like CPU load and RAM usage in linux.
Is there any packages for python
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: raw_input(), STRANGE behaviour

2008-01-26 Thread Mike Kent
On Jan 26, 7:23 am, Dox33 <[EMAIL PROTECTED]> wrote:
> I ran into a very strange behaviour of raw_input().
> I hope somebody can tell me how to fix this.
===CUT===
> *** Thirst, redirect stderr to file, STRANGE behaviour..
> From the command prompt I run:
> python script.py 2> stderr_catch.txt
> This should redirect strerr to the file and stdout should stay on the
> screen.
>
> But. What happens?
> After a few 'enter' keys, on screen apears:
> 1: This is the print statement.
> 3: This is a possible solution.
>
> WHERE IS THE SECOND LINE?
> It is in the file stderr_catch.txt!!!
>
>  See the problem?
> Please Tell me? Why is the prompt produced by raw_input() printed to
> the error channel? It should be stdout, just as the print statement
> does.

I recently ran into this behaviour myself, and reported it both here
and to the python-dev mailing list.  See
http://groups.google.com/group/comp.lang.python/browse_thread/thread/1011238ac6b79292/6f8b7c47873a4a1e?lnk=gst&q=unexpected+behavior#6f8b7c47873a4a1e

It turns out that *if* you don't have GNU readline installed, Python
falls back to its own implementation of readline, which is hard-coded
to send the prompt output to stderr.  Guido agreed that this is wrong,
and a bug for it has been entered into the Python bug tracking
database.

Your workaround until this bug is fixed is to install GNU readline,
and rebuild your python installation to use it rather than the fall-
back version.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Just for fun: Countdown numbers game solver

2008-01-26 Thread Arnaud Delobelle
Right, I've cleaned up my efforts a bit:

* tried to improve the efficiency of the 'fold' technique that I  
posted earlier.
* taken on Dan's email about equivalence of expressions
* created a problem random generator
* created a little function test to time and compare various things,  
and a 'random test' function.

In the file there are two methods for combining two expressions: 'ops'  
and 'cleverops'.  Ops is vanilla, cleverops only returns canonical  
expressions (roughly) as defined in Dan's email.

The two strategies for walking the solution tree are 'divide and  
conquer' (divide) and 'origami' (fold).  The code is pretty  
straighforward and is commented!

Then there are some convenience functions for running the algorithms:  
print_countdown, all_countdown and first_countdown.

Here's an example of how it works:

 >>> # print all solutions using the divide method, and cleverops:
 >>> print_countdown([50, 8, 5, 4, 9, 10], 983, method=divide,  
ops=cleverops)
50*5*4-9-8
(50*5+8-10)*4-9
(50+8/4)*(10+9)-5
50*(10-5)*4-9-8
 >>> # Test which method is fastest, divide or fold:
 >>> randtest(10, 'method', method=[divide, fold], ops=cleverops)
   divide fold
 0.317304 0.366359([1, 2, 4, 3, 6, 7], 249)
 0.495667 0.660426([75, 100, 50, 25, 9, 3], 289)
 0.443912 0.562409([50, 8, 5, 4, 9, 10], 399)
 0.199696 0.231997([100, 1, 5, 7, 1, 4], 833)
 0.406256 0.527588([50, 25, 10, 9, 3, 8], 123)
 0.263348 0.315722([9, 8, 7, 5, 1, 7], 730)
 0.403028 0.517426([25, 75, 9, 4, 10, 6], 605)
 0.420140 0.564138([10, 6, 10, 9, 5, 4], 900)
 0.278489 0.343525([4, 10, 5, 9, 9, 1], 388)
 0.485815 0.643627([100, 10, 2, 6, 3, 9], 146)
 
 0.371365 0.473322
 >>> # Test which method is best for finding just one solution:
 >>> randtest(10, 'method', method=[divide, fold],  
countdown=first_countdown)
   divide fold
 0.001674 0.043920([50, 75, 25, 9, 5, 8], 333)
 0.164332 0.072060([75, 2, 7, 8, 8, 5], 409)
 0.028889 0.212317([50, 100, 75, 6, 3, 9], 782)
 0.049070 0.005830([75, 4, 3, 2, 1, 6], 471)
 0.014728 0.091845([100, 75, 25, 50, 8, 7], 483)
 0.290982 0.367972([3, 1, 7, 6, 5, 3], 794)
 0.240363 0.118508([50, 100, 75, 3, 1, 10], 537)
 0.001693 0.009519([50, 75, 8, 7, 5, 5], 180)
 0.000289 0.037539([3, 9, 2, 4, 4, 1], 123)
 0.079161 0.174323([50, 75, 100, 25, 4, 10], 723)
 
 0.087118 0.113383
 >>> # Test how cleverops improves over ops for the fold method:
 >>> randtest(10, 'ops', method=fold, ops=[ops, cleverops])
  opscleverops
 1.689920 0.671041([75, 9, 6, 10, 3, 9], 874)
 0.938402 0.338120([5, 7, 8, 2, 1, 7], 258)
 0.982800 0.333443([25, 50, 9, 4, 8, 1], 309)
 1.152037 0.407845([25, 50, 3, 5, 10, 1], 736)
 0.892541 0.323406([9, 7, 1, 9, 4, 10], 108)
 1.794778 0.677161([25, 50, 10, 8, 2, 6], 357)
 1.534185 0.591878([50, 100, 25, 7, 7, 3], 773)
 1.013421 0.350179([50, 6, 3, 1, 8, 9], 761)
 0.612838 0.228354([25, 1, 4, 3, 1, 4], 148)
 1.213055 0.430611([50, 100, 5, 3, 10, 1], 814)
 
 1.182398 0.435204

I have found that the 'divide & conquer' strategy is faster than the  
'origami' one.  Moreover cleverops (i.e. clever pruning) improves  
origami by much more than divide&conquer.

Code follows.  Terry: I'm going to look at your code tonight and see  
if I can interface it with my little testing suite.  Thanks for  
posting it!

It was a lot of fun thinking about this, although I am sure that there  
is a lot of room for improvement.  In particular, there must be a  
simple way to avoid the amount of list tinkering in fold().  Any  
feedback greatly appreciated.

-- 
Arnaud

== countdown.py ===
def getop(h): return 'n' if isinstance(h, int) else h[1]

# An ops function takes two numbers with histories and yield all  
suitable
# ways of combining them together.

def ops(a, b):
 if a < b: a, b = b, a
 x, hx = a
 y, hy = b
 yield x + y, (a, '+', b)
 if x != 1 and y != 1:
 yield x * y, (a, '*', b)
 if x != y:
 yield x - y, (a, '-', b)
 if not x % y and y != 1:
 yield x / y, (a, '/', b)

def cleverops(a, b, getop=getop):
 if a < b: a, b = b, a
 x, hx = a
 y, hy = b
 opx, opy = getop(hx), getop(hy)
 # rx is the right operand of hx (or x if no history)
 rx = x if opx == 'n' else hx[2][0]
 if opy not in '+-':
 # Only allow a+b+c-x-y-z if a >= b >= c...
 if (opx == '+' and rx >= y) or (opx not in '+-' and x >= y):
 yield x + y, (a, '+', b)
 # ... and x >= y >= z
 if x > y and (opx != '-' or rx >= y

Re: Index of maximum element in list

2008-01-26 Thread bearophileHUGS
Paul Rubin:
> def posmax(seq, key=lambda x:x):
>return max(enumerate(seq), key=lambda k: key(k[1]))[0]

Is the Python max able to tell that's the identity function? I don't
think so, so your version may be slower and more memory hungry in the
common situation where you don't have a key function. So I think my
version is better :-)

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


Re: Doesn't know what it wants

2008-01-26 Thread rzed
Tim Rau <[EMAIL PROTECTED]> wrote in
news:0104616d-87be-4250-b3ef-
[EMAIL PROTECTED]
com: 

> 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.
> 

Are you passing the class or an instance of the class? I'd bet the 
former, but it should be the latter.

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


Beginner String formatting question

2008-01-26 Thread JAMoore84
Hi all,

I am trying to write a simple program that will accept an integral
"time" input in the HHMMSS format and output a "HH:MM:SS" form.  My
code is as follows:

import string

def FormatTime(time):
  '''Converts an HHMMSS string to HH:MM:SS format.'''

  timeString = str(time)  #converts the num to string

  hours= [timeString[0], timeString[1]]
  minutes = [timeString[2], timeString[3]]
  seconds = [timeString[4], timeString[5]]

  Ftime = "%s:%s:%s",(hours,minutes,seconds)
  clock = Ftime.join()

  return clock
  ===

when I run it from IDLE, I get this:

>>> Format.FormatTime(time)
['1', '1', ':', '2', '2', ':', '3', '3']
['1', '1', ':', '2', '2', ':', '3', '3']

My questions-
1) Why is this function printing out twice?
2)It may be a formatting issue, but I want to have the output as
"HH:MM:SS", rather than having it broken out into each cell.  I
thought the 'join' command would do this, but I must not be using it
properly/understanding something.
3)as a side note, I've noticed that the parameter "time" passed in
must be passed in as a string, otherwise I receive an error that
"time" is unsubscriptable.  Am I unable to pass in an int and then
convert it to a string within the function with str()?

I've been at this for a while, so I may not be able to see the forest
through the trees at this point.  I'd greatly appreciate any
suggestions or instruction on these mistakes.

Best,

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


Portably killing/signalling another process not supported?

2008-01-26 Thread John Nagle
There doesn't seem to be any way to portably kill another process
in Python.  "os.kill" is Mac/Unix only.  The "signal" module only lets
you send signals to the current process.  And the "subprocess" module
doesn't have a "kill" function.

Subprocess objects really should have a portable "interrupt" or
"kill" function.  They already have "poll" and "wait", which have
to be implemented differently for different systems; that's the
logical place for "kill".

Yes, there are nonportable workarounds
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462)
but no portable solution.

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


Re: Beginner String formatting question

2008-01-26 Thread Mark Tolonen

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi all,
>
> I am trying to write a simple program that will accept an integral
> "time" input in the HHMMSS format and output a "HH:MM:SS" form.  My
> code is as follows:
> 
> import string
>
> def FormatTime(time):
>  '''Converts an HHMMSS string to HH:MM:SS format.'''
>
>  timeString = str(time)  #converts the num to string
>
>  hours= [timeString[0], timeString[1]]
>  minutes = [timeString[2], timeString[3]]
>  seconds = [timeString[4], timeString[5]]
>
>  Ftime = "%s:%s:%s",(hours,minutes,seconds)
>  clock = Ftime.join()
>
>  return clock
>  ===
>
> when I run it from IDLE, I get this:
>
 Format.FormatTime(time)
> ['1', '1', ':', '2', '2', ':', '3', '3']
> ['1', '1', ':', '2', '2', ':', '3', '3']
>
> My questions-
> 1) Why is this function printing out twice?
> 2)It may be a formatting issue, but I want to have the output as
> "HH:MM:SS", rather than having it broken out into each cell.  I
> thought the 'join' command would do this, but I must not be using it
> properly/understanding something.
> 3)as a side note, I've noticed that the parameter "time" passed in
> must be passed in as a string, otherwise I receive an error that
> "time" is unsubscriptable.  Am I unable to pass in an int and then
> convert it to a string within the function with str()?
>
> I've been at this for a while, so I may not be able to see the forest
> through the trees at this point.  I'd greatly appreciate any
> suggestions or instruction on these mistakes.
>
> Best,
>
> Jimmy

Your code as displayed above doesn't work.

>>> Format.FormatTime(112233)
Traceback (most recent call last):
  File "", line 1, in 
  File "Format.py", line 13, in FormatTime
clock = Ftime.join()
AttributeError: 'tuple' object has no attribute 'join'
>>> Format.FormatTime('112233')
Traceback (most recent call last):
  File "", line 1, in 
  File "Format.py", line 13, in FormatTime
clock = Ftime.join()
AttributeError: 'tuple' object has no attribute 'join'

Make sure to copy/paste the exact working code.

Look at the 'time' and 'datetime' modules and the functions and methods 
'strftime' and 'strptime' for displaying and parsing times.

--Mark 

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


Re: Portably killing/signalling another process not supported?

2008-01-26 Thread Christian Heimes
John Nagle wrote:
> There doesn't seem to be any way to portably kill another process
> in Python.  "os.kill" is Mac/Unix only.  The "signal" module only lets
> you send signals to the current process.  And the "subprocess" module
> doesn't have a "kill" function.
> 
> Subprocess objects really should have a portable "interrupt" or
> "kill" function.  They already have "poll" and "wait", which have
> to be implemented differently for different systems; that's the
> logical place for "kill".
> 
> Yes, there are nonportable workarounds
> (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462)
> but no portable solution.

We are looking for somebody to implement a portable and cross platform
implementation of kill() and send_signal() for the subprocess module.
Are you interested in working on a patch for Python 2.6 and 3.0?

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


Re: Beginner String formatting question

2008-01-26 Thread chaosgy
On 1月27日, 上午1时02分, [EMAIL PROTECTED] wrote:
> Hi all,
>
> I am trying to write a simple program that will accept an integral
> "time" input in the HHMMSS format and output a "HH:MM:SS" form.  My
> code is as follows:
> 
> import string
>
> def FormatTime(time):
>   '''Converts an HHMMSS string to HH:MM:SS format.'''
>
>   timeString = str(time)  #converts the num to string
>
>   hours= [timeString[0], timeString[1]]
>   minutes = [timeString[2], timeString[3]]
>   seconds = [timeString[4], timeString[5]]
>
>   Ftime = "%s:%s:%s",(hours,minutes,seconds)
>   clock = Ftime.join()
>
>   return clock
>   ===
>
> when I run it from IDLE, I get this:
>
> >>> Format.FormatTime(time)
>
> ['1', '1', ':', '2', '2', ':', '3', '3']
> ['1', '1', ':', '2', '2', ':', '3', '3']
>
> My questions-
> 1) Why is this function printing out twice?
> 2)It may be a formatting issue, but I want to have the output as
> "HH:MM:SS", rather than having it broken out into each cell.  I
> thought the 'join' command would do this, but I must not be using it
> properly/understanding something.
> 3)as a side note, I've noticed that the parameter "time" passed in
> must be passed in as a string, otherwise I receive an error that
> "time" is unsubscriptable.  Am I unable to pass in an int and then
> convert it to a string within the function with str()?
>
> I've been at this for a while, so I may not be able to see the forest
> through the trees at this point.  I'd greatly appreciate any
> suggestions or instruction on these mistakes.
>
> Best,
>
> Jimmy

import string


def FormatTime(time):
  '''Converts an HHMMSS string to HH:MM:SS format.'''


  timeString = "%06d" % (time, )  #converts the num to string

  return timeString[:2] + ":" + timeString[2:4] + ":" +
timeString[4:];

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

Re: Beginner String formatting question

2008-01-26 Thread Gary Herron
[EMAIL PROTECTED] wrote:
> Hi all,
>
> I am trying to write a simple program that will accept an integral
> "time" input in the HHMMSS format and output a "HH:MM:SS" form.  My
> code is as follows:
> 
> import string
>
> def FormatTime(time):
>   '''Converts an HHMMSS string to HH:MM:SS format.'''
>
>   timeString = str(time)  #converts the num to string
>
>   hours= [timeString[0], timeString[1]]
>   minutes = [timeString[2], timeString[3]]
>   seconds = [timeString[4], timeString[5]]
>
>   Ftime = "%s:%s:%s",(hours,minutes,seconds)
>   clock = Ftime.join()
>
>   return clock
>   ===
>
> when I run it from IDLE, I get this:
>
>   
 Format.FormatTime(time)
 
> ['1', '1', ':', '2', '2', ':', '3', '3']
> ['1', '1', ':', '2', '2', ':', '3', '3']
>   
The code you posted did not produce the output you are showing.  You'll
have to be more careful with your posting if you expect to get a useful
answer.

Beyond that, there are a bundle of errors in the code that will prevent
it from working:

If you want to carve a string into substrings, use this kind of syntax
  hours = timeString[0:2]
  minutes = timeString[2:4]
  seconds = timeString{4:6]

If you want to combine small strings into longer strings you've got
several choices:
  output = hours + ':' + ...
or
  output = "%s:%s:%s" %  (hours, ...)  #NOTICE the % operator between
the  format string and value tuple

Since both of those produce a  string as output, you have no need of a
join, BUT if you do decide to produce a list of strings that you want to
join into a longer string, you need to use join correctly:
parts = [hours,minutes,seconds]
output = ':'.join(parts)

Another error:  If your time starts with an hour that is just a single
digit, then your string will be only 5 digits long (there will be no
leading zero).   In that case, all the extraction of individual fields
based on indexing into the string will be off by one.
> My questions-
> 1) Why is this function printing out twice?
>   
Show us your real code.
> 2)It may be a formatting issue, but I want to have the output as
> "HH:MM:SS", rather than having it broken out into each cell.  I
> thought the 'join' command would do this, but I must not be using it
> properly/understanding something.
>   
See the example above.
> 3)as a side note, I've noticed that the parameter "time" passed in
> must be passed in as a string, otherwise I receive an error that
> "time" is unsubscriptable.  Am I unable to pass in an int and then
> convert it to a string within the function with str()?
>   
Of course you can pass any type into a function.  Then you have to write
the program to operate correctly on whatever the input type is.
> I've been at this for a while, so I may not be able to see the forest
> through the trees at this point.  I'd greatly appreciate any
> suggestions or instruction on these mistakes.
>   
My guess is that's why the code you show does not match the output you
present.
> Best,
>
> Jimmy
>   

Gary Herron


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


Replacing a package with another

2008-01-26 Thread J . Pablo Fernández
Hello,

Is it possible to replace one package with another at runtime, that is, I
have package a.blah which I want instead of b.blah, so I can "inject"
functionality in an existing package?

Thanks.
-- 
J. Pablo Fernández <[EMAIL PROTECTED]> (http://pupeno.com)

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

Re: Sorting Large File (Code/Performance)

2008-01-26 Thread Gabriel Genellina
En Fri, 25 Jan 2008 17:50:17 -0200, Paul Rubin  
<"http://phr.cx"@NOSPAM.invalid> escribi�:

> 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.

Or forget about Python and use the Windows sort command. It has been there  
since MS-DOS ages, there is no need to download and install other  
packages, and the documentation at  
http://technet.microsoft.com/en-us/library/bb491004.aspx says:

Limits on file size:
   The sort command has no limit on file size.

Better, since the OP only intents to extract lines starting with "zz", use  
the findstr command:
findstr /l /b "zz" filename.exe
would do the job.

Why doing things more complicated than that?

-- 
Gabriel Genellina

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

Re: Anybody has ported talib to Python via SWIG

2008-01-26 Thread Gabriel Genellina
En Thu, 24 Jan 2008 20:49:33 -0200, Aldo Ceccarelli  
<[EMAIL PROTECTED]> escribi�:

> Hi Everybody,
> TaLib (technical analysis package with function indicators coded in C/C
> ++, http://www.ta-lib.org ) has a complete library with source in C/C+
> +.
>
> I am new to SWIG (wrapper interface generator) and would really
> appreciate any Python (.py) port of TaLib to be able to call and test
> TaLib's functions (f.i. MACD, Parabolic SAR and so on) in some Python
> (2.5) script.
>
> Do you have idea whether TaLib Python package has already been
> generated and can be eventually downloaded anywhere?

If Talib has a C API (not C++), the ctypes module can be used to call  
those C functions, so there is no need to write a special SWIG wrapper. In  
fact it may be much easier to do that way.

ctypes is a standard module on Python 2.5, and is documented here:
http://docs.python.org/lib/module-ctypes.html

-- 
Gabriel Genellina

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

Programmer Need

2008-01-26 Thread tim
Hi,
  I have a program of about 300 lines of code that I wrote in
AutoHotKeys.   I am looking for someone who might be interested in
making a little $ to help me bring this program into a mac compatable
language.

I can be reached at   tim at rileyphotographic dot come
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: grouping in module 'locale'

2008-01-26 Thread Gabriel Genellina
En Fri, 25 Jan 2008 14:46:13 -0200, Roman Bertle <[EMAIL PROTECTED]>  
escribi�:

> I try to format monetary values using the locale module, python2.5:

 locale.localeconv()
> {... 'mon_thousands_sep': ' '
 locale.currency(1234.5678, grouping=True, symbol=False)
> '1234,57'
>
> As you can see, the decimal point is correctly set to ','. But the
> grouping is not done, every 3 digits should be separated by space (' ').

> Using the 'de_DE.utf8' locale, ist works:
 locale.currency(1234.5678, grouping=True, symbol=False)
> '1.234,57'
>
> The difference here is that thounds_sep is '.', not ' '. If we look at  
> the code
> of locale.py, revision 55038, lines 157-161, the inserted spaces are  
> later
> deleted again:
>
> while seps:
> sp = formatted.find(' ')
> if sp == -1: break
> formatted = formatted[:sp] + formatted[sp+1:]
> seps -= 1

Looks like a bug, please report it at http://bugs.python.org
Only *leading* and *trailing* spaces should be removed, the code above  
removes spaces anywhere. This would be a better alternative:

 if seps:
 i = 0
 while seps and i=0 and formatted[i]==' ':
 seps -= 1
 i -= 1
 formatted = formatted[:i+1]

Integers should be processed that way too:

py> locale.format('%10d', 1234567, True)
'   1.234.567'
(output has 12 characters, not 10)

Another issue: the code currently assumes that mon_thousands_sep and  
thousands_sep are single characters, but they might be longer. There  
should be a seps *= len(separator used) before the above whitespace  
removal.

I'll try to make a patch tomorrow.

-- 
Gabriel Genellina

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

wx.EVT_RIGHT_UP strangeness?

2008-01-26 Thread sigpoggy
I am playing with wxPython 2.8.7.1 on OS X 10.4.11 with MacPython 2.5

When running the demo program, the ShapeWindow demo does not close the
window
on right click. It turns out that the wx.EVT_RIGHT_UP does not fire.

I discovered that one way to get it to fire is to bind the
wx.EVT_RIGHT_DOWN event also.

Thus adding the following two lines solves the problem:

in __init__ add:  self.Bind(wx.EVT_RIGHT_DOWN,self.OnRightDown)

secondly add:  def OnRightDown(self, evt): pass

Everything then works ok.

My question is: Is this how it is supposed to work, and if not, am I
the only one with
this problem?

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


Re: Beginner String formatting question

2008-01-26 Thread JAMoore84
I apologize for the lack of details in my last post.  This time
formatting program is a piece of a larger program I am trying to write
to de-clutter GPS transmission.  I have a GPS receiver that transmits
its readings via bluetooth.  I've been able to use pySerial and store
X number of bytes, then write that to a file (the next step will be
finding a way to write the stream to a file directly).  The raw GPS
data is tranmitted in the NMEA format (http://vancouver-webpages.com/
peter/nmeafaq.txt):

$GPRMC,024830,V,,N,,E,,,260108,,,N*58
$GPVTG,,T,,M,,N,,K,N*2C
$GPGGA,024831,LAT_GOES_HERE,N,LONG_GOES_HERE,E,0,00,,,M,,M,,*61
$GPGSA,A,1,,,*1E
$GPGSV,3,1,09,09,,,37,13,,,00,18,,,00,23,,,00*75
$GPGSV,3,2,09,01,,,00,29,,,00,14,,,00,26,,,00*7A
$GPGSV,3,3,09,12,,,00*73
$GPRMC,024831,V,LAT_GOES_HERE,N,LONG_GOES_HERE,E,,,260108,,,N*59
$GPVTG,,T,,M,,N,,K,N*2C

the "$GPGGA" and "$GPRMC" lines are the ones that will give you your
Latitude and Longitude data --or the would if I had a signal.
All the entries are comma delimited, so I used the split(',') function
to parse the appropriate statements.  Here's the code for that:
=
input = open('c:\sample_readout.txt','r')   #location of the Raw GPS
data
output = open('c:\GPSout.txt', 'w')

output.write("Timestamp \t Latitude \t Longitude \t Velocity")

s = input.readlines()

for line in s:

  if line.startswith('$GPGGA'):
InputTuple = line.split(',')

time = InputTuple[1]
lat  = InputTuple[2]+' '+InputTuple[3]
long = InputTuple[4]+' '+InputTuple[5]

out = '\n '+ time + '\t\t' + lat + '\t\t\t' + long

output.writelines(out)

  elif line.startswith('$GPRMC'):
InputTuple = line.split(',')

time = InputTuple[1]
lat  = InputTuple[3]+' '+InputTuple[4]
long = InputTuple[5]+' '+InputTuple[6]

out = '\n '+ time + '\t\t' + lat + '\t\t\t' + long

output.writelines(out)

  elif line.startswith('$GPVTG'):  #this will give grounp speed in
knts and [7] gives kmph
InputTuple = line.split(',')

out = '\n ' + '\t\t' + InputTuple[5]

output.writelines(out)

input.close()
output.close()


The time stamp for both the GPRMC and GPGGA lines will be stored in
InputTuple[1].

Right now, this program will read the GPS data file and pull out the
necessary information.  I wanted the Format.py program to function as
a module so that I could call Format.FormatTime(time) to change the
HHMMSS GPS data to HH:MM:SS, for readability.  The next step was to
write a FormatCoord function (within the Format module) to do the same
for lat/long data.

Now that I've explained the structure, the argument of
Format.FormatTime() will be InputTuple[1] (the timestamp).  I want to
be able to call that function in the GPS program to read the contents
of InputTuple[1] and write the HH:MM:SS data to the file.

I've incorporated some of your recommendations into my program already
and it looks much better.  Thanks to everyone for your suggestions.

Jimmy


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


Re: Portably killing/signalling another process not supported?

2008-01-26 Thread John Nagle
Christian Heimes wrote:
> John Nagle wrote:
>> There doesn't seem to be any way to portably kill another process
>> in Python.  "os.kill" is Mac/Unix only.  The "signal" module only lets
>> you send signals to the current process.  And the "subprocess" module
>> doesn't have a "kill" function.
>>
>> Subprocess objects really should have a portable "interrupt" or
>> "kill" function.  They already have "poll" and "wait", which have
>> to be implemented differently for different systems; that's the
>> logical place for "kill".
>>
>> Yes, there are nonportable workarounds
>> (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462)
>> but no portable solution.
> 
> We are looking for somebody to implement a portable and cross platform
> implementation of kill() and send_signal() for the subprocess module.
> Are you interested in working on a patch for Python 2.6 and 3.0?
> 
Since I use 2.4 and 2.5, I'm  interested in something that
goes back to at least 2.4.

The ActiveState solution above needs C modules that aren't part of
the regular CPython distribution, unfortunately.

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


Re: Index of maximum element in list

2008-01-26 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> > def posmax(seq, key=lambda x:x):
> >return max(enumerate(seq), key=lambda k: key(k[1]))[0]
> 
> Is the Python max able to tell that's the identity function? I don't
> think so, so your version may be slower and more memory hungry in the
> common situation where you don't have a key function. So I think my
> version is better :-)

I don't think there will be a noticable memory increase.  It's not a
DSU situation like in sorting, it's just a small constant parameter.
Yes there might be a small speed hit.  The compiler in principle could
convert the (lambda k: lambda x: k[1]) to something like
operator.itemgetter(1), but I doubt that it actually does so.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression negate a word (not character)

2008-01-26 Thread Ilya Zakharevich
[A complimentary Cc of this posting was sent to
Summercool 
<[EMAIL PROTECTED]>], who wrote in article <[EMAIL PROTECTED]>:
> so for example, it will grep for
> 
>   winter tire
>   tire
>   retire
>   tired
> 
> but will not grep for
> 
>   snow tire
>   snow   tire
>   some snowtires

This does not describe the problem completely.  What about

  thisnow tire
  snow; tire

etc?  Anyway, one of the obvious modifications of

   (^ | \b(?!snow) \w+ ) \W* tire

should work.

Hope this helps,
Ilya

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


Re: Doesn't know what it wants

2008-01-26 Thread Tim Rau
On Jan 26, 2:52 am, John Machin <[EMAIL PROTECTED]> wrote:
> 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
> """

Ok, so apparently, it needs a different vec2d, one which is
specifically modified vec2d to work with the library Chipmunk, which
is a c library, but with pindings binding(PyMunk)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Index of maximum element in list

2008-01-26 Thread Steven D'Aprano
On Sat, 26 Jan 2008 12:40:26 -0800, Paul Rubin wrote:

> [EMAIL PROTECTED] writes:
>> > def posmax(seq, key=lambda x:x):
>> >return max(enumerate(seq), key=lambda k: key(k[1]))[0]
>> 
>> Is the Python max able to tell that's the identity function? I don't
>> think so, so your version may be slower and more memory hungry in the
>> common situation where you don't have a key function. So I think my
>> version is better :-)
> 
> I don't think there will be a noticable memory increase.  It's not a DSU
> situation like in sorting, it's just a small constant parameter. Yes
> there might be a small speed hit.  The compiler in principle could
> convert the (lambda k: lambda x: k[1]) to something like
> operator.itemgetter(1), but I doubt that it actually does so.

Actually there is a big speed hit. Until such time that Python has a fast 
identity function, and lambda x:x isn't it, your version is about three 
times slower than Bearophile's.

Much to my surprise, the fastest solution I've tried appears to be a pure 
Python version not even using max() at all.

Here are the three versions:

def posmax1(seq, key=None):  # bearophile's version
"""Return the position of the first maximum item of a sequence.
It accepts the usual key parameter too."""
if key:
return max(enumerate(seq), key=lambda k: key(k[1]))[0]
else:
return max(enumerate(seq), key=itemgetter(1))[0]


def posmax2(seq, key=lambda x:x):  # Paul Rubin's version
return max(enumerate(seq), key=lambda k: key(k[1]))[0]


def posmax3(seq, key=None):  # Pure Python version
if key is None:
m = seq[0]
index = 0
for i, x in enumerate(seq):
if x > m:
m = x
index = i
return index
else:
return NotImplemented



And my timing results:

>>> alist = [3]*1000 + [5] + [3]*1000
>>> assert alist.index(5) == 1000
>>> assert posmax1(alist) == posmax2(alist) == posmax3(alist) == 1000
>>>
>>> min(timeit.Timer('posmax1(alist)',
... 'from __main__ import posmax1, alist').repeat(number=1000))/1000
0.00074387979507446289
>>> min(timeit.Timer('posmax2(alist)',
... 'from __main__ import posmax2, alist').repeat(number=1000))/1000
0.0022983889579772949
>>> min(timeit.Timer('posmax3(alist)',
... 'from __main__ import posmax3, alist').repeat(number=1000))/1000
0.00063846302032470701



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


LEL

2008-01-26 Thread bearophileHUGS
The LEL mini language (there used for JRuby) seems nice, it may be
added to Tkinter:
http://ihate.rubyforge.org/profligacy/lel.html
http://ihate.rubyforge.org/profligacy/sample.html

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


Re: Python and binary compatibility

2008-01-26 Thread Christian Heimes
Joshua Kugler wrote:
 > 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...

You can still find some copies of the free toolkit on the internet.

Christian

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


Re: Index of maximum element in list

2008-01-26 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> Actually there is a big speed hit. Until such time that Python has a fast 
> identity function, and lambda x:x isn't it, your version is about three 
> times slower than Bearophile's.

Interesting.  Fixing that speed hit probably needs compiler attention.

> Much to my surprise, the fastest solution I've tried appears to be a pure 
> Python version not even using max() at all.

Could you try the l.index version?  That avoids creating all those
intermediate tuples.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Index of maximum element in list

2008-01-26 Thread bearophileHUGS
Steven D'Aprano:
> Much to my surprise, the fastest solution I've tried appears to be a pure
> Python version not even using max() at all.

That version is easy to translate to other languages and you can
probably find that Psyco makes it much faster still.

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


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

2008-01-26 Thread Ben Finney
Carl Banks <[EMAIL PROTECTED]> writes:

> 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.
> 
> 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'

Thanks, that makes it clear.

> 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.

I've not seen that before, but it seems an elegant way to address what
the OP is asking for.

-- 
 \"Madness is rare in individuals, but in groups, parties, |
  `\ nations and ages it is the rule."  -- Friedrich Nietzsche |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Text-based data inspector for Python?

2008-01-26 Thread Gabriel Genellina
En Fri, 25 Jan 2008 12:28:08 -0200, kj <[EMAIL PROTECTED]> escribi�:

> The one thing I couldn't
> find, and would greatly miss if not available, is the ability to
> set breakpoints by inserting a particular indication right in the
> code.  In the Perl debugger one can insert something like the
> following anywhere in the code:
>
>   $DB::single = 1;
>
> When such a line executes, the debugger immediately switches to
> single-step mode.  It's a very flexible technique, and I like it

I think that pdb.set_trace() does what you want.

-- 
Gabriel Genellina

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

Re: raw_input(), STRANGE behaviour

2008-01-26 Thread Dox33
Hello Mike,

Thanks for your reply.
Since I momentarily do not have the ability to build a new python
executable, I would like to ask for your help in this case.
Are you able to supply me with a corrected version?

Friendly greetings

Rens Duijsens

On 26 jan, 16:50, Mike Kent <[EMAIL PROTECTED]> wrote:
> On Jan 26, 7:23 am, Dox33 <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > I ran into a very strange behaviour of raw_input().
> > I hope somebody can tell me how to fix this.
> ===CUT===
> > *** Thirst, redirect stderr to file, STRANGE behaviour..
> > From the command prompt I run:
> > python script.py 2> stderr_catch.txt
> > This should redirect strerr to the file and stdout should stay on the
> > screen.
>
> > But. What happens?
> > After a few 'enter' keys, on screen apears:
> > 1: This is the print statement.
> > 3: This is a possible solution.
>
> > WHERE IS THE SECOND LINE?
> > It is in the file stderr_catch.txt!!!
>
> >  See the problem?
> > Please Tell me? Why is the prompt produced by raw_input() printed to
> > the error channel? It should be stdout, just as the print statement
> > does.
>
> I recently ran into this behaviour myself, and reported it both here
> and to the python-dev mailing list.  
> Seehttp://groups.google.com/group/comp.lang.python/browse_thread/thread/...
>
> It turns out that *if* you don't have GNU readline installed, Python
> falls back to its own implementation of readline, which is hard-coded
> to send the prompt output to stderr.  Guido agreed that this is wrong,
> and a bug for it has been entered into the Python bug tracking
> database.
>
> Your workaround until this bug is fixed is to install GNU readline,
> and rebuild your python installation to use it rather than the fall-
> back version.- Tekst uit oorspronkelijk bericht niet weergeven -
>
> - Tekst uit oorspronkelijk bericht weergeven -

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


Re: do design patterns still apply with Python?

2008-01-26 Thread HoustonJuliet

I am a fan of these people:

Goldie Hawn
Kate Hudson
Oliver Reed
Robert Conrad
Vic Morrow
Bill Bixby




Grant Edwards wrote:
> 
> On 2006-03-02, John Salerno <[EMAIL PROTECTED]> wrote:
> 
>> Since Python does so many things different, especially compared to 
>> compiled and statically typed languages, do most of the basic design 
>> patterns still apply when writing Python code?
> 
> Definitely.  Especially plaid, paisley, and a nice medium
> houndstooth check.  But please, not all at the same time.
> 
> -- 
> Grant Edwards   grante Yow!  Maybe we could
> paint
>   at   GOLDIE HAWN a rich
> PRUSSIAN
>visi.comBLUE --
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 
:drunk:
-- 
View this message in context: 
http://www.nabble.com/do-design-patterns-still-apply-with-Python--tp3210321p15114746.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: do design patterns still apply with Python?

2008-01-26 Thread HoustonJuliet

I am a fan of Oliver Reeds since a toddler

HoustonJuliet wrote:
> 
> I am a fan of these people:
> 
> Goldie Hawn
> Kate Hudson
> Oliver Reed
> Robert Conrad
> Vic Morrow
> Bill Bixby
> 
> 
> 
> 
> Grant Edwards wrote:
>> 
>> On 2006-03-02, John Salerno <[EMAIL PROTECTED]> wrote:
>> 
>>> Since Python does so many things different, especially compared to 
>>> compiled and statically typed languages, do most of the basic design 
>>> patterns still apply when writing Python code?
>> 
>> Definitely.  Especially plaid, paisley, and a nice medium
>> houndstooth check.  But please, not all at the same time.
>> 
>> -- 
>> Grant Edwards   grante Yow!  Maybe we could
>> paint
>>   at   GOLDIE HAWN a rich
>> PRUSSIAN
>>visi.comBLUE --
>> -- 
>> http://mail.python.org/mailman/listinfo/python-list
>> 
>> 
> :drunk:
> 

-- 
View this message in context: 
http://www.nabble.com/do-design-patterns-still-apply-with-Python--tp3210321p15114748.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: do design patterns still apply with Python?

2008-01-26 Thread HoustonJuliet

I think the world of Oliver Reed, and I was so sad to learn about his death. 
I always had a crush on Oliver Reed, and I have been a fan for over 35 years
now.  I was born on June 13, 1972, and I am 35 years old.  



HoustonJuliet wrote:
> 
> I am a fan of Oliver Reeds since a toddler
> 
> HoustonJuliet wrote:
>> 
>> I am a fan of these people:
>> 
>> Goldie Hawn
>> Kate Hudson
>> Oliver Reed
>> Robert Conrad
>> Vic Morrow
>> Bill Bixby
>> 
>> 
>> 
>> 
>> Grant Edwards wrote:
>>> 
>>> On 2006-03-02, John Salerno <[EMAIL PROTECTED]> wrote:
>>> 
 Since Python does so many things different, especially compared to 
 compiled and statically typed languages, do most of the basic design 
 patterns still apply when writing Python code?
>>> 
>>> Definitely.  Especially plaid, paisley, and a nice medium
>>> houndstooth check.  But please, not all at the same time.
>>> 
>>> -- 
>>> Grant Edwards   grante Yow!  Maybe we could
>>> paint
>>>   at   GOLDIE HAWN a rich
>>> PRUSSIAN
>>>visi.comBLUE --
>>> -- 
>>> http://mail.python.org/mailman/listinfo/python-list
>>> 
>>> 
>> :drunk:
>> 
> 
> 
:drunk:
-- 
View this message in context: 
http://www.nabble.com/do-design-patterns-still-apply-with-Python--tp3210321p15114781.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Windows issue -- method to control generation of bytecode files

2008-01-26 Thread Gabriel Genellina
En Fri, 25 Jan 2008 15:50:29 -0200, Alan Nichols  
<[EMAIL PROTECTED]> escribi�:

> It seems that for some types of user accounts (specifically regular  
> users,
> not superusers or admins) MS Windows will not allow writes to the  
> C:\Program
> Files directory.  As a result, .py source files cannot be located in
> C:\Program Files because the .pyc files cannot be generated there.

Make the installer compile them at the time they're installed. Or provide  
them already compiled.

-- 
Gabriel Genellina

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

Re: Beginner String formatting question

2008-01-26 Thread John Machin
On Jan 27, 7:15 am, [EMAIL PROTECTED] wrote:
> I apologize for the lack of details in my last post.

There is nothing to apologise for. Unlike some, you gave enough
information, without prompting, to get answers to your questions.
Don't go to the other extreme :-)

>  This time
> formatting program is a piece of a larger program I am trying to write
> to de-clutter GPS transmission.  I have a GPS receiver that transmits
> its readings via bluetooth.  I've been able to use pySerial and store
> X number of bytes, then write that to a file (the next step will be
> finding a way to write the stream to a file directly).  The raw GPS
> data is tranmitted in the NMEA format (http://vancouver-webpages.com/
> peter/nmeafaq.txt):
>
> $GPRMC,024830,V,,N,,E,,,260108,,,N*58
> $GPVTG,,T,,M,,N,,K,N*2C
> $GPGGA,024831,LAT_GOES_HERE,N,LONG_GOES_HERE,E,0,00,,,M,,M,,*61
> $GPGSA,A,1,,,*1E
> $GPGSV,3,1,09,09,,,37,13,,,00,18,,,00,23,,,00*75
> $GPGSV,3,2,09,01,,,00,29,,,00,14,,,00,26,,,00*7A
> $GPGSV,3,3,09,12,,,00*73
> $GPRMC,024831,V,LAT_GOES_HERE,N,LONG_GOES_HERE,E,,,260108,,,N*59
> $GPVTG,,T,,M,,N,,K,N*2C
>
> the "$GPGGA" and "$GPRMC" lines are the ones that will give you your
> Latitude and Longitude data --or the would if I had a signal.
> All the entries are comma delimited, so I used the split(',') function
> to parse the appropriate statements.  Here's the code for that:
> =
> input = open('c:\sample_readout.txt','r')   #location of the Raw GPS
> data
> output = open('c:\GPSout.txt', 'w')

Presumably you are running MS-DOS 2.0 or later, so you have a
hierarchical file system. Don't put files in your root directory!!!

Don't use single backslashes in Windows file names -- e.g. in 'foo
\noddy' the \n will be interpreted as a newline. Use one of the
following methods:
'c:\\GPS\\test1.txt'
r'c:\GPS\test1.txt'
'c:/GPS/test1.txt'

It's not really a good habit to have constant paths in your scripts
anyway, especially for output files.

>
> output.write("Timestamp \t Latitude \t Longitude \t Velocity")
>
> s = input.readlines()
>
> for line in s:

Instead of the above two lines, do this:
for line in input:

>
>   if line.startswith('$GPGGA'):
> InputTuple = line.split(',')

Try choosing meaningful names. It's not a tuple, it's a list.

And read this:
http://www.python.org/dev/peps/pep-0008/

>
> time = InputTuple[1]
> lat  = InputTuple[2]+' '+InputTuple[3]
> long = InputTuple[4]+' '+InputTuple[5]
>
> out = '\n '+ time + '\t\t' + lat + '\t\t\t' + long
>
> output.writelines(out)
>
>   elif line.startswith('$GPRMC'):
> InputTuple = line.split(',')

You should write the code to parse the input format *once* and parse
it *correctly* -- at the moment the last field will contain
'data*checksum\n' instead of just 'data'.

Following is an example of one style of input parsing:

C:\junk>type nmea.py

sample = """
$GPRMC,024830,V,,N,,E,,,260108,,,N*58
$GPVTG,,T,,M,,N,,K,N*2C
$GPGSA,A,1,,,*1E
$GPGSV,3,1,09,09,,,37,13,,,00,18,,,00,23,,,00*75
$GPGSV,3,2,09,01,,,00,29,,,00,14,,,00,26,,,00*7A
$GPGSV,3,3,09,12,,,00*73
$GPVTG,,T,,M,,N,,K,N*2C
$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47
"""

def unpack_nmea_message(line):
line = line.rstrip() # remove any newline etc
if not line:
return [] # empty line
if line[0] != '$':
raise Exception('NMEA line %r: should start with $' % line)
try:
apos = line.rindex('*')
except ValueError:
raise Exception('NMEA line %r: missing checksum?' % line)
try:
cksum = int(line[apos+1:], 16)
except ValueError:
raise Exception('NMEA line %r: checksum not hex' % line)
if not(0 <= cksum <= 255):
raise Exception(
'NMEA line %r: checksum not in range 0-255 inclusive'
% line)
calc_cksum = 0
data = line[1:apos]
for c in data:
calc_cksum = calc_cksum ^ ord(c)
if calc_cksum != cksum:
print calc_cksum, cksum, repr(chr(calc_cksum ^ cksum))
raise Exception('NMEA line %r: invalid checksum' % line)
fields = data.split(',')
# maybe check for minimum number of fields
return fields

if __name__ == '__main__':
for x, line in enumerate(sample.splitlines()):
print 'Line %3d: %r' % (x+1, line)
print ': %r'% unpack_nmea_message(line)

C:\junk>nmea.py
Line   1: ''
: []
Line   2: '$GPRMC,024830,V,,N,,E,,,260108,,,N*58'
: ['GPRMC', '024830', 'V', '', 'N', '', 'E', '', '', '260108',
'', '', 'N']
Line   3: '$GPVTG,,T,,M,,N,,K,N*2C'
: ['GPVTG', '', 'T', '', 'M', '', 'N', '', 'K', 'N']
Line   4: '$GPGSA,A,1,,,*1E'
: ['GPGSA', 'A', '1', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '']
Line   5: '$GPGSV,3,1,09,09,,,37,13,,,00,18,,,00,23,,,00*75'
: ['GPGSV', '3', '1', '09', '09', '', '', '37', '13', '', '',
'00', '18', '', '', '00', '23', '', '', '00']
Line   6: '$GPGSV,3

Re: Operator overloading

2008-01-26 Thread MRAB
On Jan 25, 8:52 pm, Hexamorph <[EMAIL PROTECTED]> wrote:
> [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.

You'd probably want the change to be limited to a certain scope so
that, for example, it doesn't affect imported modules.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python System information

2008-01-26 Thread NMBooker
On Jan 26, 2:58 pm, Clement <[EMAIL PROTECTED]> wrote:
> Hi friends,
> How can i get system information like CPU load and RAM usage in linux.
> Is there any packages for python

Good question.

I've just had a scout around on Google and found no "ready-made"
libraries, so it looks like you'll have to poke around in the /proc
directory.

Apologies in advance if you already know about /proc and how to parse
files.  I haven't tested the code in this answer on anything but an
AMD Athlon XP, but I would hope it would work on other architectures.
I'm not quite so sure about other UNIXes though.

Reading the manpage for proc is useful for this:-
 $ man proc

You're probably interested in /proc/stat (for calculating CPU usage), /
proc/loadavg (for getting load average and process/thread counts),
and /proc/meminfo (for memory usage).

I've posted all the code from below at 
http://www.dcs.warwick.ac.uk/~csueda/proc.py
Once I've graduated in the Summer that will disappear though.

meminfo
===

In meminfo, you're probably most interested in the fields MemTotal and
MemFree (and possibly Buffers and Cached if you want to see how much
of the used memory is in fact cache rather than user programs).  You
might also want to look at SwapTotal and SwapFree.

The following just dumps all the lines from /etc/meminfo into a
dictionary (str:int):

# I thought a regex would be the easiest way to do this.
import re
re_parser = re.compile(r'^(?P\S*):\s*(?P\d*)\s*kB')
def meminfo():
"""-> dict of data from meminfo (str:int).
Values are in kilobytes.
"""
result = dict()
for line in open('/proc/meminfo'):
match = re_parser.match(line)
if not match:
continue  # skip lines that don't parse
key, value = match.groups(['key', 'value'])
result[key] = int(value)
return result


stat

/proc/stat contains the CPU info you need.

In stat, you can look at the first four fields of each "cpu" record,
for example on my machine:
$ cat /proc/stat
cpu  63888 1648769 11015 494 998 799 59339 0
cpu0 63888 1648769 11015 494 998 799 59339 0
intr 9483429 148 2 0 0 4 0 0 0 3 0 0 0 4 0 0 321118 105939 0 3 35085
32465 8988658 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 4526886
btime 1201376745
processes 7197
procs_running 2
procs_blocked 0

The cpu record refers to all processor cores, while cpuN refers to
each CPU or CPU core individually.

Unless things are more complicated than they appear, to get the busy
time fraction:

def cpuusage():
"""-> dict of cpuid : (usertime, nicetime, systemtime, idletime)
cpuid "cpu" means the total for all CPUs.
cpuid "cpuN" means the value for CPU N.
"""
wanted_records = [line for line in open('/proc/stat') if
line.startswith('cpu')]
result = {}
for cpuline in wanted_records:
fields = cpuline.split()[:5]
data = map(int, fields[1:])
result[fields[0]] = tuple(data)
return result

The manpage points out that the contents of /proc/stat can vary by
architecture, though I would guess at least the "cpu" line would be
available on all.


loadavg
===
You can get the load average and the other information in /proc/
loadavg with:

def loadavg():
   """-> 5-tuple containing the following numbers in order:
- 1-minute load average (float)
- 5-minute load average (float)
- 15-minute load average (float)
- Number of threads/processes currently executing (<= number of
CPUs) (int)
- Number of threads/processes that exist on the system (int)
- The PID of the most recently-created process on the system (int)
   """
   loadavgstr = open('/proc/loadavg', 'r').readline().strip()
   data = loadavgstr.split()
   avg1, avg5, avg15 = map(float, data[:3])
   threads_and_procs_running, threads_and_procs_total = map(int,
data[3].split('/'))
   most_recent_pid = int(data[4])
   return avg1, avg5, avg15, threads_and_procs_running,
threads_and_procs_total, most_recent_pid

Hope this solves the problem.

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


file write question

2008-01-26 Thread Robb Lane (SL name)
I have written a script which:
- opens a file
- does what it needs to do, periodically writing to the file... for a
few hours
- then closes the file when it's done
So my question is:
Would it be better to 'open' and 'close' my file on each write cycle?
e.g.
def writeStuff(content):
 myFile = open('aFile.txt', 'a+')
 myFile.write(content)
 myFile.close()

... or just leave it till it's done?
I don't need to use the file contents until the script is done
(although it would be nice... just to check it while it's working), so
just curious what people think is the better method.
- rd
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do design patterns still apply with Python?

2008-01-26 Thread Terry Reedy
To answer the OP's question: GOF design patterns that solve problems due to 
static typing (and there are some) are not needed with Python.  Others do 
apply and can be useful.  There have been various mentions in c.l.p over 
the years. 



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


Re: raw_input(), STRANGE behaviour

2008-01-26 Thread Terry Reedy
I believe a workaround to the bug of raw_input sending the prompt to stderr 
is
print 'prompt:',
a = raw_input()

Not nice, but possibly better that waiting for a corrected binary.
 



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


Re: raw_input(), STRANGE behaviour

2008-01-26 Thread Hrvoje Niksic
Dox33 <[EMAIL PROTECTED]> writes:

> Thanks for your reply.  Since I momentarily do not have the ability
> to build a new python executable, I would like to ask for your help
> in this case.  Are you able to supply me with a corrected version?

You can simply choose not to use raw_input, and use sys.stdin.readline
instead.  Or define your own corrected raw_input:

def my_raw_input(msg):
print msg,
return raw_input()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: file write question

2008-01-26 Thread Hrvoje Niksic
"Robb Lane (SL name)" <[EMAIL PROTECTED]> writes:

> ... or just leave it till it's done?
> I don't need to use the file contents until the script is done
> (although it would be nice... just to check it while it's working),

Use flush() to force the contents out at opportune times without
closing and reopening the file object.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Operator overloading

2008-01-26 Thread Terry Reedy

| > > 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.

One cannot change builtin types.  One can subclass most of them and 
override most if not all the special methods.

import math as m
class trigint(int):
def __pos__(self):
return m.cos(m.pi*self/180.0)

print +trigint(45)
>>>
0.707106781187

Of course, for this case,
def cosi(degrees): return m.pi*degrees/180.0
would probably be more sensible.

There is and is no prospect of being able to add operators.

Terry Jan Reedy



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


how to make format operator % work with unicode as expected

2008-01-26 Thread Peter Pei
I am using things like "%-20s%-60s%-10s" in tkinter listbox to make it look 
like a table, with mono sized font like lucie system. But this does not work 
with data contains "Les misérables", because it is unicode, and one byte is 
not neccessary one character. Now how can I resolve this issue?

My issue is "how to make format operator % work with unicode as expected", 
and has nothing to do with tkinter. If I want to use a table widget or 
something, I can. But that's not the question. 

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


Re: how to make format operator % work with unicode as expected

2008-01-26 Thread Peter Pei
I probably should mention that what I want is to make all parts of the
string aligned, and look like table. I am not looking for other ways to make
it table-alike, but only interested in making % work with unicode -counting
characters not bytes... 

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


Re: how to make format operator % work with unicode as expected

2008-01-26 Thread Steven D'Aprano
On Sun, 27 Jan 2008 04:06:45 +, Peter Pei wrote:

> I probably should mention that what I want is to make all parts of the
> string aligned, and look like table. I am not looking for other ways to
> make it table-alike, but only interested in making % work with unicode
> -counting characters not bytes...

% already works with unicode. Just give it unicode arguments:


>>> print u"x y z %s 1 2 3" % u"Les misérables"
x y z Les misérables 1 2 3


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

Re: how to make format operator % work with unicode as expected

2008-01-26 Thread Peter Pei
You didn't understand my question, but thanks any way.

Yes, it is true that %s already support unicode, and I did not contradict 
that. But it counts the number of bytes instead of characters, and makes 
things like %-20s out of alignment. If you don't understand my assertion, 
please don't argue back and I am only interested in answers from those who 
are qualified.
==

"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Sun, 27 Jan 2008 04:06:45 +, Peter Pei wrote:
>
>> I probably should mention that what I want is to make all parts of the
>> string aligned, and look like table. I am not looking for other ways to
>> make it table-alike, but only interested in making % work with unicode
>> -counting characters not bytes...
>
> % already works with unicode. Just give it unicode arguments:
>
>
 print u"x y z %s 1 2 3" % u"Les misérables"
> x y z Les misérables 1 2 3
>
>
> -- 
> Steven 

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

Re: how to make format operator % work with unicode as expected

2008-01-26 Thread Peter Pei
I just sorted posts by from, and figured out that you are kind of PSF guy... 
However that does not make you qualified, I care whether you are capable not 
whether you have the time to spend for PSF.

Adios!
==
"Peter Pei" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> You didn't understand my question, but thanks any way.
>
> Yes, it is true that %s already support unicode, and I did not contradict 
> that. But it counts the number of bytes instead of characters, and makes 
> things like %-20s out of alignment. If you don't understand my assertion, 
> please don't argue back and I am only interested in answers from those who 
> are qualified.
> ==
>
> "Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> On Sun, 27 Jan 2008 04:06:45 +, Peter Pei wrote:
>>
>>> I probably should mention that what I want is to make all parts of the
>>> string aligned, and look like table. I am not looking for other ways to
>>> make it table-alike, but only interested in making % work with unicode
>>> -counting characters not bytes...
>>
>> % already works with unicode. Just give it unicode arguments:
>>
>>
> print u"x y z %s 1 2 3" % u"Les misérables"
>> x y z Les misérables 1 2 3
>>
>>
>> -- 
>> Steven
> 

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

Re: how to make format operator % work with unicode as expected

2008-01-26 Thread Peter Pei
For sure I can calculate the number of characters and do the padding myself, 
but what's the point, and i surely hope that python does it for me.

"Peter Pei" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I am using things like "%-20s%-60s%-10s" in tkinter listbox to make it look 
>like a table, with mono sized font like lucie system. But this does not 
>work with data contains "Les misérables", because it is unicode, and one 
>byte is not neccessary one character. Now how can I resolve this issue?
>
> My issue is "how to make format operator % work with unicode as expected", 
> and has nothing to do with tkinter. If I want to use a table widget or 
> something, I can. But that's not the question. 

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


Re: how to make format operator % work with unicode as expected

2008-01-26 Thread I V
On Sun, 27 Jan 2008 05:32:40 +, Peter Pei wrote:
> Yes, it is true that %s already support unicode, and I did not
> contradict that. But it counts the number of bytes instead of
> characters, and makes things like %-20s out of alignment. If you don't
> understand my assertion, please don't argue back and I am only
> interested in answers from those who are qualified.

What version of python are you using? On python 2.4 and 2.5 on linux, 
%-20s counts the characters, not the bytes, or, I think it does. when I 
run:

>>> print u'%-20s|\n%-20s|' % (u'foo bar', u'foo bár')

the output is:

foo bar |
foo bár |

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

Re: paging in python shell

2008-01-26 Thread Gabriel Genellina
[reformatting to bottom-post]

En Sat, 26 Jan 2008 08:26:37 -0200, Alex K <[EMAIL PROTECTED]>  
escribi�:
> On 26/01/2008, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>> --- 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 )
> That seems interesting but it's not quite what I want to do. To take
> an example I would like to be able to do something similar to the
> mysql shell when its pager is set to less. Displayhook is called
> whenever an expression is being evaluated. I'd like to call 'less' on
> the ouput of a statement.

The only statement with any output that I can think of is "print". You  
could define your own function and use it instead of print:

def p(x):
   pydoc.pipepager(str(text), 'less')

and use p(something) instead of print something. (Else I totally  
misundertood your problem)

-- 
Gabriel Genellina

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

Klik2 Project, Python apps on linux

2008-01-26 Thread Jason Taylor
Hi

We've been working on klik2, http://code.google.com/p/klikclient/, which
implements OSX like application files on linux (with applications working on
all distros), In which every user desktop application is 1 file

We've run into a bit of a problem with python apps,  so while we can run a
complicated application like openoffice.org on ubuntu, fedora and suse from
a single file we cant run any python applications such as

jokosher
gnome-specimen
angrydd
gausssum
pathological
quodlibet
webboard
istanbul
exaile
ccsm
bittornado
pessulus
labyrinth
wammu
accerciser


We'd like to fix this in a clean way with out resorting to nasty hacks
involving $PYTHON_PATH.

If any one has any suggestions please email me or drop by #klik on freenode

Issue http://code.google.com/p/klikclient/issues/detail?id=144

Cheers

Jason Taylor

-- 
"Why isn't my life like a situation comedy? Why don't I have a bunch of
friends with nothing better to do but drop by and instigate wacky
adventures? Why aren't my conversations peppered with spontaneous
witticisms? Why don't my friends demonstrate heartfelt concern for my well
being when I have problems? ...I gotta get my life some writers." - Calven
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: LEL

2008-01-26 Thread Paddy
On Jan 26, 10:14 pm, [EMAIL PROTECTED] wrote:
> The LEL mini language (there used for JRuby) seems nice, it may be
> added to 
> Tkinter:http://ihate.rubyforge.org/profligacy/lel.htmlhttp://ihate.rubyforge.org/profligacy/sample.html
>
> Bye,
> bearophile

Seems a good idea - I love the size of the grammar!

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


Using a dict as if it were a module namespace

2008-01-26 Thread Steven D'Aprano
I have a problem which I think could be solved by using a dict as a 
namespace, in a similar way that exec and eval do.

When using the timeit module, it is very inconvenient to have to define 
functions as strings. A good alternative is to create the function as 
normal, and import it:

def myfunc(x, y):
return x+y

timeit.Timer("myfunc(59, 60)", "from __main__ import myfunc").timeit()


Not only is this an easy idiom to follow, but myfunc can live in another 
module: just replace __main__ with the module name.

Now, I'm trying to build a suite of tests to use with timeit. I have a 
bunch of tests which I've created as dicts:

test_suite= [dict(x=59, y=60), dict(x=-1, y=-2)]

What I *think* I want to do is use the from ... import idiom to grab 
arguments from the dicts as if they were modules, but this doesn't work:

expr = "myfunc(x, y)"
for test in test_suite:
setup = "from __main__ import myfunc; from test import x, y"
t = timeit.Timer(expr, setup).timeit()


Even if the Timer could see test, it is not a module and you can't import 
from it. Naturally.


Alternatives that I have found:

(1) Import the test and grab the values needed from it:

setup = """from __main__ import myfunc, test
x, y = test['x'], test['y']"""


I don't like this one. It doesn't seem very elegant to me, and it gets 
unwieldy as the complexity increases. Every item I need from test has to 
be named twice, violating the principle Don't Repeat Yourself. If the 
tests change, the setup string has to be explicitly changed also. 


(2) Mess with the global namespace:

globals().update(t)
setup = "from __main__ import myfunc"

I don't like this one. It looks hackish, and I worry about conflicts and 
side-effects. If it works (and I haven't tested it) it relies on an 
implementation detail of timeit.Timer.__init__, namely the line
"exec code in globals(), ns". Worst of all, it pollutes or even mangles 
the global namespace of the calling code, not the code being tested.


(3) Explicitly pass a namespace dict to the Timer class, possibly even 
getting rid of setup altogether:

test['myfunc'] = myfunc
t = timeit.Timer(expr, '', ns=test).timeit()

This would be the most elegant solution, but at this time it is 
completely hypothetical. Timer does not have that functionality.


(4) Dump the test data straight into the setup string:

setup = "from __main__ import myfunc; x = %(x)s; y = %(y)s" % t

Again, unwieldy and against DRY. The additional disadvantage is that 
there are many types of test data that can't be converted to and from 
strings like that.


What do others think? Have I missed something? What other alternatives 
are there?



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


Re: how to make format operator % work with unicode as expected

2008-01-26 Thread Steven D'Aprano
On Sun, 27 Jan 2008 05:32:40 +, Peter Pei wrote:

> You didn't understand my question, but thanks any way.
> 
> Yes, it is true that %s already support unicode, and I did not
> contradict that. But it counts the number of bytes instead of
> characters, and makes things like %-20s out of alignment. If you don't
> understand my assertion, please don't argue back and I am only
> interested in answers from those who are qualified.

I understand your assertion. I think it is nonsense.

>>> def test():
... print "12345678901234567890 +"
... print "%-20s +" % "Plain ASCII"
... print u"%-20s +" % u"Les misérables-\320\321\322"
...
>>> test()
12345678901234567890 +
Plain ASCII  +
Les misérables-ÐÑÒ   +




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