Re: Colored text

2007-08-12 Thread ianaré
On Aug 13, 1:50 am, Rohan <[EMAIL PROTECTED]> wrote:
> On Aug 12, 10:01 pm, ianaré <[EMAIL PROTECTED]> wrote:
>
> > On Aug 12, 10:05 pm, Rohan <[EMAIL PROTECTED]> wrote:
>
> > > Hello,
> > > Can some one tell me how do I get colored text. Say when I want to
> > > write something in a text file , how do I get it colored.
>
> > Plain text files don't have color. You could output in html ...
>
> Oh ok what about a csv file, I know its also a text file but I want
> the color to be say blue in an excel sheet.

CSV is also pretty much plain text. No support for formatting.

You will need to write xls files. Personaly, I avoid proprietary file
formats like the plague, but this may be what you're looking for:

http://www.answermysearches.com/index.php/generate-an-excel-formatted-file-right-in-python/122/

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

Re: decorators - more than just syntactic sugar

2007-08-12 Thread Kay Schluehr
On Aug 11, 8:30 pm, Helmut Jarausch <[EMAIL PROTECTED]> wrote:

> How can I find out the predefined decorators?

I dare to say that's not easy. Since decorators are just(?)
syntactical sugar they don't obtain a particular semantics expressed
by distinctive declarative elements. Unlike generators which can be
identified looking for a yield expression a decorator can be
identified syntactically just when it is used. However this might be
sufficient, depending on your intention?

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


Re: decorators - more than just syntactic sugar

2007-08-12 Thread Michele Simionato
On Aug 11, 8:30 pm, Helmut Jarausch <[EMAIL PROTECTED]> wrote:
> Hi,
>
> are decorators more than just syntactic sugar in python 2.x and what
> about python 3k ?

Well, I argued may times that syntactic sugar is important (all Turing
complete languages differs by syntactic sugar only) and having or not
having
a given syntactic sugar makes a difference between writing and not
writing
a given program. Having decorators in core Python makes us think
differently.
Have a look at David Mertz article

http://www.ibm.com/developerworks/linux/library/l-cpdecor.html

   Michele Simionato

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


Re: is there anybody using __del__ correctly??

2007-08-12 Thread Michele Simionato
On Aug 12, 9:14 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
> Michele Simionato wrote:
> > On Aug 10, 7:09 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
> >> There were also a few recipes posted during this discussion that wrap
> >> weakrefs up a bit nicer so it's easier to use them in place of __del__:
>
> >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/519635
>
> > I knew about your recipe and I thought it was clever, *very*
> > clever. I have been thinking about it a bit more today and
> > here is an alternative, which does not require metaclasses,
> > does not require descriptors, and does not require the user to
> > declare the attributes she will use in the __finalize__ method.
> > Warning: it is no more tested than the test case in your recipe:
>
> > import weakref
>
> > _get = object.__getattribute__
> > _set = object.__setattr__
> > _del = object.__delattr__
>
> > def getinnerobj(self):
> > return _get(self, '*innerobj*')
>
> > class Impostor(object):
> > "It tries very hard to impersonate the inner object"
> > def __init__(self, obj):
> > _set(self, '*innerobj*', obj)
> > def __getattribute__(self, name):
> > return getattr(getinnerobj(self), name)
> > def __setattr__(self, name, value):
> > _set(getinnerobj(self), name, value)
> > def __delattr__(self, name):
> > _del(getinnerobj(self), name)
>
> > _refset = set()
>
> > class Finalized(object):
> > def __new__(cls, *args, **kw):
> > self = super(Finalized, cls).__new__(cls, *args, **kw)
> > self.__init__(*args, **kw)
> > def finalize(ref, refset=_refset):
> > refset.remove(ref)
> > cls.__finalize__(self)
> > fake = Impostor(self)
> > _refset.add(weakref.ref(fake, finalize))
> > return fake
> > def __finalize__(self):
> > pass
>
> The problem here is that __getattribute__ doesn't work for things like
> __getitem__.

Yeah, it is the old issue of special methods being special, i.e.
len(x)
is not exactly x.__len__(). I am not sure if this can be changed in
Py3k,
it is certainly annoying in some (rare) circumstances, as
here.
One workaround is to add all special methods to the Impostor
class:

SPECIALMETHODS = ['__%s__' % name for name in
'''
abs add and call concat contains delitem delslice div eq floordiv ge
getitem
getslice gt iadd iand iconcat idiv ifloordiv ilshift imod imul index
inv invert
ior ipow irepeat irshift isub iter itruediv ixor le len lshift lt mod
mul ne neg
not or pos pow repeat repr rshift setitem setslice str sub truediv
xor
'''.split()]

def add_special_method(cls,
name): def
meth(self,
*args):
return getattr(self, name)
(*args)
meth.__name__ =
name
setattr(cls, name,
meth)
for name in
SPECIALMETHODS:
add_special_method(Impostor,
name)

In this way the Impostor can emulate even the special methods. Here is
an
example:

>>> class C(object):
...
pass
...
>>> c=Impostor(C())
>>> print c
<__main__.C object at
0x102a390>

Notice that the impostor is calling the __str__ method of C, so it
really
looks like a C object.
Moreover

>>> c.__class__


and

>>> isinstance(c, C)
True

so the Impostor is doing a damn pretty good job of imposture for C
objects.
Of course it does what it can, and it cannot impersonate C objects
completely:
>>> type(c)


so code using checks like ``type(c) is C`` would break and the
approach here
cannot be considered more than a hack. Still a cool hack, I would
say ;)

Michele Simionato

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


Re: Colored text

2007-08-12 Thread Michael Bentley

On Aug 12, 2007, at 7:05 PM, Rohan wrote:
> Can some one tell me how do I get colored text. Say when I want to
> write something in a text file , how do I get it colored.

You can use ANSI escape codes -- http://en.wikipedia.org/wiki/ 
ANSI_escape_code:

colorCodes = [
 "\033[0mAll attributes off\033[0m",
 "\033[1mBold\033[0m",
 "\033[4mUnderline\033[0m",
 "\033[5mBlink\033[0m",
 "\033[8mHide\033[0m",
 "\033[30mBlack\033[0m",
 "\033[31mRed\033[0m",
 "\033[32mGreen\033[0m",
 "\033[33mYellow\033[0m",
 "\033[34mBlue\033[0m",
 "\033[35mMagenta\033[0m",
 "\033[36mCyan\033[0m",
 "\033[37mWhite\033[0m",
 "\033[40m\033[37mBlack Background\033[0m",
 "\033[41mRed Background\033[0m",
 "\033[42mGreen Background\033[0m",
 "\033[43mYellow Background\033[0m",
 "\033[44mBlue Background\033[0m",
 "\033[45mMagenta Background\033[0m",
 "\033[46mCyan Background\033[0m",
 "\033[47mWhite Background\033[0m"
]

for i in colorCodes:
 print i

hth,
Michael
---
"I would rather use Java than Perl. And I'd rather be eaten by a  
crocodile than use Java." — Trouser


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


Re: Colored text

2007-08-12 Thread Rohan
On Aug 12, 10:01 pm, ianaré <[EMAIL PROTECTED]> wrote:
> On Aug 12, 10:05 pm, Rohan <[EMAIL PROTECTED]> wrote:
>
> > Hello,
> > Can some one tell me how do I get colored text. Say when I want to
> > write something in a text file , how do I get it colored.
>
> Plain text files don't have color. You could output in html ...

Oh ok what about a csv file, I know its also a text file but I want
the color to be say blue in an excel sheet.

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

Re: Pausing and Unpausing Threads

2007-08-12 Thread Gabriel Genellina
En Sun, 12 Aug 2007 21:45:47 -0300, Aaron J. M. <[EMAIL PROTECTED]>  
escribi�:

> Uhg, I thought of something I didn't consider before: how to cleanly
> end the Server/DirectedControl(l)er process.

Use the same Queue; put a special kind of Action, or just a None object,  
to tell the thread that there are no more things to process.
 From the main thread, you can join() the others, waiting for them to  
finish.

-- 
Gabriel Genellina

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

Re: Complexity of methods etc

2007-08-12 Thread Paddy
On Aug 13, 1:04 am, "Nathan Harmston" <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> I was wondering if anyone knew of any resources, where I might be able
> to find information about the complexity of certain python functions
> or little tips on how to reduce complexity. I mean like the "".join(),
> kind of thing?
>
> I want to see if there are any improvements I can add to my coding in
> order to reduce  time/space usage/
>
> Many Thanks in advance
>
> Nathan

There is this collection:
http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
Although I don't think algorithm complexity is given, it is telling
you how to select the most efficient way of doing things in a number
of examples.

- Paddy.

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


Re: Querying Graphics Card Name

2007-08-12 Thread Benjamin Goldenberg
On Aug 12, 2:18 pm, Jorgen Grahn <[EMAIL PROTECTED]>
wrote:
> On Thu, 09 Aug 2007 21:58:54 -, Benjamin Goldenberg <[EMAIL PROTECTED]> 
> wrote:
> > On Aug 9, 3:26 pm, Bjoern Schliessmann  > [EMAIL PROTECTED]> wrote:
> >> Benjamin Goldenberg wrote:
> >> > I would like to find out the name of the graphics card of the
> >> > machine my program is running on. I have looked into the pyopengl
> >> > module, and using them to query the card, but it seems like there
> >> > ought to be a simpler way to find this out without setting up a
> >> > glcontext. Does anyone have any ideas?
>
> >> You could execute glxinfo and look for the renderer string. If
> >> that's sharp enough for your purpose. Another option is lspci.
>
> > I should have clarified. I would like a cross platform implementation,
> > Windows and *nix. It doesn't seem as if glxinfo is available under
> > Windows, at least not without installing X11 under cygwin. If
> > necessary, I can write the *nix and Windows queries separately.
>
> Yeah, but ...
> - what if there isn't one?
> - what if there are several?
> - what if there *is* one, but your user is sitting by a remote machine,
>   not using the card at all?
>
> Your method will, no matter how you choose, fail sooner or later,
> so you'd better plan for that.
>
> What is your reason to do this, by the way?  Remember what Homer
> Simpson said: if something appears to be hard, it is simply not worth
> doing. And I mean that semi-seriously.

These are for some internal automation scripts for the company I work
for. We do development for specific graphics cards, all of which are
OpenGL 2.0 compatible. In order to automate aspects of our building
and testing systems, we need to know which graphics card the software
is being built on. Hopefully, that makes some sense.

-Benjamin

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


Re: Ligmail bug?

2007-08-12 Thread Gabriel Genellina
En Sun, 12 Aug 2007 22:14:08 -0300, Ed Leafe <[EMAIL PROTECTED]> escribi�:

> On Aug 12, 2007, at 7:06 AM, Steve Holden wrote:
>
>> [Please reply via the list when a response is made via the list.
>
>   The default behavior for this list should be to reply to the list,
> as you have pointed out. Yet for some unfathomable reason, the
> keepers of the list have set it up to default to reply to the
> original sender. This is nothing short of stupid, and I cast my vote
> (if I even have one) for changing this default to a more intelligent
> one, if for no other reason than to not have to constantly read
> comments like this chiding someone for acting in a predictable fashion.

Please read this  
http://woozle.org/~neale/papers/reply-to-still-harmful.html>

-- 
Gabriel Genellina

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

wx.ListBox drag and drop

2007-08-12 Thread ianaré
Hey all,

I see plenty of drag and drop examples but they are all for
wx.ListCtrl. Anyone know of examples or tutorials for wx.ListBox?
Specifically, I would like to be able to drag a selection from one
ListBox to another.

Thanks in advance,

- ianaré

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


Re: Colored text

2007-08-12 Thread ianaré
On Aug 12, 10:05 pm, Rohan <[EMAIL PROTECTED]> wrote:
> Hello,
> Can some one tell me how do I get colored text. Say when I want to
> write something in a text file , how do I get it colored.

Plain text files don't have color. You could output in html ...

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


Re: python + XUL

2007-08-12 Thread Madhu Alagu
On Aug 13, 3:54 am, Luis M. González <[EMAIL PROTECTED]> wrote:
> On Aug 12, 3:21 am, Stefan Behnel <[EMAIL PROTECTED]> wrote:
>
> > Madhu Alagu wrote:
> > > Hi
>
> > > Python + XUL Success Stories
>
> > > Thanks
>
> > > Madhu Alagu
>
> > Any chance you forgot to ask a question?
>
> > Stefan
>
> My telepatic powers tell me that this means:
> "I don't really feel like googling, so just give me the info, ok?"



I am very sorry for the short word... Has anyone had any success in
getting XUL to work with python?

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

Re: Binary, Hex, and Decimal string conversions

2007-08-12 Thread Dick Moores
At 07:04 PM 8/12/2007, Michael Bentley wrote:

>On Aug 12, 2007, at 6:28 PM, Dick Moores wrote:
>
>>n = 12
>>base = 36
>>print to_base(n, base)
>>==
>>This seems to work fine for n >= base, but not for n < base. For 
>>example, the code shown returns "c". Is my indentation wrong, or 
>>the code? It seems to me that the code should work for the general 
>>case, not just for n >= base.
>
>Isn't 'c' the correct answer?

Yes, of course. Stupid of me.

Dick


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


Re: Error calling module

2007-08-12 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, fartknuckle
wrote:

> When I try to call gtk like so:
> 
> 
> import gtk
> 
> I get the error:
> 
> ImportError: No module named gtk
> 
> 
> I installed a new Python and a new pygtk.
> Is the gtk module not a part of pygtk???
> 
> I have PYTHONPATH=/usr/local/lib/python2.5/site-packages
> set. So what am I doing wrong?

First question: where is the gtk module located?

Second question: start up python interactively, type

import sys
sys.path

Does the resulting list include the directory that is the answer to the
first question?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question: how to transfer objects between server and client?

2007-08-12 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>,
OpenPavilion wrote:

> just found out, that if I use "pickle.dumps(object)" (on client side)
> and "pickle.loads(object)" (on server side) before and after sending,
> I have access to the object.

That's assuming that the client and server can trust each other. If you
can't be sure of that, then this sounds like it could be a security hole.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A dumb question about a class

2007-08-12 Thread Steven Bethard
Steven Bethard wrote:
> Dustan wrote:
>> On Aug 12, 7:35 pm, Dustan <[EMAIL PROTECTED]> wrote:
>>> On Aug 12, 5:09 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
>>>
  def iter_primes():
  # an iterator of all numbers between 2 and +infinity
  numbers = itertools.count(2)
  # generate primes forever
  while True:
  # get the first number from the iterator (always a prime)
  prime = numbers.next()
  yield prime
  # remove all numbers from the (infinite) iterator that are
  # divisible by the prime we just generated
  numbers = itertools.ifilter(prime.__rmod__, numbers)
>>> This is kind of OT (from the thread), but in this iter_primes
>>> function, numbers is becoming an ifilter of an ifilter of an ifilter
>>> of an ifilter of an ifilter of an ifilter of... Is that really at all
>>> efficient for larger numbers (millions or billions, or even bigger)?
>>
>> To word my question better:
>>
>> How does this algorithm compare and contrast to maintaining a
>> dictionary or set and iterating through those structures to find out
>> if a number is divisible? All of those algorithms I've described are
>> O(n^2), if I'm not mistaken, but as far as memory-efficiency and the
>> likes, how do they compare/contrast?
> 
> I don't have the answer off hand, but if anyone wants to report some 
> timeit results or memory consumption here, I'd be interested.

Ok, I played around with it myself.  Here are the two implementations I 
tested::

 def iter_primes_recursive():
 # an iterator of all numbers between 2 and +infinity
 numbers = itertools.count(2)

 # generate primes forever
 while True:

 # get the first number from the iterator (always a prime)
 prime = numbers.next()
 yield prime

 # remove all numbers from the (infinite) iterator that are
 # divisible by the prime we just generated
 numbers = itertools.ifilter(prime.__rmod__, numbers)


 def iter_primes_mapping():

 # mapping from composite number to first prime that revealed
 # that number as a composite
 composite_to_factor_map = {}

 # generate primes forever
 for i in itertools.count(2):

 # find a factor of the number
 factor = composite_to_factor_map.pop(i, None)

 # if no factor is found, the number is prime
 if factor is None:
 yield i
 composite_to_factor_map[i * i] = i

 # add the factor to the number until we find a new
 # composite number
 else:
 composite = i + factor
 while composite in composite_to_factor_map:
 composite += factor
 composite_to_factor_map[composite] = factor

And here are some timeit results::

$ python -m timeit -s "from script import iter_primes_recursive as 
iter_primes" "for i in iter_primes():" "if i >= 100:"
"break"
1 loops, best of 3: 102 usec per loop

$ python -m timeit -s "from script import iter_primes_mapping as 
iter_primes" "for i in iter_primes():" "if i >= 100:"
"break"
1 loops, best of 3: 75.2 usec per loop

$ python -m timeit -s "from script import iter_primes_recursive as 
iter_primes" "for i in iter_primes():" "if i >= 1:"
"break"
10 loops, best of 3: 111 msec per loop

$ python -m timeit -s "from script import iter_primes_mapping as 
iter_primes" "for i in iter_primes():" "if i >= 1:"
"break"
100 loops, best of 3: 8.4 msec per loop

So, somewhat unsurprisingly, the non-recursive version is much faster 
for larger primes. (Someone should check that both my implementations 
are right -- I only did a couple of spot checks on the output.)

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


Python script for mobile platforms -- suggested?

2007-08-12 Thread Robert Dailey
Hi,

I'm currently developing a game for a cell phone. The game has a GUI system
that's currently using XML to define the individual menus. Basically this
means that for every single menu the user goes to, it loads and parses an
XML file. Would using Python Script instead of XML be a reasonable
replacement, or would it be even slower? I've read various articles online
but I'm still curious to hear what everyone has to say here.

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

Re: A dumb question about a class

2007-08-12 Thread Steven Bethard
Dick Moores wrote:
> At 03:35 PM 8/12/2007, Steven Bethard wrote:
>> Note that if you just want to iterate over all the primes, there's no
>> need for the class at all.  Simply write::
>>
>>  for prime in iter_primes():
> 
> Even if I want to test only 1 integer, or want the list of primes in a 
> certain interval, I don't need the class at all

Yep.  That was the basis of my original feeling that the recipe was 
kinda overkill.

> Thanks for your help. I didn't learn much about classes, but appreciated 
> your iter_primes() a lot!

You're welcome, though I can't actually take credit for iter_primes(). 
The original version is due to Tim Hochberg, in a comment on this recipe:

 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117119

FWIW, he says that he "managed to generate all primes up to 909,691 
before it bombed the Python interpreter mysteriously, but it takes a while!"

I'm not particularly married to that prime generator. For your purposes, 
any generator version of iter_primes() is probably more useful than the 
class you were looking at. You can see some other implementations of 
prime generators on that same recipe page.

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


Re: Fatest standard way to sum bytes (and their squares)?

2007-08-12 Thread Erik Max Francis
Peter Otten wrote:

> from itertools import imap
> 
> def summit_array(data=data, lookup=lookup):
> a = array.array("B")
> a.fromstring(data)
> return sum(a), sum(imap(lookup.__getitem__, a))
> 
> $ python -m timeit -s'from summit import summit_array as summit' 'summit()'
> 100 loops, best of 3: 9.15 msec per loop
> 
> I think I'll stop here...

Yes, this was the fastest approach of all the alternatives I tried. 
Plugging the algorithm in the tool, it makes it about twice as fast as 
the generator-sum method I was using before, and about _five_ time as 
fast as a naive for loop.  The use of an array is particularly clever; I 
never would have thought of that.

Thanks to everyone for their ideas.  Amusingly I posted it late last 
night (well, this morning I guess), not expecting much, at least until 
the next day, but got a factor of two speedup within half an hour!

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   It is morale that wins the victory.
-- Gen. George C. Marshall
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fatest standard way to sum bytes (and their squares)?

2007-08-12 Thread Erik Max Francis
Duncan Booth wrote:

> I haven't timed it, but at the very least I'd avoid going through all the 
> data twice:
> 
> count = {}
> for i in range(256):
>   count[chr(i)] = 0
> for x in data:
>   count[x] += 1
> 
> ordinalSum = sum(ord(c)*count[c] for c in count)
> ordinalSumSquared = sum(ord(c)**2 * count[c] for c in count)

This approach is definitely faster than using a generator in my tests, 
and was second fastest overall.  I'm actually a bit surprised that it's 
as fast as it is; it never would have occurred to me to try it this way.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   It is morale that wins the victory.
-- Gen. George C. Marshall
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A dumb question about a class

2007-08-12 Thread Steven Bethard
Dustan wrote:
> On Aug 12, 7:35 pm, Dustan <[EMAIL PROTECTED]> wrote:
>> On Aug 12, 5:09 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
>>
>>>  def iter_primes():
>>>  # an iterator of all numbers between 2 and +infinity
>>>  numbers = itertools.count(2)
>>>  # generate primes forever
>>>  while True:
>>>  # get the first number from the iterator (always a prime)
>>>  prime = numbers.next()
>>>  yield prime
>>>  # remove all numbers from the (infinite) iterator that are
>>>  # divisible by the prime we just generated
>>>  numbers = itertools.ifilter(prime.__rmod__, numbers)
>> This is kind of OT (from the thread), but in this iter_primes
>> function, numbers is becoming an ifilter of an ifilter of an ifilter
>> of an ifilter of an ifilter of an ifilter of... Is that really at all
>> efficient for larger numbers (millions or billions, or even bigger)?
> 
> To word my question better:
> 
> How does this algorithm compare and contrast to maintaining a
> dictionary or set and iterating through those structures to find out
> if a number is divisible? All of those algorithms I've described are
> O(n^2), if I'm not mistaken, but as far as memory-efficiency and the
> likes, how do they compare/contrast?

I don't have the answer off hand, but if anyone wants to report some 
timeit results or memory consumption here, I'd be interested.

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


Re: which IDE is highly recommended in Windows OS

2007-08-12 Thread _spitFIRE
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Ge Chunyuan wrote:
> hi Group:
> 
> I am a new comer for Python, I wonder which IDE is recommended in
> Windows OS.
> Can anyone give some suggestion.
> 
> 
> Thanks indeed
> Ge Chunyuan
> 

- - Stani's Python Editor
(http://www.softpedia.com/get/Programming/Coding-languages-Compilers/Stanis-Python-Editor.shtml)
- - Black Adder (http://www.thekompany.com/products/blackadder/)
- - Zeus (http://www.zeusedit.com/python.html)
- - PyScripter (http://mmm-experts.com/Products.aspx?ProductId=4)
- - ActivePython (http://www.activestate.com/)
- - IDLE (http://www.python.org/idle/doc/idle2.html)

and depending on how you define IDEs, you can also decide whether or not to
include, the following
- - emacs
- - vim
- - scite
...

- --
_ _ _]{5pitph!r3}[_ _ _
__
“I'm smart enough to know that I'm dumb.”
  - Richard P Feynman
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGv8DSA0th8WKBUJMRAqGcAJ9hhMp3tyS7XmBZT2+fol/A69j4jwCfXNya
xQTmmDlDF5BAfiWkrSW3TuQ=
=902n
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list

retrieving ATOM/FSS feeds

2007-08-12 Thread _spitFIRE
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

  I'm using feedparser library to parser ATOM/RSS feeds. However, I don't
get the entire post! but only summaries! How do I retrieve the entire feed?
I believe that the parser library should have support for doing that or the
specification should detail how it can be done? Or should I simply get the
feed link and do HTML scraping?


- --
_ _ _]{5pitph!r3}[_ _ _
__
“I'm smart enough to know that I'm dumb.”
  - Richard P Feynman
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGv77mA0th8WKBUJMRAk80AJ9VCIBXIZVhuPtT7bfY4dRrM15H+gCeOVJG
77Zbl8jmWPsp4QjP85Lbwbc=
=Ho+8
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list

which IDE is highly recommended in Windows OS

2007-08-12 Thread Ge Chunyuan
hi Group:

I am a new comer for Python, I wonder which IDE is recommended in
Windows OS.
Can anyone give some suggestion.


Thanks indeed
Ge Chunyuan

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


Colored text

2007-08-12 Thread Rohan
Hello,
Can some one tell me how do I get colored text. Say when I want to
write something in a text file , how do I get it colored.

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


Re: Ligmail bug?

2007-08-12 Thread Steve Holden
Ed Leafe wrote:
> On Aug 12, 2007, at 7:06 AM, Steve Holden wrote:
> 
>> [Please reply via the list when a response is made via the list.  
>> You may
>> now have detached the follow-ups from your original question, but at
>> least if you use the list there's a chance someone else will help  
>> you if
>> I give up or don't have time. Note I have sent this response to the
>> list; you are Cc'd to make sure you pick it up even though it may not
>> appear in the same thread.]
> 
>   I've seen others comment on this, so I'll throw in my 2 cents.
> 
>   The default behavior for this list should be to reply to the list,  
> as you have pointed out. Yet for some unfathomable reason, the  
> keepers of the list have set it up to default to reply to the  
> original sender. This is nothing short of stupid, and I cast my vote  
> (if I even have one) for changing this default to a more intelligent  
> one, if for no other reason than to not have to constantly read  
> comments like this chiding someone for acting in a predictable fashion.
> 
Since I subscribe to the newsgroup rather than to the mailing list I 
don't see that behavior. It's by far the most convenient way to interact 
with c.l.py, and gmane.org makes it easy to do so with Firefox or 
Outlook Express. I've never really understood why Outlook doesn't 
include an NNTP client. I presume Apple Mail (which appears in your 
headers) doesn't act as a newsreader either?

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Binary, Hex, and Decimal string conversions

2007-08-12 Thread Michael Bentley


On Aug 12, 2007, at 6:28 PM, Dick Moores wrote:


n = 12
base = 36
print to_base(n, base)
==
This seems to work fine for n >= base, but not for n < base. For  
example, the code shown returns "c". Is my indentation wrong, or  
the code? It seems to me that the code should work for the general  
case, not just for n >= base.


Isn't 'c' the correct answer?

Regards,
Michael
---
Simplicity is the ultimate sophistication. -Leonardo da Vinci



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

Re: Hex editor - Python beginner's code open to review

2007-08-12 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> On Aug 10, 10:36 pm, CC <[EMAIL PROTECTED]> wrote:
>> Hi:
>>
>> http://web.newsguy.com/crcarl/python/hexl.py
>>
>> This is my first Python program other than tutorial code snippet
>> experimentation.  I chose a hex line editor.  I may do a hex screen
>> editor once this is done, if I feel like playing with the curses module.
>>   Or move straight to wxPython.
>>
>> This is unfinished, and is really just a hex viewer at this point.  It
>> seems like a good point to stop and see what others think.  I would be
>> interested to hear any comments.
>>
>> My command parsing if of course crude, brute-force, and not very
>> scalable.  I am doing some reading on this subject, and will be trying
>> to do a more generalized approach in the next revision.  This is going
>> to be a subject where I need to learn a lot, because I have 2-3
>> embedded applications in C that need varying levels of command parsers,
>> so I will be seeking to improve this skill considerably.
>>
>> Thanks for input.
>>
>> --
>> _
>> Christopher R. Carlen
>> [EMAIL PROTECTED]
>> SuSE 9.1 Linux 2.6.5
> 
> Looks like mostly clean code to me. I don't understand why you declare
> "Offset" globally twice. Wouldn't it make more sense to just stick it
> at the top of the file like your "Hexdigits" variable? I'm also not
> sure if your style follows the style guide...then again, mine probably
> doesn't either. You can check it out here though:
> 
> http://www.python.org/doc/essays/styleguide.html
> 
Nowadays the standard for Python style is PEP 8, which represents an 
update on the above.

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

> Rather than using if/else statements for error checking, you may want
> to consider using try/except:
> 
> http://docs.python.org/tut/node10.html
> 
> That my 2¢!
> 
"if" statements are best if the errors are predictable, "try/except"for 
the less predictable ones, or when it would be difficult to ensure 
correct program flow with "if".

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: LRU cache?

2007-08-12 Thread Paul Rubin
Nikita the Spider <[EMAIL PROTECTED]> writes:
> This one works for me:
> http://www.webfast.com/~skip/python/Cache.py

Thanks, this one keeps track of the actual clock time rather than just
the relative age of cache entries, and has kind of a weird ageing
mechanism, building and sorting an O(n) sized list when the cache gets
95% full, giving amortized O(log n) operations per update.  But the
license is ok and I guess the functionality I need is there.  So I may
use it and/or code something.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: LRU cache?

2007-08-12 Thread Paul Rubin
[EMAIL PROTECTED] (Alex Martelli) writes:
> So what's wrong with Evan Prodromou's lrucache.py module that's in pypi?
> Haven't used it, but can't see anything wrong at a glance.

Thanks, I wasn't aware of that one.  I notice two things about it:
1) it's under a GPL-incompatible license (therefore also incompatible 
   with the PSF license); that's a problem for what I'm doing.

2) it uses heapq to figure out which entry is the oldest.  I guess
that's not too unreasonable and maybe it's necessary.  But unless I'm
missing something it's never necessary to insert new records into the
middle of the list-by-age.  So I think it may be easiest to just keep
a doubly linked list of records with the invariant that they are
ordered by age, keeping track of where both ends are; plus a hash
table to map indices to nodes in the linked list.  On any access that
hits the cache, the found node gets removed and moved to the front of
the list in O(1) operations.  This may be easiest with a circular
list.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Binary, Hex, and Decimal string conversions

2007-08-12 Thread Dick Moores


At 04:20 PM 8/12/2007, Robert Dailey wrote:
Well, I decided to implement my
own way of doing this. I've attached the source. You're all welcome
:)
On 8/12/07, Michael Bentley
<
[EMAIL PROTECTED]> wrote:


Hi Robert,

On Aug 11, 2007, at 3:59 PM, Robert Dailey wrote:

Hi, I was wondering if there is a built in module that supports
conversion in any direction between Binary, Hex, and Decimal strings?
Thanks. 

Shouldn't be too hard to build one.  Here's a little incantation
to convert from base 10 to another base:

import string

def to_base(number, base):

'converts base 10 integer to another base'

number = int(number)

base = int(base)

if base < 2 or base > 36:

raise ValueError, "Base must be between 2 and 36" 

if not number:

return 0

symbols = string.digits + string.lowercase[:26]

answer = []

while number:

number, remainder = divmod(number, base)

answer.append(symbols[remainder]) 

return ''.join(reversed(answer))

I've tried to figure out the correct indentation for this, and came up
with

import string
def to_base(n, base):
    'converts base 10 integer to another base, up thru
base 36'
    n = int(n)
    base = int(base) 
    if base < 2 or base > 36:
    raise ValueError, "Base
must be between 2 and 36" 
    if not n:
    return 0
    symbols = string.digits + string.lowercase[:26] 
    answer = []
    while n:
    n, remainder = divmod(n,
base)
   
answer.append(symbols[remainder]) 
    return ''.join(reversed(answer))
n = 12
base = 36
print to_base(n, base)
==
This seems to work fine for n >= base, but not for n < base. For
example, the code shown returns "c". Is my indentation wrong,
or the code? It seems to me that the code should work for the general
case, not just for n >= base.
Dick Moores


How 'bout you hack a from_base function and email it back to me?
(hint: type 'help(int)' in the python interpreter).

Peace,

Michael

---

Let the wookie win.



Content-Type: text/plain; name="baseconv.py"
Content-Disposition: attachment; filename="baseconv.py"
X-Attachment-Id: f_f5a5roa4

-- 

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



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

Re: Python not freeing memory (?)

2007-08-12 Thread Chris Fonnesbeck
Martin v. Löwis  v.loewis.de> writes:

> If you want others to help you in finding the bug, you
> need to provide more detail, e.g. a specific piece of
> code that reproducibly wastes memory. If you want to
> study how Python objects are allocated and released,
> you need to create a debug build of Python (and all
> extension modules), and start, e.g., with looking at the
> value of sys.gettotalrefcount() over time.

I tried monitoring the refcount at every iteration, but it
does not change; at the same time, the memory use by the 
python process increases. This is why I suspected that 
python was not returning memory.

Below is the method that gets called iteratively; the *_like methods
are statistical likelihoods implemented in f2py. I dont see
anything that is obviously responsible:

def model(self):
# Specification of joint log-posterior

#alpha3 = concatenate(([0], self.alpha3))

# Linear model for surfacing wait time
#self.lamda = exp(self.alpha0 + self.alpha1 * self.wind + self.alpha2 * 
self.air + alpha3[self.series-1])
gamma3 = concatenate(([0], self.gamma3))

# Linear model for at-surface probability
self.theta = invlogit(self.gamma0 + self.gamma1 * self.wind + self.gamma
2 * self.air + gamma3[self.series-1])

x, n, theta = transpose([[z[1], sum(z), t] for z, t in zip(self.downup, 
self.theta) if type(z)!=type(0.0)])

# Binomial likelihood of available animals
self.binomial_like(x, n, theta, name='theta')

# Probability of availability (per survey)
self.pa = 1.0 - (1 - self.theta)**10

beta3 = concatenate(([0], self.beta3))

# Linearmodel for probability of detection
self.pd = invlogit(self.beta0 + self.beta1 * self.wind + self.beta2 * (s
elf.cloud>0) + beta3[self.series-1])

# Binomial likelihood of detection
self.binomial_like(self.obs, self.present, self.pd * self.pa, name='pd')

zeta1 = concatenate(([0], self.zeta1))

# Probability of presence
self.pp = invlogit(self.zeta0 + zeta1[self.series-1] + self.zeta2 * self
.intake + self.zeta3 * (self.discharge - self.intake))

# Binomial likelihood of presence
self.binomial_like(self.present, self.absent + self.present, self.pp, na
me='pp')

# Correct flight counts for detection
self.N_flight = self.count / (self.pd * self.pa)

# Aggregate counts by series
N_series = [self.N_flight[self.series==i+1] for i in range(6)]

# Log-normal likelihood for N
#sum(self.lognormal_like(X, log(N), T) for X, N, T in zip(N_series, self
.N, self.T))
for N, mu in zip(N_series, self.N):
self.poisson_like(N, mu)

Thanks in advance for anything that you might suggest.

cf

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

The Truth

2007-08-12 Thread laelahaellallah5
Explore & discover & be convinced that ISLAM is the truth! ...
Please Visit:
http://www.beconvinced.com

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


Re: Hex editor - Python beginner's code open to review

2007-08-12 Thread kyosohma
On Aug 10, 10:36 pm, CC <[EMAIL PROTECTED]> wrote:
> Hi:
>
> http://web.newsguy.com/crcarl/python/hexl.py
>
> This is my first Python program other than tutorial code snippet
> experimentation.  I chose a hex line editor.  I may do a hex screen
> editor once this is done, if I feel like playing with the curses module.
>   Or move straight to wxPython.
>
> This is unfinished, and is really just a hex viewer at this point.  It
> seems like a good point to stop and see what others think.  I would be
> interested to hear any comments.
>
> My command parsing if of course crude, brute-force, and not very
> scalable.  I am doing some reading on this subject, and will be trying
> to do a more generalized approach in the next revision.  This is going
> to be a subject where I need to learn a lot, because I have 2-3
> embedded applications in C that need varying levels of command parsers,
> so I will be seeking to improve this skill considerably.
>
> Thanks for input.
>
> --
> _
> Christopher R. Carlen
> [EMAIL PROTECTED]
> SuSE 9.1 Linux 2.6.5

Looks like mostly clean code to me. I don't understand why you declare
"Offset" globally twice. Wouldn't it make more sense to just stick it
at the top of the file like your "Hexdigits" variable? I'm also not
sure if your style follows the style guide...then again, mine probably
doesn't either. You can check it out here though:

http://www.python.org/doc/essays/styleguide.html

Rather than using if/else statements for error checking, you may want
to consider using try/except:

http://docs.python.org/tut/node10.html

That my 2¢!

Mike

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

Re: Ligmail bug?

2007-08-12 Thread Ed Leafe
On Aug 12, 2007, at 7:06 AM, Steve Holden wrote:

> [Please reply via the list when a response is made via the list.  
> You may
> now have detached the follow-ups from your original question, but at
> least if you use the list there's a chance someone else will help  
> you if
> I give up or don't have time. Note I have sent this response to the
> list; you are Cc'd to make sure you pick it up even though it may not
> appear in the same thread.]

I've seen others comment on this, so I'll throw in my 2 cents.

The default behavior for this list should be to reply to the list,  
as you have pointed out. Yet for some unfathomable reason, the  
keepers of the list have set it up to default to reply to the  
original sender. This is nothing short of stupid, and I cast my vote  
(if I even have one) for changing this default to a more intelligent  
one, if for no other reason than to not have to constantly read  
comments like this chiding someone for acting in a predictable fashion.

-- Ed Leafe
-- http://leafe.com
-- http://dabodev.com


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


Re: C++ Runtime Library error message - Pythonwin?

2007-08-12 Thread kyosohma
On Aug 11, 5:48 pm, goldtech <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Doing GIS [Geographic Information Systems] scripts.
>
> I was running a batch clip script that worked OK for 126 iterations
>  then I got the following message:
>
> "Microsoft Visual C++ Runtime Library
>
> program: C:\python21\pythonwin\pythonwin.exe
>
> This application has requested the runtime to terminate in an unusual
>  way. Please contact the applications support team for more
> information."
>
> What does this mean? Using XP. Is there a log on my system that gives
> more info?
>
> Thanks

Dunno. You should redirect the stdout/stderr to a log file and stick
some informative print statements in your code. Then when it crashes,
you might be able to track this down.

Mike

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


Re: Complexity of methods etc

2007-08-12 Thread kyosohma
On Aug 12, 7:04 pm, "Nathan Harmston" <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> I was wondering if anyone knew of any resources, where I might be able
> to find information about the complexity of certain python functions
> or little tips on how to reduce complexity. I mean like the "".join(),
> kind of thing?
>
> I want to see if there are any improvements I can add to my coding in
> order to reduce  time/space usage/
>
> Many Thanks in advance
>
> Nathan

Read a book? Lutz's "Programming Python 3rd Ed." will teach you a lot
of tricks. I would also recommend the Python Cookbook book or the
online version here: http://aspn.activestate.com/ASPN/Python/Cookbook/

Mike

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


Re: wxPython - drawing without paint event

2007-08-12 Thread kyosohma
On Aug 12, 4:11 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> 7stud wrote:
> > On Aug 12, 2:20 pm, Bjoern Schliessmann  > [EMAIL PROTECTED]> wrote:
> >> But any suggestions what's
> >> better for a beginner? The (incomplete) tutorial surely not.
>
> > Another GUI toolkit.
>
> Well if all you have to offer is fatuous advice you would be helping
> people more by keeping quiet. wxPython is a more-than-adequate GUI
> toolkit, as has been proved in many successful projects.
>
> What other toolkits have you used, and to what effect, and on what size
> of program? I suspect you are not particularly well-qualified to be
> answering this question in the first place, although as always you are
> entitled to your opinion. It's just that you appear to have an inflated
> value of its worth.
>
> regards
>   Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenweb  http://del.icio.us/steve.holden
> --- Asciimercial --
> Get on the web: Blog, lens and tag the Internet
> Many services currently offer free registration
> --- Thank You for Reading -

If you've followed 7Stud's posts, you'll note that he/she is always
short and mildly to extremely abrupt or rude. Robin Dunn has written
on multiple occasions on the wxPython list about the trouble's they
had organizing the book with the publisher.

While the book does have issues, it is better (in my opinion) than the
only published Tkinter book, although both books are now outdated.
However, I have found that with practice, I can write a fairly complex
GUI front-end with wxPython in only a couple of hours.

As with all programming, if you don't practice, you won't learn.

Mike

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


Re: A dumb question about a class

2007-08-12 Thread Dustan
On Aug 12, 7:35 pm, Dustan <[EMAIL PROTECTED]> wrote:
> On Aug 12, 5:09 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
>
> >  def iter_primes():
> >  # an iterator of all numbers between 2 and +infinity
> >  numbers = itertools.count(2)
>
> >  # generate primes forever
> >  while True:
>
> >  # get the first number from the iterator (always a prime)
> >  prime = numbers.next()
> >  yield prime
>
> >  # remove all numbers from the (infinite) iterator that are
> >  # divisible by the prime we just generated
> >  numbers = itertools.ifilter(prime.__rmod__, numbers)
>
> This is kind of OT (from the thread), but in this iter_primes
> function, numbers is becoming an ifilter of an ifilter of an ifilter
> of an ifilter of an ifilter of an ifilter of... Is that really at all
> efficient for larger numbers (millions or billions, or even bigger)?

To word my question better:

How does this algorithm compare and contrast to maintaining a
dictionary or set and iterating through those structures to find out
if a number is divisible? All of those algorithms I've described are
O(n^2), if I'm not mistaken, but as far as memory-efficiency and the
likes, how do they compare/contrast?

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


Re: who is simpler? try/except/else or try/except

2007-08-12 Thread greg
Peter Otten wrote:
> try:
> 
> except :
>
> else:
> 
> 
> When you move the else suite into the try...except
> 
> try:
> 
>  #
> except :
>

Note that in general the semantics of these are different,
since in the first version the except clause will only catch
exceptions in , whereas in the
second it may catch exceptions in 
as well.

It probably doesn't make a difference in this example, but
there are situations where it can.

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


Re: python + XUL

2007-08-12 Thread Luis M . González
On Aug 12, 3:21 am, Stefan Behnel <[EMAIL PROTECTED]> wrote:
> Madhu Alagu wrote:
> > Hi
>
> > Python + XUL Success Stories
>
> > Thanks
>
> > Madhu Alagu
>
> Any chance you forgot to ask a question?
>
> Stefan



My telepatic powers tell me that this means:
"I don't really feel like googling, so just give me the info, ok?"

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


Re: Pausing and Unpausing Threads

2007-08-12 Thread Aaron J. M.
Uhg, I thought of something I didn't consider before: how to cleanly
end the Server/DirectedControl(l)er process.  Assuming that the Client
only sends Actions to the DirectedController while the
DirectedController is in its turn() method (which I would probably
regulate using some flag in DirectedController) the Client will
eventually need a way to order the Server to stop its processing.
Stopping the Server also has to make the DirectedController break out
of its turn method without letting it execute an Action.  I don't want
to just kill the Server thread because I may want to do serialization
or other kinds of cleanup.

Have people encountered something like this before?

Thank you,

Aaron J. M.

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


Re: Complexity of methods etc

2007-08-12 Thread Dustan
On Aug 12, 7:04 pm, "Nathan Harmston" <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> I was wondering if anyone knew of any resources, where I might be able
> to find information about the complexity of certain python functions
> or little tips on how to reduce complexity. I mean like the "".join(),
> kind of thing?
>
> I want to see if there are any improvements I can add to my coding in
> order to reduce  time/space usage/

It's really difficult to understand what you mean. If you're looking
for a reference on the functions that are available in the library,
you have a long journey ahead of you at http://docs.python.org/ .

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


Re: A dumb question about a class

2007-08-12 Thread Dustan
On Aug 12, 5:09 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
>  def iter_primes():
>  # an iterator of all numbers between 2 and +infinity
>  numbers = itertools.count(2)
>
>  # generate primes forever
>  while True:
>
>  # get the first number from the iterator (always a prime)
>  prime = numbers.next()
>  yield prime
>
>  # remove all numbers from the (infinite) iterator that are
>  # divisible by the prime we just generated
>  numbers = itertools.ifilter(prime.__rmod__, numbers)

This is kind of OT (from the thread), but in this iter_primes
function, numbers is becoming an ifilter of an ifilter of an ifilter
of an ifilter of an ifilter of an ifilter of... Is that really at all
efficient for larger numbers (millions or billions, or even bigger)?

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


Re: Fatest standard way to sum bytes (and their squares)?

2007-08-12 Thread Erik Max Francis
Hrvoje Niksic wrote:

> For ordinalSum, using imap is almost twice as fast:
> 
> $ python -m timeit -s 'data=[chr(x) for x in xrange(256)]' 'sum(ord(x) for x 
> in data)'
> 1 loops, best of 3: 92.4 usec per loop
> $ python -m timeit -s 'data=[chr(x) for x in xrange(256)]; from itertools 
> import imap' 'sum(imap(ord, data))'
> 1 loops, best of 3: 55.4 usec per loop

You're using data which is a list of chars (strings), rather than a 
string itself, which is what the format is in.  The imap optimization 
doesn't appear to work quite as dramatically well for me with strings 
instead of lists, but it certainly is an improvement.

> Of course, that optimization doesn't work for the squared sum; using a
> lambda only pessimizes it.

Right.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Experience is the name everyone gives to their mistakes.
-- Oscar Wilde
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fatest standard way to sum bytes (and their squares)?

2007-08-12 Thread Erik Max Francis
Alexander Schmolck wrote:

> Is this any faster?
> 
>  ordSum, orsSumSq = (lambda c:c.real,c.imag)(sum(complex(ord(x),ord(x)<<1) 
>  for x in data))

That's pretty clever, but I neglected to mention that I need to 
accumulate the sums as ints/longs to avoid losing precision, so 
converting to floating point isn't an optional.  (The sums are 
normalized by the sizes of the files and expanded to 32 bits in order to 
maximize precision.)

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Experience is the name everyone gives to their mistakes.
-- Oscar Wilde
-- 
http://mail.python.org/mailman/listinfo/python-list


Complexity of methods etc

2007-08-12 Thread Nathan Harmston
Hi,

I was wondering if anyone knew of any resources, where I might be able
to find information about the complexity of certain python functions
or little tips on how to reduce complexity. I mean like the "".join(),
kind of thing?

I want to see if there are any improvements I can add to my coding in
order to reduce  time/space usage/

Many Thanks in advance

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


Re: A dumb question about a class

2007-08-12 Thread Dick Moores
At 03:35 PM 8/12/2007, Steven Bethard wrote:
>Note that if you just want to iterate over all the primes, there's no
>need for the class at all.  Simply write::
>
>  for prime in iter_primes():

Even if I want to test only 1 integer, or want the list of primes in 
a certain interval, I don't need the class at all:


import itertools

def iter_primes():
 # an iterator of all numbers between 2 and +infinity
 numbers = itertools.count(2)


 # generate primes forever
 while True:


 # get the first number from the iterator (always a prime)
 prime = numbers.next()
 yield prime


 # remove all numbers from the (infinite) iterator that are
 # divisible by the prime we just generated
 numbers = itertools.ifilter(prime.__rmod__, numbers)

def listPrimes(n,m):
 """
 Returns the list of primes in closed interval [n,m]
 """
 primes = []
 for prime in iter_primes():
 if prime > m:
 return primes
 if n <= prime <= m:
 primes.append(prime)


Thanks for your help. I didn't learn much about classes, but 
appreciated your iter_primes() a lot!

Dick Moores 

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


Apache cgi and multiple versions of python

2007-08-12 Thread Lars Wessman
I am running OS X and have Python 2.3 installed with the system and
have installed 2.5 using the installer available at pythonmac.org. I
am running the system install of Apache 1.3 and I am not using
mod_python.

When Apache 1.3 runs Python cgi scripts, the cgitb output indicates
that the verision of python being used is 2.3. I would like it to use
Python 2.5. Does anyone have any advice on how to get Apache to use
the version of Python I would like it to?

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


Re: Binary, Hex, and Decimal string conversions

2007-08-12 Thread Robert Dailey
Well, I decided to implement my own way of doing this. I've attached the
source. You're all welcome :)

On 8/12/07, Michael Bentley <[EMAIL PROTECTED]> wrote:
>
> Hi Robert,
> On Aug 11, 2007, at 3:59 PM, Robert Dailey wrote:
>
> Hi, I was wondering if there is a built in module that supports conversion
> in any direction between Binary, Hex, and Decimal strings? Thanks.
>
>
> Shouldn't be too hard to build one.  Here's a little incantation to
> convert from base 10 to another base:
>
> import string
>
> def to_base(number, base):
> 'converts base 10 integer to another base'
>
> number = int(number)
> base = int(base)
> if base < 2 or base > 36:
> raise ValueError, "Base must be between 2 and 36"
> if not number:
> return 0
>  symbols = string.digits + string.lowercase[:26]
> answer = []
> while number:
> number, remainder = divmod(number, base)
> answer.append(symbols[remainder])
> return ''.join(reversed(answer))
>
> How 'bout you hack a from_base function and email it back to me? (hint:
> type 'help(int)' in the python interpreter).
>
> Peace,
> Michael
>
> ---
> Let the wookie win.
>
>
>
>

###

def hex2dec( hex ):
return str( int( hex, 16 ) )

###

def hex2bin( hex ):

nibbles =   {
"0":"", "1":"0001", "2":"0010", "3":"0011",
"4":"0100", "5":"0101", "6":"0110", "7":"0111",
"8":"1000", "9":"1001", "A":"1010", "B":"1011",
"C":"1100", "D":"1101", "E":"1110", "F":""
}

# Check for '0x' in front of the string & remove it
if hex[:2] == "0x":
hex = hex[2:]

try:
return str().join([nibbles[c] for c in hex.upper()]).lstrip("0")

except KeyError:
print "ERROR --> Non-hexadecimal character specified."

###

def dec2hex( dec ):
result = hex( int( dec ) )
return result[:2] + result[2:].upper()

###

def dec2bin( dec ):
return hex2bin( dec2hex( dec ) )

###

def bin2dec( bin ):
return str( int( bin, 2 ) )

###

def bin2hex( bin ):
return dec2hex( bin2dec( bin ) )

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

Re: wxPython - drawing without paint event

2007-08-12 Thread Bjoern Schliessmann
7stud wrote:
> On Aug 12, 2:20 pm, Bjoern Schliessmann > But any suggestions what's
>> better for a beginner? The (incomplete) tutorial surely not.

> Another GUI toolkit.

So it seems your dislike is not for the book, but for the toolkit. 

Regards,


Björn

-- 
BOFH excuse #414:

tachyon emissions overloading the system

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


Re: Python not freeing memory (?)

2007-08-12 Thread Robert Kern
Chris wrote:
> I have a Bayesian simulation package that keeps running into memory 
> allocation problems. I have a feeling this has something to do with 
> Python (2.5.1.1) not freeing memory. The program essentially 
> iterates n times, each time proposing new arrays (numpy) of values 
> that are evaluated using statistical likelihoods. All variables in 
> the loop are re-assigned at each iteration, so there should not be 
> a leak. Nevertheless, at approximately the same iteration every 
> time, I run into malloc errors:

There might be a bug in numpy. It's unlikely that the bug is in Python. Let's
bring it over to numpy-discussion. What version of numpy are you using? Can you
give us a complete example that demonstrates the leak?

-- 
Robert Kern

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

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


Re: Python not freeing memory (?)

2007-08-12 Thread Martin v. Löwis
> Is there *any* way of getting around this?

Sure: Determine the bug, and fix it. A prerequisite
is that you have the source code of all extension modules
which you are using, but that seems to be the case.

If you want others to help you in finding the bug, you
need to provide more detail, e.g. a specific piece of
code that reproducibly wastes memory. If you want to
study how Python objects are allocated and released,
you need to create a debug build of Python (and all
extension modules), and start, e.g., with looking at the
value of sys.gettotalrefcount() over time.

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


Re: A dumb question about a class

2007-08-12 Thread Steven Bethard
Dick Moores wrote:
> At 03:09 PM 8/12/2007, Steven Bethard wrote:
> 
>> Here's how I'd write the recipe::
>>
>>  import itertools
>>
>>  def iter_primes():
>>  # an iterator of all numbers between 2 and +infinity
>>  numbers = itertools.count(2)
>>
>>  # generate primes forever
>>  while True:
>>
>>  # get the first number from the iterator (always a prime)
>>  prime = numbers.next()
>>  yield prime
>>
>>  # remove all numbers from the (infinite) iterator that are
>>  # divisible by the prime we just generated
>>  numbers = itertools.ifilter(prime.__rmod__, numbers)
>>
>>
>>  class PrimeList(object):
>>  def __init__(self):
>>  # infinite iterator of primes
>>  self._prime_iter = iter_primes()
>>
>>  # the last prime we've seen
>>  self._last_prime = None
>>
>>  # all primes seen so far
>>  self._prime_set = set()
>>
>>  # add the first prime (so that _last_prime is set)
>>  self._add_prime()
>>
>>  def __contains__(self, n):
>>  # add primes to the list until we exceed n
>>  while n > self._last_prime:
>>  self._add_prime()
>>
>>  # return True if n is one of our primes
>>  return n in self._prime_set
>>
>>  def _add_prime(self):
>>  # take a prime off the iterator and update the prime set
>>  self._last_prime = self._prime_iter.next()
>>  self._prime_set.add(self._last_prime)
> 
> I'm afraid my next question is "How do I run this"?


The same way I showed at the top (which you snipped in your reply)::

 >>> plist = PrimeList()
 >>> 1 in plist
 False
 >>> 2 in plist
 True
 >>> 22 in plist
 False
 >>> 23 in plist
 True
 >>> 782 in plist
 False
 >>> 787 in plist
 True

The first line, ``plist = PrimeList()`` creates a PrimeList object and 
names it ``plist``.  You can then check whether a prime is in that 
PrimeList object much like you might check a normal ``list`` or ``set`` 
object -- using the ``in`` operator as above.

Note that if you just want to iterate over all the primes, there's no 
need for the class at all.  Simply write::

 for prime in iter_primes():
 ...

HTH,

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


Re: A dumb question about a class

2007-08-12 Thread Dick Moores
At 03:09 PM 8/12/2007, Steven Bethard wrote:

>Here's how I'd write the recipe::
>
>  import itertools
>
>  def iter_primes():
>  # an iterator of all numbers between 2 and +infinity
>  numbers = itertools.count(2)
>
>  # generate primes forever
>  while True:
>
>  # get the first number from the iterator (always a prime)
>  prime = numbers.next()
>  yield prime
>
>  # remove all numbers from the (infinite) iterator that are
>  # divisible by the prime we just generated
>  numbers = itertools.ifilter(prime.__rmod__, numbers)
>
>
>  class PrimeList(object):
>  def __init__(self):
>  # infinite iterator of primes
>  self._prime_iter = iter_primes()
>
>  # the last prime we've seen
>  self._last_prime = None
>
>  # all primes seen so far
>  self._prime_set = set()
>
>  # add the first prime (so that _last_prime is set)
>  self._add_prime()
>
>  def __contains__(self, n):
>  # add primes to the list until we exceed n
>  while n > self._last_prime:
>  self._add_prime()
>
>  # return True if n is one of our primes
>  return n in self._prime_set
>
>  def _add_prime(self):
>  # take a prime off the iterator and update the prime set
>  self._last_prime = self._prime_iter.next()
>  self._prime_set.add(self._last_prime)

I'm afraid my next question is "How do I run this"?

Dick


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


Re: A dumb question about a class

2007-08-12 Thread Steven Bethard
Dick Moores wrote:
> I'm still trying to understand classes. I've made some progress, I 
> think, but I don't understand how to use this one. How do I call it, or 
> any of its functions? It's from the Cookbook, at 
> .

The short answer is that use should look something like::

 >>> plist = PrimeList()
 >>> plist.contains(32)
 False
 >>> plist.contains(23)
 True

But this doesn't seem like a particularly good recipe. Seems like you 
would really rather be writing code like::

 >>> plist = PrimeList()
 >>> 1 in plist
 False
 >>> 2 in plist
 True
 >>> 22 in plist
 False
 >>> 23 in plist
 True
 >>> 782 in plist
 False
 >>> 787 in plist
 True

Here's how I'd write the recipe::

 import itertools

 def iter_primes():
 # an iterator of all numbers between 2 and +infinity
 numbers = itertools.count(2)

 # generate primes forever
 while True:

 # get the first number from the iterator (always a prime)
 prime = numbers.next()
 yield prime

 # remove all numbers from the (infinite) iterator that are
 # divisible by the prime we just generated
 numbers = itertools.ifilter(prime.__rmod__, numbers)


 class PrimeList(object):
 def __init__(self):
 # infinite iterator of primes
 self._prime_iter = iter_primes()

 # the last prime we've seen
 self._last_prime = None

 # all primes seen so far
 self._prime_set = set()

 # add the first prime (so that _last_prime is set)
 self._add_prime()

 def __contains__(self, n):
 # add primes to the list until we exceed n
 while n > self._last_prime:
 self._add_prime()

 # return True if n is one of our primes
 return n in self._prime_set

 def _add_prime(self):
 # take a prime off the iterator and update the prime set
 self._last_prime = self._prime_iter.next()
 self._prime_set.add(self._last_prime)


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


A dumb question about a class

2007-08-12 Thread Dick Moores
I'm still trying to understand classes. I've made some progress, I 
think, but I don't understand how to use this one. How do I call it, 
or any of its functions? It's from the Cookbook, at 
.

Thanks,

Dick Moores

=
class PrimeList:
def __init__(self, initial=0):
self.primelist = [2,3]
self.primelookup = [0,0,1,1]
self.max_prime = 3
self.grow_primelist(initial)

def grow_primelist(self,number):
newprimes = []
while self.max_prime <= number:
next = self.nextprime()
newprimes.append(next)
self.max_prime = next
size_difference = self.max_prime - 
len(self.primelookup) + 1
self.primelookup.extend([0] * size_difference)
for i in newprimes:
self.primelookup[i]=1

def contains(self,number):
if number < 2:
return 0
if number > len(self.primelookup) - 1:
self.grow_primelist(number)
return self.primelookup[number]
return self.primelookup[number]

def nextprime(self):
i = self.max_prime + 2
while 1:
isprime = True
for prime in self.primelist:
if i % prime == 0:
isprime = False
i += 2
break
if isprime:
self.primelist.append(i)
return(i)
==

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


Re: cgi and headers

2007-08-12 Thread Steve Holden
kalin mintchev wrote:
> hi there...
> 
> i'm starting to work with python cgi scripts using ajax.
> one problem i have is that the cgi module doesn;t do (apparently) anything
> without the -- print "Content-type: text/html\n" -- line in the script.
> 
> the issue is that the output of the script has to be an xml file and not
> an html. it's not really a problem for any normal browser but the retarded
> explorer thing doesn;t process the xml unless it gets back the xml header.
> 
> so my scripts work fine on mozilla but not in explorer because of the
> missing xml header.
> 
> what would be the correct solution for this?
> 
> thanks
> 
> 
> 
try "text/xml" or "text/html+xml" as content type. FWIW IE 6 actually 
required an extension of ".xml" on the output page to consider the page 
content to be XML, IIRC. IE 7 may be less broken, I haven't tried it 
much yet.

regards
  Steve

-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: wxPython - drawing without paint event

2007-08-12 Thread Steve Holden
7stud wrote:
> On Aug 12, 2:20 pm, Bjoern Schliessmann  [EMAIL PROTECTED]> wrote:
>> But any suggestions what's
>> better for a beginner? The (incomplete) tutorial surely not.
>>
> 
> Another GUI toolkit.
> 
> 
Well if all you have to offer is fatuous advice you would be helping 
people more by keeping quiet. wxPython is a more-than-adequate GUI 
toolkit, as has been proved in many successful projects.

What other toolkits have you used, and to what effect, and on what size 
of program? I suspect you are not particularly well-qualified to be 
answering this question in the first place, although as always you are 
entitled to your opinion. It's just that you appear to have an inflated 
value of its worth.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: cgi and headers

2007-08-12 Thread kalin mintchev

nevermind...  i'm not sure why the xml header didn;t work before and now
it does...  thanks

>
> hi there...
>
> i'm starting to work with python cgi scripts using ajax.
> one problem i have is that the cgi module doesn;t do (apparently) anything
> without the -- print "Content-type: text/html\n" -- line in the script.
>
> the issue is that the output of the script has to be an xml file and not
> an html. it's not really a problem for any normal browser but the retarded
> explorer thing doesn;t process the xml unless it gets back the xml header.
>
> so my scripts work fine on mozilla but not in explorer because of the
> missing xml header.
>
> what would be the correct solution for this?
>
> thanks
>
>
>


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


cgi and headers

2007-08-12 Thread kalin mintchev

hi there...

i'm starting to work with python cgi scripts using ajax.
one problem i have is that the cgi module doesn;t do (apparently) anything
without the -- print "Content-type: text/html\n" -- line in the script.

the issue is that the output of the script has to be an xml file and not
an html. it's not really a problem for any normal browser but the retarded
explorer thing doesn;t process the xml unless it gets back the xml header.

so my scripts work fine on mozilla but not in explorer because of the
missing xml header.

what would be the correct solution for this?

thanks



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


Re: Regular Expression Grouping

2007-08-12 Thread Paul McGuire
On Aug 12, 12:21 pm, [EMAIL PROTECTED] wrote:
>
> I cannot understand why 'c' constitutes a group here without being
> surrounded by "(" ,")" ?
>
> >>>import re
> >>> m = re.match("([abc])+", "abc")
> >>> m.groups()
>
> ('c',)
>

It sounds from the other replies that this is just the way re's work -
if a group is represented multiple times in the matched text, only the
last matching text is returned for that group.

This sounds similar to a behavior in pyparsing, in using a results
name for the parsed results.  Here is an annotated session using
pyparsing to extract this data.  The explicit OneOrMore and Group
classes and oneOf method give you a little more control over the
collection and structure of the results.

-- Paul

Setup to use pyparsing, and define input string.
>>> from pyparsing import *
>>> data = "abc"

Use a simple pyparsing expression - matches and returns each separate
character.  Each inner match can be returned as element [0], [1], or
[2] of the parsed results.
>>> print OneOrMore( oneOf("a b c") ).parseString(data)
['a', 'b', 'c']

Add use of Group - each single-character match is wrapped in a
subgroup.
>>> print OneOrMore( Group(oneOf("a b c")) ).parseString(data)
[['a'], ['b'], ['c']]

Instead of Group, set a results name on the entire pattern.
>>> pattern = OneOrMore( oneOf("a b c") ).setResultsName("char")
>>> print pattern.parseString(data)['char']
['a', 'b', 'c']

Set results name on the inner expression - this behavior seems most
like the regular expression behavior described in the original post.
>>> pattern = OneOrMore( oneOf("a b c").setResultsName("char") )
>>> print pattern.parseString(data)['char']
c

Adjust results name to retain all of the matched characters for the
given results name.
>>> pattern = OneOrMore( oneOf("a b 
>>> c").setResultsName("char",listAllMatches=True) )
>>> print pattern.parseString(data)['char']
['a', 'b', 'c']

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


Re: Web based Reporting tool for Python

2007-08-12 Thread Jorge Godoy
Jon Rosebaugh wrote:
> Sure, but again, these aren't reporting engines; they're just template
> engines. And I don't think any of the web template engines have PDF
> output.

I generate my PDFs with Genshi / Kid and ReportLab.  For the markup
processing I use z3c.rml.

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


Python not freeing memory (?)

2007-08-12 Thread Chris
I have a Bayesian simulation package that keeps running into memory 
allocation problems. I have a feeling this has something to do with 
Python (2.5.1.1) not freeing memory. The program essentially 
iterates n times, each time proposing new arrays (numpy) of values 
that are evaluated using statistical likelihoods. All variables in 
the loop are re-assigned at each iteration, so there should not be 
a leak. Nevertheless, at approximately the same iteration every 
time, I run into malloc errors:

Iteration 36200 at 5647.58165097

Iteration 36300 at 5664.8412981

Iteration 36400 at 5681.71009493
Python(28344,0xa000d000) malloc: *** vm_allocate(size=8421376) 
failed (error code=3)
Python(28344,0xa000d000) malloc: *** error: can't allocate region
Python(28344,0xa000d000) malloc: *** set a breakpoint in szone_error 
to debug
Traceback (most recent call last):
  File "/Users/chris/EURING/detection/detection2.py", line 285, 
in 
run()
  File "/Users/chris/EURING/detection/detection2.py", line 268, in run
results = sampler.sample(iterations=iterations, burn=burn, thin=thin)
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-
packages/PyMC/MCMC.py", line 3021, in sample
parameter.propose(debug)
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-
packages/PyMC/MCMC.py", line 768, in propose
if not self._sampler.test():
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-
packages/PyMC/MCMC.py", line 2899, in test
self()
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-
packages/PyMC/MCMC.py", line 2562, in __call__
return self.model()
  File "/Users/chris/EURING/detection/detection2.py", line 238, in model
self.pd = invlogit(self.beta0 + self.beta1 * self.wind + self.beta2 * 
(self.cloud>0) + beta3[self.series-
1])
MemoryError

Is there *any* way of getting around this?

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


Re: wxPython - drawing without paint event

2007-08-12 Thread 7stud
On Aug 12, 2:20 pm, Bjoern Schliessmann  wrote:
> But any suggestions what's
> better for a beginner? The (incomplete) tutorial surely not.
>

Another GUI toolkit.


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


Re: Pausing and Unpausing Threads

2007-08-12 Thread Aaron J. M.
On Aug 12, 3:55 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> By this definition, if there is no "action" supplied, a
> "DirectedControler" will result in blocking ALL others (directed or not)
> in this "server" (as it blocks the entire server thread).
>
> Is that really the behavior you want?

For my particular application, yes.  This is exactly what I want.

> I'd suggest using a Queue PER directed controller. Initialize
>
> self._actions = Queue.Queue()
>
> -=-=-=-=-=-
>
> def turn(self):
> while True:
> atn = self._actions.get()   #blocks until at 
> least one entry
> if atn and atn.execute():   #should be in a 
> try/except if
>   
>   # action has NO execute method
> break   #did 
> something, so exit while
>
> -=-=-=-=-=-
>
> def setAction(self, action):
> self._actions.put(action)   #could add code to ensure
> #an 
> execute attribute

Thank you very much for your help. :) I'll get to work on this now.

Cheers,

Aaron J. M.

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


Re: wxPython - drawing without paint event

2007-08-12 Thread Bjoern Schliessmann
7stud wrote:
> I don't.  "wxPython in Action" is by far the worst computer book
> I've ever purchased.  It's poorly organized, poorly written, and
> full of mistakes--and it's expensive.  The fact that the authors
> foist that piece of junk on unsuspecting newbies is a crime.

Your opinion (I've seen much worse). But any suggestions what's
better for a beginner? The (incomplete) tutorial surely not.

Regards,


Björn

-- 
BOFH excuse #88:

Boss' kid fucked up the machine

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


Re: Querying Graphics Card Name

2007-08-12 Thread Jorgen Grahn
On Thu, 09 Aug 2007 21:58:54 -, Benjamin Goldenberg <[EMAIL PROTECTED]> 
wrote:
> On Aug 9, 3:26 pm, Bjoern Schliessmann  [EMAIL PROTECTED]> wrote:
>> Benjamin Goldenberg wrote:
>> > I would like to find out the name of the graphics card of the
>> > machine my program is running on. I have looked into the pyopengl
>> > module, and using them to query the card, but it seems like there
>> > ought to be a simpler way to find this out without setting up a
>> > glcontext. Does anyone have any ideas?
>>
>> You could execute glxinfo and look for the renderer string. If
>> that's sharp enough for your purpose. Another option is lspci.
>
> I should have clarified. I would like a cross platform implementation,
> Windows and *nix. It doesn't seem as if glxinfo is available under
> Windows, at least not without installing X11 under cygwin. If
> necessary, I can write the *nix and Windows queries separately.

Yeah, but ...
- what if there isn't one?
- what if there are several?
- what if there *is* one, but your user is sitting by a remote machine,
  not using the card at all?

Your method will, no matter how you choose, fail sooner or later,
so you'd better plan for that.

What is your reason to do this, by the way?  Remember what Homer
Simpson said: if something appears to be hard, it is simply not worth
doing. And I mean that semi-seriously.

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there anybody using __del__ correctly??

2007-08-12 Thread Steven Bethard
Michele Simionato wrote:
> On Aug 10, 7:09 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
>> There were also a few recipes posted during this discussion that wrap
>> weakrefs up a bit nicer so it's easier to use them in place of __del__:
>>
>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/519635
> 
> I knew about your recipe and I thought it was clever, *very*
> clever. I have been thinking about it a bit more today and
> here is an alternative, which does not require metaclasses,
> does not require descriptors, and does not require the user to
> declare the attributes she will use in the __finalize__ method.
> Warning: it is no more tested than the test case in your recipe:
> 
> import weakref
> 
> _get = object.__getattribute__
> _set = object.__setattr__
> _del = object.__delattr__
> 
> def getinnerobj(self):
> return _get(self, '*innerobj*')
> 
> class Impostor(object):
> "It tries very hard to impersonate the inner object"
> def __init__(self, obj):
> _set(self, '*innerobj*', obj)
> def __getattribute__(self, name):
> return getattr(getinnerobj(self), name)
> def __setattr__(self, name, value):
> _set(getinnerobj(self), name, value)
> def __delattr__(self, name):
> _del(getinnerobj(self), name)
> 
> _refset = set()
> 
> class Finalized(object):
> def __new__(cls, *args, **kw):
> self = super(Finalized, cls).__new__(cls, *args, **kw)
> self.__init__(*args, **kw)
> def finalize(ref, refset=_refset):
> refset.remove(ref)
> cls.__finalize__(self)
> fake = Impostor(self)
> _refset.add(weakref.ref(fake, finalize))
> return fake
> def __finalize__(self):
> pass

The problem here is that __getattribute__ doesn't work for things like 
__getitem__.  So the fake object can't properly delegate these::

 >>> class C(Finalized):
 ... def __getitem__(self, key):
 ... return key
 ...
 >>> c = C()
 >>> c[1]
 Traceback (most recent call last):
   File "", line 1, in 
 TypeError: 'Impostor' object is unindexable

AFAIK, with new-style classes, there is no way to do this kind of 
delegation properly.

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


Re: Fatest standard way to sum bytes (and their squares)?

2007-08-12 Thread Hrvoje Niksic
Erik Max Francis <[EMAIL PROTECTED]> writes:

> So far the fastest way I've found is using the `sum` builtin and
> generators::
>
>   ordinalSum = sum(ord(x) for x in data)
>   ordinalSumSquared = sum(ord(x)**2 for x in data)

For ordinalSum, using imap is almost twice as fast:

$ python -m timeit -s 'data=[chr(x) for x in xrange(256)]' 'sum(ord(x) for x in 
data)'
1 loops, best of 3: 92.4 usec per loop
$ python -m timeit -s 'data=[chr(x) for x in xrange(256)]; from itertools 
import imap' 'sum(imap(ord, data))'
1 loops, best of 3: 55.4 usec per loop

Of course, that optimization doesn't work for the squared sum; using a
lambda only pessimizes it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: who is simpler? try/except/else or try/except

2007-08-12 Thread Fabio Z Tessitore
Il Sun, 12 Aug 2007 20:06:23 +0200, Peter Otten ha scritto:

[cut]
> at the same time introducing the implicit
> constraint that the latter does not fail with .
> Therefore the original code gives the reader a much clearer notion of
> the author's intention.  This may not be a problem for the simple code
> at hand but is definitely a bad habit to get into.
> 

thanks Peter, that's the kind of opinion I'm interesting to.

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


Re: Formatting Results so that They Can be Nicely Imported into a Spreadsheet.

2007-08-12 Thread Gabriel Genellina
En Sun, 05 Aug 2007 06:06:54 -0300, SMERSH009 <[EMAIL PROTECTED]>  
escribió:

> The only question that remains for me--and this is just for my
> knowledge-- what does the "if i" mean in this code snippet?
> f = [i.split() for i in d if i]
> How is it helpful to leave a dangling "if i"? Why not just f =
> [i.split() for i in d]?

`if i` means `if i is considered true`. In this case we are talking about  
strings: "" is false and all other strings are true. So this is a way to  
say `if i is not the empty string`, effectively filtering out empty lines.
Perhaps using more meaningful names for variables makes the code more  
clear:

exploded_lines = [line.split() for line in lines if line]

-- 
Gabriel Genellina

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


Re: who is simpler? try/except/else or try/except

2007-08-12 Thread Peter Otten
Fabio Z Tessitore wrote:

> reading Dive Into Python, on Chapter 6 (exception), I've found:
> 
> "This code comes from the getpass module, a wrapper module for getting a 
> password from the user"

> try:
> from EasyDialogs import AskPassword
> except ImportError:
> getpass = default_getpass
> else:
> getpass = AskPassword

> Knowing that this code is very simple, my question is about simplicity. I 
> think it is simpler the following code. I haven't a long experience on 
> Python, so I'd like to know your opinions about.

> 
> try:
> from EasyDialogs import AskPassword
> getpass = AskPassword
> except ImportError:
> getpass = default_getpass

I think you are asking the wrong question.  The difference between these two
functionally equivalent snippets is in expressiveness rather than
simplicity.

The first can be read as

try:

except :
   
else:


When you move the else suite into the try...except

try:

 #
except :
   

you blur the difference between  and  while at the same time introducing the implicit
constraint that the latter does not fail with . 
Therefore the original code gives the reader a much clearer notion of the
author's intention.  This may not be a problem for the simple code at hand
but is definitely a bad habit to get into. 

Peter

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


Re: Regular Expression Grouping

2007-08-12 Thread Michael J. Fromberger
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] wrote:

> Fairly new to this regex thing, so this might be very juvenile but
> important.
> 
> I cannot understand and why 'c' constitutes a group here without being
> surrounded by "(" ,")" ?
> 
> >>>import re
> >>> m = re.match("([abc])+", "abc")
> >>> m.groups()
> ('c',)
> 
> Grateful for any clarity.

Hello!

I believe your confusion arises from the placement of the "+" operator 
in your expression.  You wrote:

  '([abc])+'

This means, in plain language, "one or more groups in which each group 
contains a string of one character from the set {a, b, c}."

Contrast this with what you probably intended, to wit:

  '([abc]+)'

The latter means, in plain language, "a single group containing a string 
of one or more characters from the set {a, b, c}."

In the former case, the greedy property of matching attempts to maximize 
the number of times the quantified expression is matched -- thus, you 
match the group three times, once for each character of "abc", and the 
result shows you only the last occurrence of the matching. 

Compare this with the following:

] import re
] m = re.match('([abc]+)', 'abc')
] m.groups()
=> ('abc',)

I suspect the latter is what you are after.

Cheers,
-M

-- 
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Public Telnet Server?

2007-08-12 Thread Jorgen Grahn
On Sat, 11 Aug 2007 15:07:25 -, Dave <[EMAIL PROTECTED]> wrote:
> Hi there. I'm a beginner at Python and I'm writing my first Python
> script. It's a text adventure about coffee and mixing drinks and being
> crazy and such. I keep updating it and want my friends to beta test it
> for me, but some of them don't have the right version of Python or
> don't want to get Python at all. Is there an easy way I can set up a
> public telnet server so they can just telnet the server and play it?

- get yourself a Unix machine with a real, routable IP address
- enable telnet (or better, ssh) access
- create a new user
- make the game this user's login shell, or let her login script
  exec the game
- test it out
- distribute address, user name and password to people

"netcat ... -e the_game" may be another option.

However, the security implications of this may be serious. You should
assume these people can get local user shell access whenever they feel
like it, and use your machine for evil purposes. I trust my brother
with local access to my machines, and noone else[1].

/Jörgen

[1] Well, his two cats too, but they have never logged in so far.
Probably forgot the password, too.

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: who is simpler? try/except/else or try/except

2007-08-12 Thread Fabio Z Tessitore
Il Sun, 12 Aug 2007 13:49:18 -0400, Steve Holden ha scritto:

>> 
> In matters of style such as this there *are* only opinions. I don't
> think there are definite grounds for preferring either one.

Opinions are what I'd like to see, because most of you have bigger 
experience than me. maybe this example is too trivial for that ... ;-)

 
> If you were to propose such a patch on the python-dev list,

Oh no, I didn't think that

thanks,

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


Re: Regular Expression Grouping

2007-08-12 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Fairly new to this regex thing, so this might be very juvenile but
> important.
> 
> I cannot understand and why 'c' constitutes a group here without being
> surrounded by "(" ,")" ?
> 
 import re
 m = re.match("([abc])+", "abc")
 m.groups()
> ('c',)
> 
> Grateful for any clarity.
> 
What's happening there is that the same group is being used three times 
to complete the match, but a group can only be represented once in the 
output, so you are seeing the last substring that the group matched. 
Contrast with:

 >>> m = re.match("([abc]+)", 'abc')
 >>> m.groups()
('abc',)
 >>>

I don't *think* there's any way to introduce a variable number of groups 
into your match, but I don't use re's that much so someone may be able 
to help if that's what you want. Is it?

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Regular Expression Grouping

2007-08-12 Thread linnewbie
On Aug 12, 1:31 pm, Fabio Z Tessitore <[EMAIL PROTECTED]>
wrote:
> Il Sun, 12 Aug 2007 17:21:02 +, linnewbie ha scritto:
>
> > Fairly new to this regex thing, so this might be very juvenile but
> > important.
>
> > I cannot understand and why 'c' constitutes a group here without being
> > surrounded by "(" ,")" ?
>
> import re
>  m = re.match("([abc])+", "abc")
>  m.groups()
> > ('c',)
>
> > Grateful for any clarity.
>
> thera are () outer [], maybe you don't know what do [] mean? or you want
> to know why 'c' and not 'a' or 'b'
> bye

I sort of get what the metacharacters  "(", ")"  and "[" ,"]" , groups
are marked by the "(", ")" no?

So I get this:

>>> import re
>>> re.match("ab(c)d","abcd")
<_sre.SRE_Match object at 0xb7d72c60>
>>> m= re.match("ab(c)d","abcd")
>>> m.groups()
('c',)

I can see clearly here that 'c' is group(1), because of the "..(c)..
".  I cannot see how 'c' is a inner group in the expressions "([abc])
+" above?






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


Re: who is simpler? try/except/else or try/except

2007-08-12 Thread Steve Holden
Fabio Z Tessitore wrote:
> Hi all,
> 
> reading Dive Into Python, on Chapter 6 (exception), I've found:
> 
> "This code comes from the getpass module, a wrapper module for getting a 
> password from the user"
> 
> try:
>   import termios, TERMIOS
> except ImportError:
>   try:
>   import msvcrt
>   except ImportError:
>   try:
>   from EasyDialogs import AskPassword
>   except ImportError:
>   getpass = default_getpass
>   else:
>   getpass = AskPassword
>   else:
>   getpass = win_getpass
> else:
>   getpass = unix_getpass
> 
> Knowing that this code is very simple, my question is about simplicity. I 
> think it is simpler the following code. I haven't a long experience on 
> Python, so I'd like to know your opinions about.
> 
> try:
>   import termios, TERMIOS
>   getpass = unix_getpass
> 
> except ImportError:
>   try:
>   import msvcrt
>   getpass = win_getpass
> 
>   except ImportError:
>   try:
>   from EasyDialogs import AskPassword
>   getpass = AskPassword
> 
>   except ImportError:
>   getpass = default_getpass
> 
In matters of style such as this there *are* only opinions. I don't 
think there are definite grounds for preferring either one.

If you were to propose such a patch on the python-dev list, it would 
almost certainly be rejected - not because it is necessarily worse, but 
because it would represent a change of style only.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Launch file from Python

2007-08-12 Thread Jorgen Grahn
On Wed, 08 Aug 2007 10:28:57 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Good afternoon from someone who is trying to learn Python.
>
> I would like to launch an app from within a Python script. From the
> examples I have found, I should be able to do this with os.system.
>
> I use this:
> os.system("xplanet-1.2.0/xplanet.exe -fontsize 24 -label -target earth
> -lat 33.65 -lon -84.42 -radius 40 -num_times 1 -tmpdir .")
> This is copied directly from the .bat file that launches the xplanet
> app. It works there.
>
> and get this:
> 1

That means "error", as others noted.

It is odd that you get no printouts. Had this been on Unix, you'd
either get "file not found" or similar from the shell trying to run
the thing, or something from xplanet itself (only really badly
programs return failure without printing some kind of cause).

Two more comments, assuming you are on Windows (you mention ".bat
files"):

- You use the relative path xplanet-1.2.0/xplanet.exe. That should
  require your program to have the parent of xplanet-1.2.0 as current
  directory. Did the .bat script change directory first?

- It is unusual to use / as a path separator on Windows --
  xplanet-1.2.0\xplanet.exe is more normal. Some parts of Windows
  tolerate both, others do not, IIRC.  But Python itself should not
  care in this case.

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expression Grouping

2007-08-12 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> Fairly new to this regex thing, so this might be very juvenile but
> important.
> 
> I cannot understand and why 'c' constitutes a group here without being
> surrounded by "(" ,")" ?
> 
import re
 m = re.match("([abc])+", "abc")
 m.groups()
> ('c',)
> 
> Grateful for any clarity.
> 
The group matches a single letter a, b, or c. That group must match one or 
more times for the entire expression to match: in this case it matches 3 
times once for the a, once for the b and once for the c. When a group 
matches more than once, only the last match is available, i.e. the 'c'. The 
matches against the a and b are discarded.

Its a bit like having some code:

   x = 'a'
   x = 'b'
   x = 'c'
   print x

and asking why x isn't 'a' and 'b' as well as 'c'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expression Grouping

2007-08-12 Thread Fabio Z Tessitore
Il Sun, 12 Aug 2007 17:21:02 +, linnewbie ha scritto:

> Fairly new to this regex thing, so this might be very juvenile but
> important.
> 
> I cannot understand and why 'c' constitutes a group here without being
> surrounded by "(" ,")" ?
> 
import re
 m = re.match("([abc])+", "abc")
 m.groups()
> ('c',)
> 
> Grateful for any clarity.

thera are () outer [], maybe you don't know what do [] mean? or you want 
to know why 'c' and not 'a' or 'b'
bye
-- 
http://mail.python.org/mailman/listinfo/python-list


Regular Expression Grouping

2007-08-12 Thread linnewbie
Fairly new to this regex thing, so this might be very juvenile but
important.

I cannot understand and why 'c' constitutes a group here without being
surrounded by "(" ,")" ?

>>>import re
>>> m = re.match("([abc])+", "abc")
>>> m.groups()
('c',)

Grateful for any clarity.

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


Re: Puzzled by "is"

2007-08-12 Thread Dick Moores
At 09:59 AM 8/12/2007, Steve Holden wrote:
>Dick Moores wrote:
> > At 08:23 AM 8/12/2007, Steve Holden wrote:
> >> Dick Moores wrote:
> >>> So would a programmer EVER use "is" in a script?
> >> Sure. For example, the canonical test for None uses
> >>
> >>  x is None
> >>
> >> because there is only ever one instance of type Nonetype, so it's the
> >> fastest test. Generally speaking you use "is" to test for identity (do
> >> these two expressions reference the same object) rather than equality
> >> (do these two expressions evaluate to equivalent objects).
> >
> > Off the top of your head, could you or others give me as many
> > examples as you can think of?
> >
>Occasionally it's necessary to test for a specific type (though in
>Python this is usually bad practice). Since types are also singletons
>the best way to do this is (e.g.):
>
>  type(x) is type([]) # test specifically for a list
>
>If you want to know whether you have been told to write to standard
>output, one possible test is
>
>  if f is not sys.stdout
>
>Similarly, of course, you can test for the other standard IO channels.
>
>The imputil module contains the test
>
>  if importer is not self
>
>to determine whether a reload() should be performed in the context of
>the current package.
>
>When you need to establish a specific sentinel value that can never be
>provided by an outside caller it's normal to create an instance of
>object (the simplest possible thing you can create in a Python program)
>and test for that instance, as in
>
>  sentinel = object()
>  ...
>  if value is sentinel:
>
>You can test whether a class is new-style as opposed to old-style, which
>can help to unify old-style and new-style objects:
>
>class MetaProperty(type):
>  def __new__(cls, name, bases, dct):
>  if bases[0] is object: # allow us to create class Property
>  return type.__new__(cls, name, bases, dct)
>  return property(dct.get('get'), dct.get('set'),
>  dct.get('delete'), dct.get('__doc__'))
>
>  def __init__(cls, name, bases, dct):
>  if bases[0] is object:
>  return type.__init__(cls, name, bases, dct)
>
>
>That gets you started ...

Sure does. Thanks very much, Steve.

Dick


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


Re: Pausing and Unpausing Threads

2007-08-12 Thread Martin v. Löwis
> I'm worried that this loop may wast some CPU cycles, and wonder if
> there's a better way through thread synchronization using such things
> as Events or Conditions.

Typically, people are after the Queue module in such cases. Each
DirectedControl(l)er would have an instance of the Queue class,
and clients would put() actions into the queue. The controller would
get() an action from the queue, execute it, get the next action,
and so on. The get() will block when the queue is empty, so you
get synchronization for free. The queue would also accommodate the
case where multiple clients want to direct the same controller
simultaneously, by, well, queuing up the tasks.

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


who is simpler? try/except/else or try/except

2007-08-12 Thread Fabio Z Tessitore
Hi all,

reading Dive Into Python, on Chapter 6 (exception), I've found:

"This code comes from the getpass module, a wrapper module for getting a 
password from the user"

try:
import termios, TERMIOS
except ImportError:
try:
import msvcrt
except ImportError:
try:
from EasyDialogs import AskPassword
except ImportError:
getpass = default_getpass
else:
getpass = AskPassword
else:
getpass = win_getpass
else:
getpass = unix_getpass

Knowing that this code is very simple, my question is about simplicity. I 
think it is simpler the following code. I haven't a long experience on 
Python, so I'd like to know your opinions about.

try:
import termios, TERMIOS
getpass = unix_getpass

except ImportError:
try:
import msvcrt
getpass = win_getpass

except ImportError:
try:
from EasyDialogs import AskPassword
getpass = AskPassword

except ImportError:
getpass = default_getpass

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


Re: Web based Reporting tool for Python

2007-08-12 Thread Jon Rosebaugh
On 2007-08-12 06:08:49 -0500, Steve Holden <[EMAIL PROTECTED]> said:

> Steve Holden wrote:
>> Madhu Alagu wrote:
>>> On Aug 8, 4:57 pm, Jon Rosebaugh <[EMAIL PROTECTED]> wrote:
 On 2007-08-07 23:35:26 -0500, Madhu Alagu <[EMAIL PROTECTED]> said:
 
> Thanking so much for all the informations and links.I would like to
> use Mako Templates(www.makotemplates.org).Ilike to use simple and
> python default module...
 Mako is an excellent template system, but you'll have a lot of work to
 do making it into a reporting system.
>>> 
>>> 
>>> Any reporting template in python ?
>>> 
>> 
>> Dabo (www.dabodev.com) is certainly heading that way, but I am not sure 
>> how far it's got yet.
>> 
> Sorry, Dabo isn't web-based. You could look at Kid, Genshi, Cheetah, ...
> 
> Or you could do a Google search for "python web template" and see what 
> comes up. There are many good contenders.

Sure, but again, these aren't reporting engines; they're just template 
engines. And I don't think any of the web template engines have PDF 
output.

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


Re: Puzzled by "is"

2007-08-12 Thread Steve Holden
Dick Moores wrote:
> At 08:23 AM 8/12/2007, Steve Holden wrote:
>> Dick Moores wrote:
>>> So would a programmer EVER use "is" in a script?
>> Sure. For example, the canonical test for None uses
>>
>>  x is None
>>
>> because there is only ever one instance of type Nonetype, so it's the
>> fastest test. Generally speaking you use "is" to test for identity (do
>> these two expressions reference the same object) rather than equality
>> (do these two expressions evaluate to equivalent objects).
> 
> Off the top of your head, could you or others give me as many 
> examples as you can think of?
> 
Occasionally it's necessary to test for a specific type (though in 
Python this is usually bad practice). Since types are also singletons 
the best way to do this is (e.g.):

 type(x) is type([]) # test specifically for a list

If you want to know whether you have been told to write to standard 
output, one possible test is

 if f is not sys.stdout

Similarly, of course, you can test for the other standard IO channels.

The imputil module contains the test

 if importer is not self

to determine whether a reload() should be performed in the context of 
the current package.

When you need to establish a specific sentinel value that can never be 
provided by an outside caller it's normal to create an instance of 
object (the simplest possible thing you can create in a Python program) 
and test for that instance, as in

 sentinel = object()
 ...
 if value is sentinel:

You can test whether a class is new-style as opposed to old-style, which 
can help to unify old-style and new-style objects:

class MetaProperty(type):
 def __new__(cls, name, bases, dct):
 if bases[0] is object: # allow us to create class Property
 return type.__new__(cls, name, bases, dct)
 return property(dct.get('get'), dct.get('set'),
 dct.get('delete'), dct.get('__doc__'))

 def __init__(cls, name, bases, dct):
 if bases[0] is object:
 return type.__init__(cls, name, bases, dct)


That gets you started ...

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Puzzled by "is"

2007-08-12 Thread Dick Moores
At 08:23 AM 8/12/2007, Steve Holden wrote:
>Dick Moores wrote:
> > So would a programmer EVER use "is" in a script?
>
>Sure. For example, the canonical test for None uses
>
>  x is None
>
>because there is only ever one instance of type Nonetype, so it's the
>fastest test. Generally speaking you use "is" to test for identity (do
>these two expressions reference the same object) rather than equality
>(do these two expressions evaluate to equivalent objects).

Off the top of your head, could you or others give me as many 
examples as you can think of?

Thanks again,

Dick


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


Re: LRU cache?

2007-08-12 Thread Nikita the Spider
In article <[EMAIL PROTECTED]>,
 Paul Rubin  wrote:

> Anyone got a favorite LRU cache implementation?  I see a few in google
> but none look all that good.  I just want a dictionary indexed by
> strings, that remembers the last few thousand entries I put in it.
> 
> It actually looks like this is almost a FAQ.  A well-written
> implementation would probably make a good standard library module.

This one works for me:
http://www.webfast.com/~skip/python/Cache.py

-- 
Philip
http://NikitaTheSpider.com/
Whole-site HTML validation, link checking and more
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Compyler 0.1

2007-08-12 Thread Irmen de Jong
Grant Olson wrote:
> Compyler is a pre-alpha x86 native code compiler. 

In what ways is this similar or different to Shed Skin?
http://mark.dufour.googlepages.com/

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


Re: Puzzled by "is"

2007-08-12 Thread Steve Holden
Dick Moores wrote:
> On 8/12/07, *Ben Finney* <[EMAIL PROTECTED] 
> > wrote:
> 
> Dick Moores <[EMAIL PROTECTED] > writes:
> 
>  > At 06:13 PM 8/9/2007, Ben Finney wrote:
>  > >it's entirely left to the language implementation which
>  > >optimisation trade-offs to make, and the language user (that's you
>  > >and I) should *not* expect any particular behaviour to hold between
>  > >different implementations.
>  >
>  > I'm not clear on the meaning of "implementations" here.  Would 2.5
>  > for Windows, Mac, Linux all be different implementations? Would Iron
>  > Python be another? ActivePython?
> 
> For the purpose of the above statement, you should consider even the
> same Python on two different machines to be "different
> implementations". As a programmer writing Python code, you should not
> expect any "implementation-dependent" behaviour to operate in any
> particular way.
> 
> 
> So would a programmer EVER use "is" in a script?

Sure. For example, the canonical test for None uses

 x is None

because there is only ever one instance of type Nonetype, so it's the 
fastest test. Generally speaking you use "is" to test for identity (do 
these two expressions reference the same object) rather than equality 
(do these two expressions evaluate to equivalent objects).

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Database intensive application

2007-08-12 Thread johnf
Rohit wrote:

> I am a novice. I want to know whether Python can be used to develop
> client/server database and web applications like .NET. Which is the
> best book/source to learn Python?


IMO you should use Dabo (www.dabodev.com).  If you want to strike on your
own check using SQLAlchemy as your database connection.  

Check out the O'Reilly books.

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


Re: I am giving up perl because of assholes on clpm -- switching to Python

2007-08-12 Thread Robert Dailey
That's a bit hard given the unpredictability of each person on that list.
What seems like a simple question one minute suddenly turns into a flamewar
because someone had a bad day at work and needed to vent at my expense. This
is beyond phrasing your questions properly. It has to do with just pure
stupidity.

On 8/11/07, Greg Donald <[EMAIL PROTECTED]> wrote:
>
> On 8/11/07, Robert Dailey <[EMAIL PROTECTED]> wrote:
> > I had this very same problem with the doxygen mailing list... doxygen is
> > such a great tool but full of assholes in their mailing list.
>
> I'm not defending any assholes you may have ran into, but I find the
> thing to do is only ask questions in such a way that no one can
> possibly have a reason to be an asshole.
>
> http://catb.org/~esr/faqs/smart-questions.html
>
>
> --
> Greg Donald
> http://destiney.com/
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: wxPython - drawing without paint event

2007-08-12 Thread 7stud
On Aug 12, 6:06 am, Bjoern Schliessmann  wrote:
> I really recommend reading "wxPython in Action", or at least the
> tutorial.
>

I don't.  "wxPython in Action" is by far the worst computer book I've
ever purchased.  It's poorly organized, poorly written, and full of
mistakes--and it's expensive.  The fact that the authors foist that
piece of junk on unsuspecting newbies is a crime.

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


Bill Gates try to sell Microsoft @ ebay look here

2007-08-12 Thread MartinWuitz
http://www.pennergame.de/ref.php?uid=4762

http://www.pennergame.de/ref.php?uid=5572

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


Re: Puzzled by "is"

2007-08-12 Thread Dick Moores
On 8/12/07, Ben Finney <[EMAIL PROTECTED]> wrote:
>
> Dick Moores <[EMAIL PROTECTED]> writes:
>
> > At 06:13 PM 8/9/2007, Ben Finney wrote:
> > >it's entirely left to the language implementation which
> > >optimisation trade-offs to make, and the language user (that's you
> > >and I) should *not* expect any particular behaviour to hold between
> > >different implementations.
> >
> > I'm not clear on the meaning of "implementations" here.  Would 2.5
> > for Windows, Mac, Linux all be different implementations? Would Iron
> > Python be another? ActivePython?
>
> For the purpose of the above statement, you should consider even the
> same Python on two different machines to be "different
> implementations". As a programmer writing Python code, you should not
> expect any "implementation-dependent" behaviour to operate in any
> particular way.


So would a programmer EVER use "is" in a script?

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

Re: Seek the one billionth line in a file containing 3 billion lines.

2007-08-12 Thread John J. Lee
"Chris Mellon" <[EMAIL PROTECTED]> writes:
[...]
> The minimum bounds for a line is at least one byte (the newline) and
> maybe more, depending on your data. You can seek() forward the minimum
> amount of bytes that (1 billion -1) lines will consume and save
> yourself some wasted IO.

But how do you know which line number you're on, then?


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


Re: Database intensive application

2007-08-12 Thread Peter Decker
On 8/12/07, Rohit <[EMAIL PROTECTED]> wrote:
> I am a novice. I want to know whether Python can be used to develop
> client/server database and web applications like .NET. Which is the
> best book/source to learn Python?

You've already gotten several excellent answers for web applications;
if you need to create client/server desktop database apps, your best
(and AFAIK, only) choice would be Dabo: http://dabodev.com
-- 

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >