Re: Optimizing methods away or not?

2008-12-14 Thread James Stroud

Steven D'Aprano wrote:

class Parrot:
def __init__(self, *args):
print "Initialising instance..."
if __debug__:
self.verify()  # check internal program state, not args
if __debug__:
def verify(self):
print "Verifying..."


+1 It looks good to me and the intent is much clearer than the other.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bidrectional Subprocess Communication

2008-12-14 Thread greg

Gabriel Genellina wrote:

(Pipes don't work the same as sockets, although unix-like systems try 
hard  to hide the differences...)


BSD-based unixes implement pipes using socketpair(), so
pipes actually *are* sockets (or at least they used to be,
not sure whether it's still true).

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


Re: __future__ and compile: unrecognised flags

2008-12-14 Thread Rhamphoryncus
On Dec 13, 6:03 am, Steve Holden  wrote:
> Poor Yorick wrote:
> > I have a future statement in a script which is intended to work in 2.6 and 
> > 3.
> > Shouldn't compile flags in __future__ objects essentially be noops for 
> > versions
> > that already support the feature? doctest is complaining about unrecognised
> > flags.  This illustrates the problem:
>
> >     Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit 
> > (Intel)] on win
> >     32
> >     Type "help", "copyright", "credits" or "license" for more information.
> >     >>> from __future__ import unicode_literals
> >     >>> src = 'a = "hello"'
> >     >>> c1 = compile(src,'','exec',unicode_literals.compiler_flag)
> >     Traceback (most recent call last):
> >       File "", line 1, in 
> >     ValueError: compile(): unrecognised flags
>
> This could arguably be classed as a bug given that the 2.6 documentation
> for __future__ says "No feature description will ever be deleted from
> __future__." However I suspect that the feature has been removed because
> all string literals are Unicode in 3.0 and up, and 3.0 is allowed to
> break compatibility.

I don't think the rule about __future__ applies to compile().
--
http://mail.python.org/mailman/listinfo/python-list


Re: Optimizing methods away or not?

2008-12-14 Thread Marc 'BlackJack' Rintsch
On Sun, 14 Dec 2008 07:41:55 +, Steven D'Aprano wrote:

> I have a class with a method meant to verify internal program logic (not
> data supplied by the caller). Because it is time-consuming but optional,
> I treat it as a complex assertion statement, and optimize it away if
> __debug__ is false:
> 
> class Parrot:
> def __init__(self, *args):
> print "Initialising instance..."
> if __debug__:
> self.verify()  # check internal program state, not args
> if __debug__:
> def verify(self):
> print "Verifying..."
> 
> 
> If I run Python normally, I can do this:
> 
 p = Parrot()
> Initialising instance...
> Verifying...
 p.verify()
> Verifying...
> 
> 
> and if I run Python with the -O flag, I get this:
> 
 p = Parrot()
> Initialising instance...
 p.verify()
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: Parrot instance has no attribute 'verify'
> 
> 
> This is the behaviour I want, but I haven't seen it before in other
> code. What do people think? Is it a good idea or a bad?
> 
> If you think it is a bad idea to have verify disappear under
> optimization, would you change your mind if it were called __verify
> instead?
> 
> 
> One possible alternative is to do something like this:
> 
> class Parrot:
> def __init__(self, *args):
> print "Initialising instance..."
> if __debug__:
> self.verify()
> def verify(self):
> if __debug__:
> print "Verifying..."
> return None
> # this is optional
> else:
> warnings.warn("verify() is a null op")
> 
> 
> which now means that Parrot instances will always have a verify method,
> even if it does nothing. I'm not sure I like that. What do others think?
> Which do you consider better design?

None of it.  Why not simply:

class Parrot:
def __init__(self, *args):
print "Initialising instance..."
assert self.verify()

def _verify(self):
print "Verifying..."
return None

If you compile with -O the ``assert`` is optimized away.  But you still 
can call `_verify()` at specific points even in optimized code if you 
want or need.

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


Re: XMPP xmpppy - User Authorization

2008-12-14 Thread James Mills
On Sun, Dec 14, 2008 at 3:47 PM, Henson  wrote:
> In my own bot, using the latest xmpppy, I've been printing everything
> going to the message handler to the screen.  I've yet to see a
> 'subscribe' string.  Has this changed?

No this hasn't changed. This is the string you need
to check for. It does work :)

cheers
James

>
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Optimizing methods away or not?

2008-12-14 Thread Marc 'BlackJack' Rintsch
On Sun, 14 Dec 2008 09:19:45 +, Marc 'BlackJack' Rintsch wrote:

> class Parrot:
> def __init__(self, *args):
> print "Initialising instance..."
> assert self.verify()

Here I meant ``assert self._verify()`` of course.

> def _verify(self):
> print "Verifying..."
> return None

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


Re: the official way of printing unicode strings

2008-12-14 Thread Marc 'BlackJack' Rintsch
On Sun, 14 Dec 2008 06:48:19 +0100, Piotr Sobolewski wrote:

> Then I tried to do this that way:
> sys.stdout = codecs.getwriter("utf-8")(sys.__stdout__)
> s = u"Stanisław Lem"
> print u
> This works but is even more combersome.
> 
> So, my question is: what is the official, recommended Python way?

I'd make that first line:

sys.stdout = codecs.getwriter('utf-8')(sys.stdout)

Why is it even more cumbersome to execute that line *once* instead 
encoding at every ``print`` statement?

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


Re: the official way of printing unicode strings

2008-12-14 Thread Piotr Sobolewski
Marc 'BlackJack' Rintsch wrote:

> I'd make that first line:
> sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
> 
> Why is it even more cumbersome to execute that line *once* instead
> encoding at every ``print`` statement?

Oh, maybe it's not cumbersome, but a little bit strange - but sure, I can
get used to it. 

My main problem is that when I use some language I want to use it the way it
is supposed to be used. Usually doing like that saves many problems.
Especially in Python, where there is one official way to do any elementary
task. And I just want to know what is the normal, official way of printing
unicode strings. I mean, the question is not "how can I print the unicode
string" but "how the creators of the language suppose me to print the
unicode string". I couldn't find an answer to this question in docs, so I
hope somebody here knows it.

So, is it _the_ python way of printing unicode?


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


Re: 1 or 1/0 doesn't raise an exception

2008-12-14 Thread Rohannes
'Dive into Python' has a very memorable and interesting section on the
exact behaviour of 'and' and 'or' in Python:

http://diveintopython.org/power_of_introspection/and_or.html

> No: &, | (and ^, too) perform bitwise operations in Python, C and Java:

"In complete evaluation ... both expressions are always evaluated. To
obtain complete evaluation in Java, you use & rather than && ... and
use | in place of ||" - Walter Savitch, Absolute Java 2nd ed.

Although & IS the bitwise-AND operator in Java:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html

I guess it's a matter of context.
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess to pipe through several processes?

2008-12-14 Thread rdmurray

On Sat, 13 Dec 2008 at 23:05, Neal Becker wrote:

How would I use suprocess to do the equivalent of:

cat - | program_a | program_b


Have you tried extending the pipe example from the manual?

http://docs.python.org/library/subprocess.html#replacing-shell-pipeline

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


Re: Optimizing methods away or not?

2008-12-14 Thread Steven D'Aprano
On Sun, 14 Dec 2008 09:19:45 +, Marc 'BlackJack' Rintsch wrote:

> On Sun, 14 Dec 2008 07:41:55 +, Steven D'Aprano wrote:
> 
>> I have a class with a method meant to verify internal program logic
>> (not data supplied by the caller). Because it is time-consuming but
>> optional, I treat it as a complex assertion statement, and optimize it
>> away if __debug__ is false:
...
>> What do others
>> think? Which do you consider better design?
> 
> None of it.  Why not simply:
> 
> class Parrot:
> def __init__(self, *args):
> print "Initialising instance..."
> assert self._verify()
> 
> def _verify(self):
> print "Verifying..."
> return None

For your method to work, I'd have to have _verify return a boolean flag 
instead of None, because assert None always fails.


> If you compile with -O the ``assert`` is optimized away.  But you still
> can call `_verify()` at specific points even in optimized code if you
> want or need.

That's a reasonable approach, if my use-case was for the caller to call 
the verify method. It's not: it's verifying my program logic rather than 
the caller's data, and it's only meaningful to do that verification at 
initialisation time.



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


Re: problem adding custom module in cgi script

2008-12-14 Thread bobicanprogram
On Dec 11, 8:03 pm, bobicanprogram  wrote:
> Problem:
>
> Apache server serving an HTML file to a Firefox Browser containing a
> form and
> a CGI python CGI script. HTML works fine, meat of the CGI script works
> fine
> except that when a home grown and ordinarily functional module that is
> to be
> imported is added, the interpreter cannot find it.
>
> Running cgi.test() reveals that PYTHONPATH is correctly set. Still
> nada.
> Adding the sys.* stuff still nada.
>
> Items: Firefox Browser, Apache server, Python 2.5.
>
> ===
>
> The CGI script:
> #! /usr/bin/python
>
> import cgi
> #cgi.test()
> import sys
>
> #sys.path.append("/myModulePath")
> #sys.path.insert(0, "/myModulePath")
> import myModule  Problem here 
>
> ===
> httpd error_log excerpt:
> [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] Traceback
> (most recent
> call last):, referer:http://192.168.1.1/nee.html
> [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1]
> File "/var/www/cgi-bin/noo.py", line 11, in , 
> referer:http://192.168.1.1/nee.html
> [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] import
> myModule,
> referer:http://192.168.1.1/nee.html
> [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] ImportError:
> No module
> named myModule, referer:http://192.168.1.1/nee.html
>
> =
> Relevant lines from http.conf:
> ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
> SetEnv PYTHONPATH /myModulePath
> PassEnv PYTHONPATH
>
> Thanks in advance for any pointers.
>
> bob


Solution found!

The apache web server is running on a Linux box equipped with SELinux
which
was preventing apache from opening the required modules according to
the
SELinux troubleshoot browser which is available from the main menu
under the
administration moniker. Apache's error_log describes the problem as
one of
not being able to locate the said modules for import. This is
misleading to
say the least. Adjusting SELinux to allow this is the solution to the
problem; this  can be done under 'main menu/administration/ SELinux
Management

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


Re: Optimizing methods away or not?

2008-12-14 Thread Arnaud Delobelle
Steven D'Aprano  writes:

> On Sun, 14 Dec 2008 10:52:25 +, Arnaud Delobelle wrote:
>
>> You could also not use the metaclass and use post_verify as a decorator
>
> Except that self.verify doesn't exist if __debug__ is false.

OK I wrote this as an afterthought.  I'm, sure it's not beyond your ability
to add

if not __debug__:
return method

at the start of the post_verify function :)

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


Re: subprocess to C program

2008-12-14 Thread bobicanprogram
On Dec 13, 10:09 pm, MRAB  wrote:
> Aaron Brady wrote:
> > On Dec 13, 7:51 pm, Grant Edwards  wrote:
> >> On 2008-12-14, MRAB  wrote:
>
>  I am writing a C process and I want to read data from a file that I
>  write to in Python.  I'm creating a pipe in Python, passing it to the
>  C process, and calling '_read'.  It gives me error 9, bad file number.
> > snip
>  meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9.  I want 'ct'
>  to be 11 at this point.  Thanks in advance.
> >>> It looks like the ids aren't system global.
> >> They certainly aren't in Unix: Their a property of the process.
>
> >> --
> >> Grant
>
> > I'm not on Unix.  It has to be possible somehow.  Do I need to set
> > permissions on the IDs?  Are Stdin and Stdout my only options?  Or
> > does Popen prevent sharing IDs somehow?
>
> You'd be better off using sockets.


You might also consider using SIMPL (http://www.icanprogram.com/simpl)
SIMPL has had a Python interface for about 5 years now.   There is an
online tutorial here. (http://www.icanprogram.com/06py/main.html)

In one of your responses you mentioned that you were not on Unix (and
I presume Linux).   SIMPL-Python has recently been extended to work
transparently from a Windows OS as well.

bob
SIMPL project coordinator
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bidirectional Networking

2008-12-14 Thread Emanuele D'Arrigo
On Dec 14, 4:10 am, "Gabriel Genellina" 
wrote:
> daemon became a property in Python 2.6; setDaemon was the only way to set
> it in previous versions.

I thought that might be the case! The documentation is a bit vague:

http://docs.python.org/library/threading.html?highlight=threading#threading.Thread.setDaemon

Should we maybe add "New in 2.6" to the Thread.daemon paragraph?

Manu

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


Re: Bidirectional Networking

2008-12-14 Thread Emanuele D'Arrigo
On Dec 14, 2:40 am, Brian Allen Vanderburg II
 wrote:
> But what I think it means is that during the listen for an incoming
> connection on the listening socket, if multiple connection attempts are
> coming in at one time it can keep a backlog of up to 5 of these
> connection attempts for that individual socket.

Ah, Gotcha! Thank you, that makes sense!

Manu


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


Re: [OT] stable algorithm with complexity O(n)

2008-12-14 Thread Arnaud Delobelle
Steven D'Aprano  writes:

> On Sat, 13 Dec 2008 19:17:41 +, Duncan Booth wrote:
>
>> I think you must have fallen asleep during CS101. The lower bound for
>> sorting where you make a two way branch at each step is O(n * log_2 n),
>> but if you can choose between k possible orderings in a single
>> comparison you can get O(n * log_k n).
>
> I think you might have been sleeping through Maths 101 :-)
>
> The difference between log_2 N and log_k N is a constant factor (log_2 k) 
> and so doesn't effect the big-oh complexity.

It affects it if k is a function of n.  In this particular example, we
can set k=n so we get O(n).

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


Swig for Python 2.6

2008-12-14 Thread Doron Tal
Hi

I'm trying to wrap a c library for use with Python 2.6.

I'm using swig 1.3.36, and I get the following error:

linux-python/log_wrap.c: In function '_PySwigObject_type':
linux-python/log_wrap.c:1680: warning: missing initializer
linux-python/log_wrap.c:1680: warning: (near initialization for
'tmp.tp_version_tag')
linux-python/log_wrap.c: In function '_PySwigPacked_type':
linux-python/log_wrap.c:1843: warning: missing initializer
linux-python/log_wrap.c:1843: warning: (near initialization for
'tmp.tp_version_tag')
linux-python/log_wrap.c: In function 'swig_varlink_type':
linux-python/log_wrap.c:3334: warning: missing initializer
linux-python/log_wrap.c:3334: warning: (near initialization for
'tmp.tp_version_tag')

What swig version should I use?
If version 1.3.36 is good enough, then what can be my mistake?

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


Re: Bidrectional Subprocess Communication

2008-12-14 Thread Emanuele D'Arrigo
On Dec 14, 4:48 am, "Gabriel Genellina" 
wrote:
> - you have to close server.stdin when you don't have more data to send.
> The server will see an end-of-file and knows it has to exit the loop.
> Same thing on the client side.

Hi Gabriel, thanks for modifying the code to make it work. I've just
tried tinkering with it to see how far it would go. On your two
statements above: does this means that any data must be sent in one
batch and then the subprocess must shut down? What I was trying to
simulate is a client/server relationship through a subprocess, where
the server (the subprocess) keeps listening and the client sends data
when it wants to (and eventually viceversa). But when the
server.stdin.close() statement is issued, the pipe is closed for good
and can't be reopened (can it?).

> - you have to wait until the server answers, else it will get a "broken
> pipe" error or similar.

So, if I want to interrogate the subprocess multiple times I must end
and restart the ListenerThread multiple times then?

In the meantime, I better brush up on my streams... =)

Thanks for your help!

Manu


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


Re: Optimizing methods away or not?

2008-12-14 Thread Steven D'Aprano
On Sun, 14 Dec 2008 10:52:25 +, Arnaud Delobelle wrote:

> You could also not use the metaclass and use post_verify as a decorator

Except that self.verify doesn't exist if __debug__ is false.


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


Re: 1 or 1/0 doesn't raise an exception

2008-12-14 Thread News123
Hi.

r wrote:
> These are just the kind of things that make Python so beautiful ;)
> Thanks Guido!


You shouldn't forget to thank K&R ;-)
Shortcutting logical operation shortcuts existed already in C and has
been adopted by quite a lot of programming languages.


bye


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


Re: Optimizing methods away or not?

2008-12-14 Thread Arnaud Delobelle
Steven D'Aprano  writes:

> I have a class with a method meant to verify internal program logic (not 
> data supplied by the caller). Because it is time-consuming but optional, 
> I treat it as a complex assertion statement, and optimize it away if 
> __debug__ is false:
>
> class Parrot:
> def __init__(self, *args):
> print "Initialising instance..."
> if __debug__:
> self.verify()  # check internal program state, not args
> if __debug__:
> def verify(self):
> print "Verifying..."
>
>
> If I run Python normally, I can do this:

FWIW here is a way with a metaclass:

= verify_init.py =

from functools import wraps

def post_verify(method):
@wraps(method)
def decorated(self, *args):
result = method(self, *args)
self.verify()
return result
return decorated

class VerifyInit(type):
def __new__(meta, name, bases, attrs):
if __debug__:
attrs['__init__'] = post_verify(attrs['__init__'])
else:
del attrs['verify']
return type.__new__(meta, name, bases, attrs)

class Parrot:
 __metaclass__ = VerifyInit
 def __init__(self, *args):
 print "Initialising instance..."
 def verify(self):
 print "Verifying..."

coco = Parrot()

==

marigold:junk arno$ python verify_init.py 
Initialising instance...
Verifying...
marigold:junk arno$ python -O verify_init.py 
Initialising instance...

You could also not use the metaclass and use post_verify as a decorator:

class Parrot:
 @post_verify
 def __init__(self, *args):
 print "Initialising instance..."
 if __debug__:
 def verify(self):
 print "Verifying..."

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


Re: curses and refreshing problem

2008-12-14 Thread Karlo Lozovina
Carl Banks  wrote in
news:69d2698a-6f44-4d85-adc3-1180ab158...@r15g2000prd.googlegroups.com: 

> Unless you are referring to some wget screen mode I don't know about,
> I suspect wget outputs its progress bar using carriage returns
> without newlines.  If that's all you want, there is no need to use
> curses. 
> 
> Here is a little example program to illustrate:
> 
> import time, sys
> for i in range(21):
> sys.stdout.write('\rProgress: [' + '='*i + ' '*(20-i) + ']')
> sys.stdout.flush()
> time.sleep(1)
> sys.stdout.write("\nFinised!\n")

Thanks, that's it! I just assumed wget uses curses for the progress bar, 
so the carriage return didn't even cross my mind ;).

-- 
 ___Karlo Lozovina - Mosor
|   |   |.-.-. web: http://www.mosor.net || ICQ#: 10667163
|   ||  _  |  _  | Parce mihi domine quia Dalmata sum.
|__|_|__||_|_|
--
http://mail.python.org/mailman/listinfo/python-list


[OT] Alternative web server scripting language

2008-12-14 Thread Petite Abeille

Hello,

Now that Lua [1] appears as a native scripting language in more [2]  
and more [3] mainstream web servers, here is an example of a web  
server written in Lua:


http://svr225.stepx.com:3388/a

The wiki demo sports content from the 2008/9 Wikipedia Selection,  
containing about 5500 articles, accessible through full text search:


http://svr225.stepx.com:3388/search?q=python

An index, timeline and recent changes navigation is provided to  
facilitate article retrieval:


http://svr225.stepx.com:3388/index/a
http://svr225.stepx.com:3388/date/2008
http://svr225.stepx.com:3388/recent

The wiki content is accessible as an Atom feed:

feed://svr225.stepx.com:3388/search?q=brazil
feed://svr225.stepx.com:3388/index/a
feed://svr225.stepx.com:3388/date/2008
feed://svr225.stepx.com:3388/recent

Or as a WebDAV repository:

dav://svr225.stepx.com:3388/

Kind regards,

--
PA.
http://alt.textdrive.com/nanoki/

[1] http://www.lua.org/about.html
[2] http://svn.apache.org/repos/asf/httpd/mod_wombat/trunk/README
[3] http://redmine.lighttpd.net/wiki/1/Docs:ModMagnet
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help improving number guessing game

2008-12-14 Thread feba
#!/usr/bin/python
#Py3k, UTF-8

import random

def setup():
#global target, guess, a, b
#a, b make minimum, maximum. Can be adjusted.
a, b = 1, 99
target = random.randint(a, b)
return a, b, target

def playerswitch(player):
#Player Switch
#if player's a witch, burn her!
if player == "P1":
player = "P2"
else:
player = "P1"
return player

def youwin(pnum, player, p1sc, p2sc):
if pnum == 1:
print("CONGRATULATIONS!")
else:
if player == "P1":
p1sc += 1
else:
p2sc += 1
end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s"
print(end %(player, p1sc, p2sc))
return p1sc, p2sc

def playagain(play):
playover = input("PLAY AGAIN? Y/N: ")
if playover.strip().lower() == "y":
play = 1
a, b, target = setup()
else:
print("GOOD BYE. PLAY AGAIN SOON!")
quit()
return play, a, b, target


def guesscheck(guess, target, play, a, b, p1sc, p2sc):
if guess == target:
p1sc, p2sc = youwin(pnum, player, p1sc, p2sc)
play, a, b, target = playagain(play)
elif guess >= b:
print("NUMBER MUST BE IN RANGE")
guess = int(input("[%s-%s]%s>> " % (a, b, player)))
play, a, b, target, p1sc, p2sc = guesscheck(guess, target,
play,
a, b, p1sc, p2sc)
elif guess <= a:
print("NUMBER MUST BE IN RANGE")
guess = int(input("[%s-%s]%s>> " % (a, b, player)))
play, a, b, target, p1sc, p2sc = guesscheck(guess, target,
play,
a, b, p1sc, p2sc)
elif guess > target:
print("TOO HIGH")
b = guess
else:
print("TOO LOW")
a = guess
return play, a, b, target, p1sc, p2sc

def guessing(a, b, player, pnum, target, p1sc, p2sc, play):
#a and b are to keep the user aware of min/max
guess = int(input("[%s-%s]%s>> " % (a, b, player)))
play, a, b, target, p1sc, p2sc = guesscheck(guess, target, play,
a, b, p1sc, p2sc)
if pnum == 2:
player = playerswitch(player)
return play, a, b, player, target, p1sc, p2sc

#Let the show begin!
print("WELCOME TO THE SUPER NUMBER GUESSING GAME!")
pnum = int(input("1 OR 2 PLAYERS?\n> "))
play = 1
player = "P1"   # P1 goes first
#Scores, keep track of times player guessed first.
p1sc, p2sc = 0, 0

#Grabs minimum, maximum, and target numbers
a, b, target = setup()

while play == 1:
play, a, b, player, target, p1sc, p2sc \
= guessing(a, b, player, pnum, target, p1sc, p2sc, play)


This is what I have now. It seems to work perfectly, and I tried to
work in your suggestions. Thanks, by the way, for recommending the
style guide. I've bookmarked it, and I'll try to remember to consult
it in the future.

One (extremely minor) annoyance is that if you have only one possible
guess left you still have to type it in manually. As an example,
[30-32]P#>> can only possibly be 31 (and I've changed it so that any
number >= 32 or <= 30 won't be accepted, so it's all the user can
input), which means whatever player is in control has a %100 chance of
winning. I know that "if b - a == 2" would be a simple enough test for
this, but I'm not quite sure when to put it, or what to do with it.

And yes, I'm aware that

guess = int(input("[%s-%s]%s>> " % (a, b, player)))
play, a, b, target, p1sc, p2sc = guesscheck(guess, target, play,
a, b, p1sc, p2sc)

is repeated three times. I will probably try to change this into a
function later on; right now, I just spent a few hours trying to get
this to work and making sure that it does (by playing it), so I'm
going to take a break.
--
http://mail.python.org/mailman/listinfo/python-list


changing string encoding to different charset?

2008-12-14 Thread Daniel Woodhouse
Is it possible to re-encode a string to a different character set in
python?  To be more specific, I want to change a text file encoded in
windows-1251 to UTF-8.
I've tried using string.encode, but get the error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 0:
ordinal not in range(128)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python music sequencer timing problems

2008-12-14 Thread Bad Mutha Hubbard
John O'Hagan wrote:

> On Wed, 10 Dec 2008, badmuthahubbard wrote:
>> I've been trying to get the timing right for a music sequencer using
>> Tkinter.  First I just loaded the Csound API module and ran a Csound
>> engine in its own performance thread.  The score timing was good,
>> being controlled internally by Csound, but any time I moved the mouse
>> I got audio dropouts.
>> It was suggested I run the audio engine as a separate process, with
>> elevated/realtime priority and use sockets to tell it what to play,
>> and that way, too, people could set up servers for the audio on
>> different CPUs.  But I've found that the method I came up with for
>> timing the beats/notes is too slow (using threading.Timer on a
>> function that calls itself over and over), and the whole thing played
>> too slowly (and still gave me noise when moving the mouse).  I've been
>> using subprocesses, but I'm now wondering if sockets would or could
>> make a difference.
>>
>> The overall goal is this: when the user wants to audition a piece,
>> create an audio engine process with elevated/realtime priority.  This
>> engine also has all the synthesis and sound processing rules for the
>> various instruments, due to the way Csound is structured.  Set up a
>> scheduler- possibly in another process, or just another thread- and
>> fill it with all the notes from the score and their times.  Also, the
>> user should be able to see a time-cursor moving across the piece so
>> they can see where they are in the score.  As this last bit is GUI,
>> the scheduler should be able to send callbacks back to the GUI as well
>> as notes to the audio engine.  But neither the scheduler nor the audio
>> engine should wait for Tkinter's updating of the location of the time-
>> cursor.  Naturally, all notes will have higher priorities in the
>> scheduler than all GUI updates, but they won't necessarily always be
>> at the same time.
>>
>> So, I have a few ideas about how to proceed, but I want to know if
>> I'll need to learn more general things first:
>> 1.
>> Create both the scheduler and the audio engine as separate processes
>> and communicate with them through sockets.  When all events are
>> entered in the scheduler, open a server socket in the main GUI process
>> and listen for callbacks to move the cursor (is it possible to do this
>> using Tkinter's mainloop, so the mouse can be moved, albeit
>> sluggishly, at the same time the cursor is moving continuously?); the
>> audio engine runs at as high priority as possible, and the scheduler
>> runs somewhere between that and the priority of the main GUI, which
>> should even perhaps be temporarily lowered below default for good
>> measure.
>>
>> or
>>
>> 2.
>> Create the audio engine as an elevated priority process, and the
>> scheduler as a separate thread in the main process.  The scheduler
>> sends notes to the audio engine and callbacks within its own process
>> to move the GUI cursor.  Optionally, every tiny update of the cursor
>> could be a separate thread that dies an instant later.
>>
>> 3.
>> Closer to my original idea, but I'm hoping to avoid this.  All note
>> scheduling and tempo control is done by Csound as audio engine, and a
>> Csound channel is set aside for callbacks to update the cursor
>> position.  Maybe this would be smoothest, as timing is built into
>> Csound already, but the Csound score will be full of thousands of
>> pseudo-notes that only exist for those callbacks.  Down the road I'd
>> like to have notes sound whenever they are added or moved on the
>> score, not just when playing the piece, as well as the option of
>> adjusting the level, pan, etc. of running instruments.
>>
>
> Hi Chuckk,
>
> I've recently been fooling with something involving timing and synchronising 
> multiple note-on/note-off events, and also tried threading and subprocesses 
> without much success - out of the box, the high-tempo precision wasn't there.
>
> But I had more luck with this approach, if it's not way too simple for your 
> purpose (I'm not using a gui, for example); in psuedocode:
>
> from time import time, sleep
>
> start = time()
> for event in music:
> duration=len(event) #Really, the length of the event
> play(event)
> while 1:
> timer = time()
> remaining = start + duration - timer
> if remaining < 0.001:
> break
> else:
> sleep(remaining / 2)
> stop(event)
> start += duration
>
> IOW, just check the time, wait half the remaining note duration, check the 
> time again, etc, till you've reached your desired precision level (in this 
> case 0.001 sec). The halving of each succesive sleep() means that there is 
> only a handful of calls to time() per note, 5-10 depending on the tempo. (Of 
> course it could be any fraction, I just pulled that out of a hat; it would 
> probably be better too if the fraction decremented as the deadline 
> approached). 
>
> Even with this naive algorithm, I'm getting accuracy o

Re: changing string encoding to different charset?

2008-12-14 Thread Philip Semanchuk


On Dec 14, 2008, at 9:21 AM, Daniel Woodhouse wrote:


Is it possible to re-encode a string to a different character set in
python?  To be more specific, I want to change a text file encoded in
windows-1251 to UTF-8.
I've tried using string.encode, but get the error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position  
0:

ordinal not in range(128)


Without seeing your code, I can't be sure, but I suspect that first  
you need to decode the file to Unicode.


# Untested --
s = file("in.txt").read()

s = s.decode("win-1251") # Might be "cp1251" instead

assert(isinstance(s, unicode))

s = s.encode("utf-8")

file("out.txt", "w").write(s)


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


Re: 1 or 1/0 doesn't raise an exception

2008-12-14 Thread Grant Edwards
On 2008-12-14, Daniel Fetchinson  wrote:

> Let me just point out that unsuspecting people (like me) might rely on
> the whole expression to be evaluated and rely on exceptions being
> raised if needed.

Short circuit evaluation of booleans is very common (and has
been for decades), so I don't know why people would expect
something else.

-- 
Grant

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


Re: 1 or 1/0 doesn't raise an exception

2008-12-14 Thread MRAB

Rohannes wrote:

'Dive into Python' has a very memorable and interesting section on the
exact behaviour of 'and' and 'or' in Python:

http://diveintopython.org/power_of_introspection/and_or.html


No: &, | (and ^, too) perform bitwise operations in Python, C and Java:


"In complete evaluation ... both expressions are always evaluated. To
obtain complete evaluation in Java, you use & rather than && ... and
use | in place of ||" - Walter Savitch, Absolute Java 2nd ed.

Although & IS the bitwise-AND operator in Java:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html

I guess it's a matter of context.

Java has a bool type that's distinct from the int type. &, | and ^ are 
bitwise for int and Boolean for bool, and in both cases they are strict. 
&& and || are for bool only and they are lazy.


In Pascal the behaviour of "and" and "or" is implementation-dependant...
--
http://mail.python.org/mailman/listinfo/python-list


execution time

2008-12-14 Thread David Hláčik
Hi guys,

#! /usr/bin/python

import random
import bucket2

data = [ random.randint(1,25) for i in range(5)]
print "random data : %s" % data
print "result: %s" %bucket2.sort(data)

How to write a test script which will outputs execution time for
bucket2.sort(data) ?

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


Looking for the best way to translate an idiom

2008-12-14 Thread Paul Moore
I'm translating some code from another language (Lua) which has
multiple function return values. So, In Lua, it's possible to define a
function

function f()
return 1,2,3
end

which returns 3 values. These can then be used/assigned by the caller:

a,b,c = f()

So far, much like Python, but the key difference is that in Lua,
excess arguments are ignored - so you can do

a = f()
or even
a = f() + 1

where in the latter, a is 2 (as addition only needs 1 argument, so the
extra ones are discarded).

This results in the code which I'm trying to translate having
functions which return multiple arguments, the first of which is the
"main" result, and the following values are "extra" results
(specifically, the position at which a match is found, followed by the
"captured" values of the match).

I'm trying to find a natural equivalent in Python. So far, I've
considered the following:

- return a tuple (pos, captures). This is messy, because you end up
far too often unpacking the tuple and throwing away the second value
- return an object with pos and captures attributes. This is better,
as you can do match(...).pos to get the position alone, but it doesn't
really feel "pythonic" (all those calls with .pos at the end...)
- have 2 calls, one to return just the position, one to return both.
This feels awkward, because of the 2 method names to remember.

To make things worse, Lua indexes strings from 1, so it can use a
position of 0 to mean "no match" - so that a simple "did it match?"
test looks like if (match())... - where in Python I need if
(matchpos(...) != -1)... (Although if I return a match object, I can
override __nonzero__ to allow me to use the simpler Lua form).

Can anyone suggest a good idiom for this situation? At the moment, I'm
returning a match object (the second option) which seems like the
least bad of the choices (and it mirrors how the re module works,
which is somewhat useful). But I'd like to know what others think. If
you were using a pattern matching library, what interface would you
prefer?

I suspect my intuition isn't accurate here, as most of the use I've
made of the library is in writing tests, which isn't typical use :-(

Thanks for any assistance.

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


Re: 1 or 1/0 doesn't raise an exception

2008-12-14 Thread Mel
Daniel Fetchinson wrote:
[ ... ]
> Let me just point out that unsuspecting people (like me) might rely on
> the whole expression to be evaluated and rely on exceptions being
> raised if needed.

There are a lot of threads on comp.lang.python that mention beginners'
possible reactions to language features, so I'll mention this paper
relating to teaching programming:

. 
 
The early draft which I've read,

,

references quite a lot of literature on what new programmers do, discusses a
new test for programming aptitude.

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


Re: 1 or 1/0 doesn't raise an exception

2008-12-14 Thread Peter Otten
Grant Edwards wrote:

> Short circuit evaluation of booleans is very common (and has
> been for decades), so I don't know why people would expect
> something else.

Visual Basic ;) 

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


Re: 1 or 1/0 doesn't raise an exception

2008-12-14 Thread Benjamin Kaplan
On Sun, Dec 14, 2008 at 2:38 AM, Gabriel Genellina
wrote:

> En Sun, 14 Dec 2008 02:40:10 -0200, Benjamin Kaplan
>  escribió:
>
>  On Sat, Dec 13, 2008 at 10:49 PM, Daniel Fetchinson <
>> fetchin...@googlemail.com> wrote:
>>
>>  >> Is it a feature that
>>> >>
>>> >> 1 or 1/0
>>> >>
>>> >> returns 1 and doesn't raise a ZeroDivisionError? If so, what's the
>>> >> rationale?
>>> >
>>> > http://en.wikipedia.org/wiki/Short-circuit_evaluation
>>>
>>> Let me just point out that unsuspecting people (like me) might rely on
>>> the whole expression to be evaluated and rely on exceptions being
>>> raised if needed.
>>>
>>
>> If you want both expressions evaluated, you can use & and |, just like in
>> C
>> and Java (&& and || are used for short circuit evaluation in those
>> languages).
>>
>
> No: &, | (and ^, too) perform bitwise operations in Python, C and Java:
>

Perhaps I should have mentioned that you have to restrict yourself to bools
(or 0 and 1) when doing this. I know that they perform bitwise operations
when you do them with ints- I was assuming the OP was dealing with bools.

>
> py> 1 & 2
> 0
>
> && and || --in both C and Java-- are like `and` and `or` in Python; they
> perform logical operations, and short-circuit evaluation of their operands.
> If you want to evaluate a logical expression without short circuiting, do
> that explicitely:
>
> a = first part
> b = second part
> if a or b: ...
>

> --
> Gabriel Genellina
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for the best way to translate an idiom

2008-12-14 Thread Bruno Desthuilliers

Paul Moore a écrit :

I'm translating some code from another language (Lua) which has
multiple function return values. So, In Lua, it's possible to define a
function

function f()
return 1,2,3
end

which returns 3 values. These can then be used/assigned by the caller:

a,b,c = f()

So far, much like Python, but the key difference is that in Lua,
excess arguments are ignored - so you can do

a = f()
or even
a = f() + 1

where in the latter, a is 2 (as addition only needs 1 argument, so the
extra ones are discarded).

This results in the code which I'm trying to translate having
functions which return multiple arguments, the first of which is the
"main" result, and the following values are "extra" results
(specifically, the position at which a match is found, followed by the
"captured" values of the match).

I'm trying to find a natural equivalent in Python. So far, I've
considered the following:

- return a tuple (pos, captures). This is messy, because you end up
far too often unpacking the tuple and throwing away the second value


if you only want the first returned value, you can just apply a slice:

def f():
   return 1,2,3

a = f()[0] + 1


- return an object with pos and captures attributes. This is better,
as you can do match(...).pos to get the position alone, but it doesn't
really feel "pythonic" (all those calls with .pos at the end...)


FWIW, Python 2.6 has NamedTuple objects...


- have 2 calls, one to return just the position, one to return both.
This feels awkward, because of the 2 method names to remember.


You forgot one solution: passing a flag to the function to specify if 
you want only the main result or the extra ones as well, and give this 
flag the appropriate default value depending on most common use case.



To make things worse, Lua indexes strings from 1, so it can use a
position of 0 to mean "no match" - so that a simple "did it match?"
test looks like if (match())... - where in Python I need if
(matchpos(...) != -1)... (Although if I return a match object, I can
override __nonzero__ to allow me to use the simpler Lua form).

Can anyone suggest a good idiom for this situation? At the moment, I'm
returning a match object (the second option) which seems like the
least bad of the choices (and it mirrors how the re module works,
which is somewhat useful). But I'd like to know what others think. If
you were using a pattern matching library, what interface would you
prefer?


The one that happens to be the most simple for the most common usecase, 
while still providing support for more advanced stuff.



I suspect my intuition isn't accurate here, as most of the use I've
made of the library is in writing tests, which isn't typical use :-(


So perhaps you should start writing some real-life code ?


Thanks for any assistance.


Not sure I've been that helpful. Sorry...
--
http://mail.python.org/mailman/listinfo/python-list


Re: execution time

2008-12-14 Thread Bruno Desthuilliers

David Hláčik a écrit :

Hi guys,

#! /usr/bin/python

import random
import bucket2

data = [ random.randint(1,25) for i in range(5)]
print "random data : %s" % data
print "result: %s" %bucket2.sort(data)

How to write a test script which will outputs execution time for
bucket2.sort(data) ?


http://docs.python.org/library/timeit.html

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


Re: 1 or 1/0 doesn't raise an exception

2008-12-14 Thread Bruno Desthuilliers

Grant Edwards a écrit :

On 2008-12-14, Daniel Fetchinson  wrote:


Let me just point out that unsuspecting people (like me) might rely on
the whole expression to be evaluated and rely on exceptions being
raised if needed.


Short circuit evaluation of booleans is very common (and has
been for decades), so I don't know why people would expect
something else.

Because they either have no previous programming experience, or only 
experience with one of the few languages that don't do short-circuit 
evaluation ?



You can consider that short-circuit is the norm and it's absence the 
exception.


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


Re: Need help improving number guessing game

2008-12-14 Thread Bruno Desthuilliers

feba a écrit :

#!/usr/bin/python
#Py3k, UTF-8

import random

def startup():
print("WELCOME TO THE SUPER NUMBER GUESSING GAME!")
global pnum, play, player, p1sc, p2sc


You should now try to rewrite the whole thing to avoid using globals.


pnum = int(input("1 OR 2 PLAYERS?\n> "))


What happens here if you type something that's not a valid argument for 
int() ?


(snip)
--
http://mail.python.org/mailman/listinfo/python-list


Deepcopying slice objects

2008-12-14 Thread Max Argus
I stumbled across a thread about that suggests fixing deepcopy to let it
copy slice objects. (
http://mail.python.org/pipermail/python-list/2006-August/398206.html). I
expected this to work and don't see any reason why it shouldn't in case
there is a good reason why it dosen't work can someone please explain it.

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


Re: execution time

2008-12-14 Thread Andreas Kostyrka
On Sun, Dec 14, 2008 at 05:03:38PM +0100, David Hláčik wrote:
> Hi guys,
> 
> #! /usr/bin/python
> 
> import random
> import bucket2
> 
> data = [ random.randint(1,25) for i in range(5)]
> print "random data : %s" % data
> print "result: %s" %bucket2.sort(data)
> 
> How to write a test script which will outputs execution time for
> bucket2.sort(data) ?

Well:

import time

starttime = time.time()



endtime = time.time()
print "Whatever  does, it took %5.3fs to do." % (endtime - starttime)

Alternativly take a look at the timeit standard module.

Andreas

> 
> Thanks in advance!
> --
> http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for the best way to translate an idiom

2008-12-14 Thread Paul Moore
On 14 Dec, 16:22, Bruno Desthuilliers
 wrote:
> if you only want the first returned value, you can just apply a slice:
>
> def f():
>     return 1,2,3
>
> a = f()[0] + 1

Hmm, true. I'm not sure it's any less ugly, though :-)

> FWIW, Python 2.6 has NamedTuple objects...

I know, but I want to target 2.5+ (I still have a number of systems
running 2.5)

> > - have 2 calls, one to return just the position, one to return both.
> > This feels awkward, because of the 2 method names to remember.
>
> You forgot one solution: passing a flag to the function to specify if
> you want only the main result or the extra ones as well, and give this
> flag the appropriate default value depending on most common use case.

True, that's another option. It might work, I'll think about it.

> The one that happens to be the most simple for the most common usecase,
> while still providing support for more advanced stuff.

Exactly. I'll have to think some more about real use cases.

> > I suspect my intuition isn't accurate here, as most of the use I've
> > made of the library is in writing tests, which isn't typical use :-(
>
> So perhaps you should start writing some real-life code ?

:-) Once I have a library that's functional enough to do so, I may
well. Chicken and egg situation, to some extent... And I don't really
feel like switching to Lua just to get a feel for how the library gets
used!

> > Thanks for any assistance.
>
> Not sure I've been that helpful. Sorry...

Any feedback helps. Thanks for taking the time.

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


Re: Looking for the best way to translate an idiom

2008-12-14 Thread Steve Holden
Bruno Desthuilliers wrote:
[...]
> if you only want the first returned value, you can just apply a slice:
> 
> def f():
>return 1,2,3
> 
> a = f()[0] + 1
> 
That isn't a slice, it's indexing

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Need help improving number guessing game

2008-12-14 Thread Bruno Desthuilliers

feba a écrit :

#!/usr/bin/python
#Py3k, UTF-8

import random

def setup():
#global target, guess, a, b
#a, b make minimum, maximum. Can be adjusted.
a, b = 1, 99
target = random.randint(a, b)
return a, b, target


Seems ok. You may want to use arguments with default values for a and b 
(and possibly to use more meaningfull names):


def setup(mini=1, maxi=99)
   # sanity check
   if mini >= maxi:
  raise ValueError("mini must be lower than maxi")
   target = random.randint(mini, maxi)
   return mini, maxi, target


def playerswitch(player):
#Player Switch
#if player's a witch, burn her!


Extra bonus point for quoting Monty Pythons !-)


if player == "P1":
player = "P2"
else:
player = "P1"
return player



I'd name this one "switch_player" (most of the time, function names 
should be verbs) - but this is mostly a matter of personal taste !-)


Minor point for a short program, but still good practice : use 
constants. IE :


# at the top level
PLAYER_1 = 1
PLAYER_2 = 2

# in your code

   if player == PLAYER_1:
...


Also, you could use early returns here instead of rebinding then 
returning player.


def switch_player(player):
if player == PLAYER_1:
return PLAYER_2
else:
return PLAYER_1


def youwin(pnum, player, p1sc, p2sc):


I assume 'p1sc' means "player_1_score" ?

If so, you may want to use a dict for scores:

   scores = {PLAYER_1:0, PLAYER_2:0}

then...


if pnum == 1:
print("CONGRATULATIONS!")


Is it really necessary to WRITE THIS IN ALL UPPERS ?-)


else:
if player == "P1":
p1sc += 1
else:
p2sc += 1


Which would then become:
  scores[player] +=1


end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s"
print(end %(player, p1sc, p2sc))
return p1sc, p2sc




def playagain(play):
playover = input("PLAY AGAIN? Y/N: ")
if playover.strip().lower() == "y":
play = 1 


If it's meant to be 0/1 flag, Python has proper booleans too (True and 
False).



a, b, target = setup()
else:
print("GOOD BYE. PLAY AGAIN SOON!")
quit()


It might be better to avoid exiting so brutally. Why not returning 0, 
none, None, None ?



return play, a, b, target


def guesscheck(guess, target, play, a, b, p1sc, p2sc):
if guess == target:
p1sc, p2sc = youwin(pnum, player, p1sc, p2sc)
play, a, b, target = playagain(play)
elif guess >= b:
print("NUMBER MUST BE IN RANGE")
guess = int(input("[%s-%s]%s>> " % (a, b, player)))
play, a, b, target, p1sc, p2sc = guesscheck(guess, target,
play,
a, b, p1sc, p2sc)
elif guess <= a:
print("NUMBER MUST BE IN RANGE")
guess = int(input("[%s-%s]%s>> " % (a, b, player)))
play, a, b, target, p1sc, p2sc = guesscheck(guess, target,
play,
a, b, p1sc, p2sc)
elif guess > target:
print("TOO HIGH")
b = guess
else:
print("TOO LOW")
a = guess
return play, a, b, target, p1sc, p2sc

def guessing(a, b, player, pnum, target, p1sc, p2sc, play):
#a and b are to keep the user aware of min/max
guess = int(input("[%s-%s]%s>> " % (a, b, player)))
play, a, b, target, p1sc, p2sc = guesscheck(guess, target, play,
a, b, p1sc, p2sc)
if pnum == 2:
player = playerswitch(player)
return play, a, b, player, target, p1sc, p2sc

#Let the show begin!


You should either put this in it's own function (could be named 'main'), 
or at least "protect" it with an "if __name__ == '__main__':" test.



print("WELCOME TO THE SUPER NUMBER GUESSING GAME!")
pnum = int(input("1 OR 2 PLAYERS?\n> "))
play = 1
player = "P1"   # P1 goes first
#Scores, keep track of times player guessed first.
p1sc, p2sc = 0, 0

#Grabs minimum, maximum, and target numbers
a, b, target = setup()

while play == 1:
play, a, b, player, target, p1sc, p2sc \
= guessing(a, b, player, pnum, target, p1sc, p2sc, play)


This is what I have now.


And it looks way better than your first version.

(snip)
--
http://mail.python.org/mailman/listinfo/python-list


Limit traceback from most recent call

2008-12-14 Thread Brian Allen Vanderburg II
I've looked at traceback module but I can't find how to limit traceback 
from the most recent call if it is possible.  I see that extract_tb has 
a limit parameter, but it limits from the start and not the end.  
Currently I've made my own traceback code to do this but wonder if 
python already has a way to do this build in:


def format_partial_exc(limit=None):

   (type, value, tb) = sys.exc_info()

   items = traceback.extract_tb(tb)

   if limit:

   items = items[-limit:] # Get last 'limit' items and not first

   result = 'Traceback (most recent call last):\n'

   items = traceback.format_list(items)

   for i in items:

   result += i # Newline already included

   result += type.__name__ + ': ' + str(value)

   return result 



Is this possible currently from traceback or other python module?

Brian A. Vanderburg II
--
http://mail.python.org/mailman/listinfo/python-list


Re: curses and refreshing problem

2008-12-14 Thread Carl Banks
On Dec 14, 5:52 am, Karlo Lozovina <_kar...@_mosor.net_> wrote:
> Carl Banks  wrote 
> innews:69d2698a-6f44-4d85-adc3-1180ab158...@r15g2000prd.googlegroups.com:
>
> > Unless you are referring to some wget screen mode I don't know about,
> > I suspect wget outputs its progress bar using carriage returns
> > without newlines.  If that's all you want, there is no need to use
> > curses.
>
> > Here is a little example program to illustrate:
>
> > import time, sys
> > for i in range(21):
> >     sys.stdout.write('\rProgress: [' + '='*i + ' '*(20-i) + ']')
> >     sys.stdout.flush()
> >     time.sleep(1)
> > sys.stdout.write("\nFinised!\n")
>
> Thanks, that's it! I just assumed wget uses curses for the progress bar,
> so the carriage return didn't even cross my mind ;).


Sure.  One other thing I'd like to point out is sometimes even if
carriage return is not sufficient, you can get a little better control
of the terminal by using escape sequences (quod Google).  The more
basic Xterm escape sequences work in pretty much any Unix-like
environment you'd see these days, some might even work on a Windows
terminal.  For example, print "\033[2J\033[H" probably clears your
screen and moves the cursor to top.


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


Re: Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-14 Thread Paul Boddie
On 14 Des, 05:46, "Martin v. Löwis"  wrote:
>
> Yes. If you want a display that is guaranteed to work on your terminal,
> use the ascii() builtin function.

But shouldn't the production of an object's representation via repr be
a "safe" operation? That is, the operation should always produce a
result, regardless of environmental factors like the locale or
terminal's encoding support. If John were printing the object, it
would be a different matter, but he apparently just wants to see a
sequence of characters which represents the object.

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


Building from source -- zlib/binascii problems 2.5.2/2.6.1

2008-12-14 Thread peter s.
I am trying to build Python from source on a RHEL system where I do
not have root access.  There are two modules that I am having trouble
with: zlib & binascii.

zlib -- This seems like a make configuration issue.  I have noticed
that 'gcc -v' returns '--with-system-zlib':
$ gcc -v
Using built-in specs.
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --
infodir=/usr/share/info --enable-shared --enable-threads=posix --
enable-checking=release --with-system-zlib --enable-__cxa_atexit --
disable-libunwind-exceptions --enable-libgcj-multifile --enable-
languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk --
disable-dssi --enable-plugin --with-java-home=/usr/lib/jvm/java-1.4.2-
gcj-1.4.2.0/jre --with-cpu=generic --host=x86_64-redhat-linux
Thread model: posix
gcc version 4.1.2 20071124 (Red Hat 4.1.2-42)

and then when I run 'make' I see:

building 'zlib' extension
gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -
Wstrict-prototypes -I. -I/location/of/Python-2.5.2/./Include -I. -
IInclude -I./Include -I/usr/local/include -I/location/of/Python-2.5.2/
Include -I/location/of/Python-2.5.2 -c /location/of/Python-2.5.2/
Modules/zlibmodule.c -o build/temp.linux-x86_64-2.5/location/of/
Python-2.5.2/Modules/zlibmodule.o
gcc -pthread -shared build/temp.linux-x86_64-2.5/location/of/
Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/
lib.linux-x86_64-2.5/zlib.so
/usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for
-lz
/usr/bin/ld: skipping incompatible /usr/lib/libz.a when searching for -
lz
/usr/bin/ld: cannot find -lz
collect2: ld returned 1 exit status

It seems as though I need to force the build process to use the zlib
that comes with python source.

binascii -- I have no idea what binascii requires in order to compile,
so I am clueless.  It properly compiles with 2.5.2, but fails to build
in 2.6.1.  I am OK using 2.5.2 if I could get zlib to work.

Thanks,

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


Re: Shorter tracebacks

2008-12-14 Thread Peter Otten
Peter Otten wrote:

> That's none of __future__'s business, I think. Python offers a hook which
> you can modify:
> 
 import sys, traceback
 from functools import partial
 sys.excepthook = partial(traceback.print_exception, limit=5)

I just stumbled upon

>>> import sys
>>> sys.tracebacklimit
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute 'tracebacklimit'
>>> sys.tracebacklimit = 2
>>> def f(): f()
...
>>> f()
Traceback (most recent call last):
  File "", line 1, in f
  File "", line 1, in f
RuntimeError: maximum recursion depth exceeded

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


Re: Why %e not in time.strftime directives?

2008-12-14 Thread Tim Chase

Any special reasons?

Because it is there (at least on my Debian box)?


But not on windows :(

import time
time.strftime("%e")

''


Guess you'll have to take it up with the authors of strftime() at 
Microsoft :)



 The full set of format codes supported varies across
 platforms, because Python calls the platform C library's
 strftime() function, and platform variations are common.

So if your underlying C implementation of strftime() supports "%e", then
Python will.  My guess is that the same applies to time.strftime as it does
to datetime.strftime

The docs list ones that are fairly cross-platform.  However, it would seem
that not all platforms support "%e"


If you don't have any luck convincing Microsoft to add "%e" to 
their strftime implementation, you can use


  strftime('%d').lstrip('0').rjust(2)

to replicate the desired behavior :)

-tkc



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


package structure?

2008-12-14 Thread Torsten Mohr
Hi,

in a package i'd like to have a structure like this:

Files end with ".py", others are directories:

mod
  __init__.py   # sets __all__ = ['smod1']
  smod1.py  # contains AClass()
  smod1
__init__.py # sets __all__ = ['abc', 'def']
abc.py
def.py

So i can now do:

import mod.smod1.abc
import mod.smod1


But functions/classes in smod1.py are not found:

a = mod.smod1.AClass()

I know this is somehow ambiguous, but i wonder how else i can make
"mod" have subpackages and modules.

I wonder how i can make AClass() known in that package.


Thanks for any hints,
Torsten.

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


Re: Looking for the best way to translate an idiom

2008-12-14 Thread Bruno Desthuilliers

Steve Holden a écrit :

Bruno Desthuilliers wrote:
[...]

if you only want the first returned value, you can just apply a slice:

def f():
   return 1,2,3

a = f()[0] + 1


That isn't a slice, it's indexing


Yeps, sorry - and thanks for the correction.
--
http://mail.python.org/mailman/listinfo/python-list


Re: package structure?

2008-12-14 Thread Benjamin Kaplan
On Sun, Dec 14, 2008 at 3:16 PM, Torsten Mohr  wrote:

> Hi,
>
> in a package i'd like to have a structure like this:
>
> Files end with ".py", others are directories:
>
> mod
>  __init__.py   # sets __all__ = ['smod1']
>  smod1.py  # contains AClass()
>  smod1
>__init__.py # sets __all__ = ['abc', 'def']
>abc.py
>def.py
>
> So i can now do:
>
> import mod.smod1.abc
> import mod.smod1
>
>
> But functions/classes in smod1.py are not found:
>
> a = mod.smod1.AClass()
>
> I know this is somehow ambiguous, but i wonder how else i can make
> "mod" have subpackages and modules.
>
> I wonder how i can make AClass() known in that package.
>

You have two modules named smod1- one of them uses the code in smod1.py, the
other one is in smod1/__init__.py. The second one hides the first. Python
doesn't let you have two modules with the same name. You have to either
rename one of the smod1's or define AClass in smod1/__init__.py instead.


>
>
> Thanks for any hints,
> Torsten.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: package structure?

2008-12-14 Thread Arnaud Delobelle
Torsten Mohr  writes:

> Hi,
>
> in a package i'd like to have a structure like this:
>
> Files end with ".py", others are directories:
>
> mod
>   __init__.py   # sets __all__ = ['smod1']
>   smod1.py  # contains AClass()
>   smod1
> __init__.py # sets __all__ = ['abc', 'def']
> abc.py
> def.py
>
> So i can now do:
>
> import mod.smod1.abc
> import mod.smod1
>
>
> But functions/classes in smod1.py are not found:
>
> a = mod.smod1.AClass()
>
> I know this is somehow ambiguous, but i wonder how else i can make
> "mod" have subpackages and modules.
>
> I wonder how i can make AClass() known in that package.
>
>
> Thanks for any hints,
> Torsten.

Why don't you put the contents of smod1.py in mod/smod1/__init__.py?
It'll work this way.  Or you can put smod1.py within mod/smod1 and put

from smod1 import *

in mod/smod1/__init__.py

HTH

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


Re: package structure?

2008-12-14 Thread Torsten Mohr
>> I wonder how i can make AClass() known in that package.
>>
> 
> Why don't you put the contents of smod1.py in mod/smod1/__init__.py?
> It'll work this way.

Of course, thanks for that hint.


Best regards,
Torsten.

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


Re: [OT] stable algorithm with complexity O(n)

2008-12-14 Thread David Hláčik
Thank you guys for help and support!  My homework is done and waiting
for grading.

Here it comes - bucket sort with time complexity O(n) == linear complexity

#! /usr/bin/python
def sort(numbers):
"sort n positive integers in O(n) provided that they are all from
interval [1, n^2]"
N = len(numbers) # get size of test numbers

buckets_mod = [[] for i in xrange(N)]
buckets_sorted = [[] for i in xrange(N+1)]

# group numbers to buckets (list of numbers) with common modulus
for n in numbers:
buckets_mod[n % N].append(n)
print "buckets_mod: %s" % buckets_mod

# check numbers in buckets
for l in buckets_mod:
for n in l:
# place number into bucket number grouped by result of 
division
buckets_sorted[n / N].append(n)
print "buckets_sorted: %s" % buckets_sorted

# search through sorted buckets and return list of sorted numbers
return [n for l in buckets_sorted for n in l]

Regards,

David

On Sun, Dec 14, 2008 at 11:24 AM, Arnaud Delobelle
 wrote:
> Steven D'Aprano  writes:
>
>> On Sat, 13 Dec 2008 19:17:41 +, Duncan Booth wrote:
>>
>>> I think you must have fallen asleep during CS101. The lower bound for
>>> sorting where you make a two way branch at each step is O(n * log_2 n),
>>> but if you can choose between k possible orderings in a single
>>> comparison you can get O(n * log_k n).
>>
>> I think you might have been sleeping through Maths 101 :-)
>>
>> The difference between log_2 N and log_k N is a constant factor (log_2 k)
>> and so doesn't effect the big-oh complexity.
>
> It affects it if k is a function of n.  In this particular example, we
> can set k=n so we get O(n).
>
> --
> Arnaud
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-14 Thread Martin v. Löwis
> But shouldn't the production of an object's representation via repr be
> a "safe" operation?

It's a trade-off. It should also be legible.

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


Re: Bidirectional Networking

2008-12-14 Thread Gabriel Genellina
En Sun, 14 Dec 2008 11:00:18 -0200, Emanuele D'Arrigo   
escribió:



On Dec 14, 4:10 am, "Gabriel Genellina" 
wrote:
daemon became a property in Python 2.6; setDaemon was the only way to  
set

it in previous versions.


I thought that might be the case! The documentation is a bit vague:

http://docs.python.org/library/threading.html?highlight=threading#threading.Thread.setDaemon

Should we maybe add "New in 2.6" to the Thread.daemon paragraph?


That would be a nice addition, but if you are using Python 2.5, you should  
read the 2.5 version of the docs:  
http://www.python.org/doc/2.5.2/lib/thread-objects.html


--
Gabriel Genellina

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


Output to file gets lost - don't know where to look ...

2008-12-14 Thread uair01
I'm running python in IDLE on suse11.

I have a python program and after writing 100kB to 200kB to a file,
the write statements seem to stop working.
Basically the print statements look like this:

some loops:
logFile.write(string1)
logFile.write(string2)
end of loops

print(stringA)
logFile.write(string3)
logFile.write(string4)
print(stringB)

String1 and sometimes string2 / string3 (or a part of it) will end up
in the file, but string4 not.
stringsA and stringB get printed to the concole as expected.

Stepping through the program with a debugger shows that *all* write-
statements get executed.

I use several logFile.flush() statements and a logFile.close() at the
end.

Is there some kind of file-size-limit or some kind of memory or buffer
problem? Or could it be a bug in IDLE? I don't know where to look
further.

OH ... maybe just writing this message has helped. Now I see the
following error messages inside the window from where I started IDLE.
Could that be the cause?

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1403, in __call__
return self.func(*args)
  File "/usr/lib/python2.5/idlelib/MultiCall.py", line 151, in handler
r = l[i](event)
  File "/usr/lib/python2.5/idlelib/CallTips.py", line 62, in
refresh_calltip_event
self.open_calltip(False)
  File "/usr/lib/python2.5/idlelib/CallTips.py", line 65, in
open_calltip
self._remove_calltip_window()
  File "/usr/lib/python2.5/idlelib/CallTips.py", line 41, in
_remove_calltip_window
self.calltip.hidetip()
  File "/usr/lib/python2.5/idlelib/CallTipWindow.py", line 126, in
hidetip
self.label.destroy()
AttributeError: 'NoneType' object has no attribute 'destroy'

I will try the python program outside of IDLE.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] stable algorithm with complexity O(n)

2008-12-14 Thread Lie Ryan
On Sat, 13 Dec 2008 19:17:41 +, Duncan Booth wrote:

> "Diez B. Roggisch"  wrote:
> 
>> David Hláčik schrieb:
>>> Hi guys,
>>> 
>>> i am really sorry for making offtopic, hope you will not kill me, but
>>> this is for me life important problem which needs to be solved within
>>> next 12 hours..
>>> 
>>> I have to create stable algorithm for sorting n numbers from interval
>>> [1,n^2] with time complexity O(n) .
>>> 
>>> Can someone please give me a hint. Would be very very thankful!
>> 
>> Unless I grossly miss out on something in computer science 101, the
>> lower bound for sorting is O(n * log_2 n). Which makes your task
>> impossible, unless there is something to be assumed about the
>> distribution of numbers in your sequence.
>> 
>> Who has given you that assignment - a professor? Or some friend who's
>> playing tricks on you?
>> 
> I think you must have fallen asleep during CS101. The lower bound for
> sorting where you make a two way branch at each step is O(n * log_2 n),
> but if you can choose between k possible orderings in a single
> comparison you can get O(n * log_k n).
> 
> To beat n * log_2 n just use a bucket sort: for numbers with a known
> maximum you can sort them digit by digit for O(n log_k n), and if you
> don't restrict yourself to decimal then k can be as large as you want,
> so for the problem in question I think you can set k=n and (log_n n)==1
> so you get O(n)
> 

I'm sure someday, there will be a student who comes to class late and 
sees this on the board: "Design a comparison sorting algorithm that has 
better than O(n * log n) lower bound complexity." The unsuspecting 
student copied it, thinking it's a homework. He crunched to the problem, 
going to various meditations and yoga classes before finding a way that 
works just before deadline, handing out the work a bit late. Six weeks 
later, his professor called and said: "You know what you just did? You've 
just found a problem that was supposed to be an example of unsolvable 
problem."

It has happened before, why not again? 
http://www.snopes.com/college/homework/unsolvable.asp

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


Re: Bidrectional Subprocess Communication

2008-12-14 Thread Gabriel Genellina
En Sun, 14 Dec 2008 09:37:38 -0200, Emanuele D'Arrigo   
escribió:



On Dec 14, 4:48 am, "Gabriel Genellina" 
wrote:

- you have to close server.stdin when you don't have more data to send.
The server will see an end-of-file and knows it has to exit the loop.
Same thing on the client side.


Hi Gabriel, thanks for modifying the code to make it work. I've just
tried tinkering with it to see how far it would go. On your two
statements above: does this means that any data must be sent in one
batch and then the subprocess must shut down? What I was trying to
simulate is a client/server relationship through a subprocess, where
the server (the subprocess) keeps listening and the client sends data
when it wants to (and eventually viceversa). But when the
server.stdin.close() statement is issued, the pipe is closed for good
and can't be reopened (can it?).


No, not at all. You can keep writing things to the pipe - as long as the  
read side keeps reading, there is no limit on how much data you can send.
Just make sure you close the writing side of the pipe when you have no  
more data to send, to signal the other side it's OK to exit the read loop.



- you have to wait until the server answers, else it will get a "broken
pipe" error or similar.


So, if I want to interrogate the subprocess multiple times I must end
and restart the ListenerThread multiple times then?


No, I mean, since your example is bidirectional, the parent process must  
still be alive and able to read when the subprocess replies. Given this  
sequence:


parent writes "hi sub!"
child reads "hi sub!"
child writes "hi dad!"
parent reads "hi dad!"

if the parent just exits after sending "hi sub!", the child will get an  
error when replying (I think it says "invalid handle" on Windows, "broken  
pipe" on Linux, or something like this).


--
Gabriel Genellina

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


Re: Optimizing methods away or not?

2008-12-14 Thread Terry Reedy

Steven D'Aprano wrote:
I have a class with a method meant to verify internal program logic (not 
data supplied by the caller). Because it is time-consuming but optional, 
I treat it as a complex assertion statement, and optimize it away if 
__debug__ is false:


class Parrot:
def __init__(self, *args):
print "Initialising instance..."
if __debug__:
self.verify()  # check internal program state, not args
if __debug__:
def verify(self):
print "Verifying..."


Given that verify is only called from within _init__, I would put 
everything within one 'if __debug__' statement.  Either inline


if __debug__:


or if for some reason you really don't like that, nested

if __debug__:
   def verify():
  print "Verifying..."
   verify()

tjr

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


Re: Output to file gets lost - don't know where to look ...

2008-12-14 Thread uair01
> I will try the python program outside of IDLE.

Yes, running the program from the Linux shell instead of from IDLE
produces all output correctly.
Now I'll have to look for a new simple development environment :-(
I think I'll try SPE that has worked well for me ...

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


Re: Building from source -- zlib/binascii problems 2.5.2/2.6.1

2008-12-14 Thread Martin v. Löwis
> Target: x86_64-redhat-linux
> gcc -pthread -shared build/temp.linux-x86_64-2.5/location/of/
> Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/
> lib.linux-x86_64-2.5/zlib.so
> /usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for
> -lz

Do

  file /usr/lib/libz.so

It might be a 32-bit library, in which case you can check whether
/usr/lib64 has a 64-bit library. I'm puzzled why it only
happens for -lz; perhaps you are better of compiling with a 32-bit
compiler.

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


Re: the official way of printing unicode strings

2008-12-14 Thread J. Clifford Dyer
On Sun, 2008-12-14 at 11:16 +0100, Piotr Sobolewski wrote:
> Marc 'BlackJack' Rintsch wrote:
> 
> > I'd make that first line:
> > sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
> > 
> > Why is it even more cumbersome to execute that line *once* instead
> > encoding at every ``print`` statement?
> 
> Oh, maybe it's not cumbersome, but a little bit strange - but sure, I can
> get used to it. 
> 
> My main problem is that when I use some language I want to use it the way it
> is supposed to be used. Usually doing like that saves many problems.
> Especially in Python, where there is one official way to do any elementary
> task. And I just want to know what is the normal, official way of printing
> unicode strings. I mean, the question is not "how can I print the unicode
> string" but "how the creators of the language suppose me to print the
> unicode string". I couldn't find an answer to this question in docs, so I
> hope somebody here knows it.
> 
> So, is it _the_ python way of printing unicode?
> 

The "right way" to print a unicode string is to encode it in the
encoding that is appropriate for your needs (which may or may not be
UTF-8), and then to print it.  What this means in terms of your three
examples is that the first and third are correct, and the second is
incorrect.  The second one breaks when writing to a file, so don't use
it.  Both the first and third behave in the way that I suggest.  The
first (print u'foo'.encode('utf-8')) is less cumbersome if you do it
once,  but the third method (rebinding sys.stdout using codecs.open) is
less cumbersome if you'll be doing a lot of printing on stdout.  

In the end, they are the same method, but one of them introduces another
layer of abstraction.  If you'll be using more than two print statements
that need to be bound to a non-ascii encoding, I'd recommend the third,
as it rapidly becomes less cumbersome, the more you print.  

That said, you should also consider whether you want to rebind
sys.stdout or not.  It makes your print statements less verbose, but it
also loses your reference to the basic stdout.  What if you want to
print using UTF-8 for a while, but then you need to switch to another
encoding later?  If you've used a new name, you can still refer back to
the original sys.stdout.

Right:

my_out = codecs.getwriter('utf-8')(sys.stdout)
print >> my_out u"Stuff"
my_out = codecs.getwriter('ebcdic')(sys.stdout)
print >> my_out u"Stuff"

Wrong

sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
print u"Stuff"
sys.stdout = codecs.getwriter('ebcdic')(sys.stdout)
# Now sys.stdout is geting encoded twice, and you'll probably 
# get garbage out. :(
print u"Stuff"

Though I guess this is why the OP is doing:

sys.stdout = codecs.getwriter('utf-8')(sys.__stdout__)

That avoids the problem by not rebinding the original file object.
sys.__stdout__ is still in its original state. 

Carry on, then.

Cheers,
Cliff

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


Re: the official way of printing unicode strings

2008-12-14 Thread Ben Finney
Piotr Sobolewski  writes:

> in Python (contrary to Perl, for instance) there is one way to do
> common tasks.

More accurately: the ideal is that there should be only one *obvious*
way to do things. Other ways may also exist.

> Could somebody explain me what is the official python way of
> printing unicode strings?

Try these:

http://effbot.org/zone/unicode-objects.htm>
http://www.reportlab.com/i18n/python_unicode_tutorial.html>
http://www.amk.ca/python/howto/unicode>

If you want something more official, try the PEP that introduced
Unicode objects, PEP 100:

http://www.python.org/dev/peps/pep-0100/>.

> I tried to do this such way:
> s = u"Stanisław Lem"
> print u.encode('utf-8')
> This works, but is very cumbersome.

Nevertheless, that says everything that needs to be said: You've
defined a Unicode text object, and you've printed it specifying which
character encoding to use.

When dealing with text, the reality is that there is *always* an
encoding at the point where program objects must interface to or from
a device, such as a file, a keyboard, or a display. There is *no*
sensible default encoding, except for the increasingly-inadequate
7-bit ASCII.

http://www.joelonsoftware.com/articles/Unicode.html>

Since there is no sensible default, Python needs to be explicitly told
at some point which encoding to use.

> Then I tried to do this that way:
> s = u"Stanisław Lem"
> print u
> This breaks when I redirect the output of my program to some file,
> like that:
> $ example.py > log

How does it “break”? What behaviour did you expect, and what
behaviour did you get instead?

-- 
 \ “I hope that after I die, people will say of me: ‘That guy sure |
  `\owed me a lot of money’.” —Jack Handey |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: Building from source -- zlib/binascii problems 2.5.2/2.6.1

2008-12-14 Thread peter s.
On Dec 14, 4:54 pm, "Martin v. Löwis"  wrote:
> > Target: x86_64-redhat-linux
> > gcc -pthread -shared build/temp.linux-x86_64-2.5/location/of/
> > Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/
> > lib.linux-x86_64-2.5/zlib.so
> > /usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for
> > -lz
>
> Do
>
>   file /usr/lib/libz.so
>
> It might be a 32-bit library, in which case you can check whether
> /usr/lib64 has a 64-bit library. I'm puzzled why it only
> happens for -lz; perhaps you are better of compiling with a 32-bit
> compiler.
>
> Regards,
> Martin

$ file /usr/lib/libz.s*
/usr/lib/libz.so:   symbolic link to `libz.so.1.2.3'
/usr/lib/libz.so.1: symbolic link to `libz.so.1.2.3'
/usr/lib/libz.so.1.2.3: ELF 32-bit LSB shared object, Intel 80386,
version 1 (SYSV), stripped
--
http://mail.python.org/mailman/listinfo/python-list


Re: Building from source -- zlib/binascii problems 2.5.2/2.6.1

2008-12-14 Thread peter s.
On Dec 14, 5:03 pm, "peter s."  wrote:
> On Dec 14, 4:54 pm, "Martin v. Löwis"  wrote:
>
>
>
> > > Target: x86_64-redhat-linux
> > > gcc -pthread -shared build/temp.linux-x86_64-2.5/location/of/
> > > Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/
> > > lib.linux-x86_64-2.5/zlib.so
> > > /usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for
> > > -lz
>
> > Do
>
> >   file /usr/lib/libz.so
>
> > It might be a 32-bit library, in which case you can check whether
> > /usr/lib64 has a 64-bit library. I'm puzzled why it only
> > happens for -lz; perhaps you are better of compiling with a 32-bit
> > compiler.
>
> > Regards,
> > Martin
>
> $ file /usr/lib/libz.s*
> /usr/lib/libz.so:       symbolic link to `libz.so.1.2.3'
> /usr/lib/libz.so.1:     symbolic link to `libz.so.1.2.3'
> /usr/lib/libz.so.1.2.3: ELF 32-bit LSB shared object, Intel 80386,
> version 1 (SYSV), stripped

I meant to also add

$ file /usr/lib64/libz.s*
/usr/lib64/libz.so.1: symbolic link to `libz.so.1.2.3'
/usr/lib64/libz.so.1.2.3: ELF 64-bit LSB shared object, AMD x86-64,
version 1 (SYSV), stripped

So.. it seems as though I need to get it to point to the 64 bit
version (or compile the zlib that comes with Python source).  I'm not
sure how to override that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Building from source -- zlib/binascii problems 2.5.2/2.6.1

2008-12-14 Thread Martin v. Löwis
> So.. it seems as though I need to get it to point to the 64 bit
> version (or compile the zlib that comes with Python source).  I'm not
> sure how to override that.

The easiest solution would be to invoke the linker line manually,
and replace -lz with the absolute path to the right library.

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


Re: Looking for the best way to translate an idiom

2008-12-14 Thread Lie Ryan
On Sun, 14 Dec 2008 09:51:03 -0800, Paul  Moore wrote:

> On 14 Dec, 16:22, Bruno Desthuilliers
>  wrote:
>> if you only want the first returned value, you can just apply a slice:
>>
>> def f():
>>     return 1,2,3
>>
>> a = f()[0] + 1
> 
> Hmm, true. I'm not sure it's any less ugly, though :-)
> 
>> FWIW, Python 2.6 has NamedTuple objects...
> 
> I know, but I want to target 2.5+ (I still have a number of systems
> running 2.5)
> 

Ah, that discounts python 3.0
Python 3.0 allows you to do this:

a, b, *c = range(5)

# a >> 0
# b >> 1
# c >> [2, 3, 4]

*a, b, c = range(5)
# a >> [0, 1, 2]
# b >> 3
# c >> 4

a, *b, c = range(5)
# a >> 0
# b >> [1, 2, 3]
# C >> 4

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


Re: Looking for the best way to translate an idiom

2008-12-14 Thread Fuzzyman
On Dec 14, 5:51 pm, Paul  Moore  wrote:
> On 14 Dec, 16:22, Bruno Desthuilliers
>
>  wrote:
> > if you only want the first returned value, you can just apply a slice:
>
> > def f():
> >     return 1,2,3
>
> > a = f()[0] + 1
>
> Hmm, true. I'm not sure it's any less ugly, though :-)
>
> > FWIW, Python 2.6 has NamedTuple objects...
>
> I know, but I want to target 2.5+ (I still have a number of systems
> running 2.5)
>

There is a Python implementation of NamedTuple on the Python cookbook
that is compatible with Python 2.5.

Michael Foord
http://www.ironpythoninaction.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-14 Thread Fuzzyman

> That's an interesting definition of crash. You're just like saying: "C
> has crashed because I made a bug in my program". In this context, it is
> your program that crashes, not python nor C, it is misleading to say so.
>
> It will be python's crash if:
> 1. Python 'segfault'ed
> 2. Python interpreter exits before there is instruction to exit (either
> implicit (e.g. falling to the last line of the script) or explicit (e.g
> sys.exit or raise SystemExit))
> 3. Python core dumped
> 4. Python does something that is not documented

It seems to me to be a generally accepted term when an application
stops due to an unhandled error to say that it crashed.

Michael Foord
http://www.ironpythoninaction.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-14 Thread James Mills
On Mon, Dec 15, 2008 at 9:03 AM, Fuzzyman  wrote:
> It seems to me to be a generally accepted term when an application
> stops due to an unhandled error to say that it crashed.

it == application
Yes.



#!/usr/bin/env python

from traceback import format_exc

def foo():
  print "Hello World!"

def main():
  try:
 foo()
  except Exception, error:
 print "ERROR: %s" % error
 print format_exc()

if __name__ == "__main__":
  main()



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


Re: Need help improving number guessing game

2008-12-14 Thread James Stroud
It looks much better. But as Bruno suggests and as I alluded to earlier, 
you should get in the habit of forming verification loops on input 
channels that aren't already guaranteed to provide valid input messages. 
I'm not sure how to say that in English, but in python my example was:


while True:
  try:
guess1 = int(input("\n>> "))
  except ValueError:
print 'Bad value.'
  else:
break


Other than that, you still have some points where you can break lines 
down to improve clarity. Think of it like trying to avoid run-on sentences.


Over all, it looks like you have picked up some good technique that you 
could only get by experimentation over the course of about 5 or 6 months.


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


Re: the official way of printing unicode strings

2008-12-14 Thread Martin v. Löwis
> My main problem is that when I use some language I want to use it the way it
> is supposed to be used. Usually doing like that saves many problems.
> Especially in Python, where there is one official way to do any elementary
> task. And I just want to know what is the normal, official way of printing
> unicode strings. I mean, the question is not "how can I print the unicode
> string" but "how the creators of the language suppose me to print the
> unicode string". I couldn't find an answer to this question in docs, so I
> hope somebody here knows it.
> 
> So, is it _the_ python way of printing unicode?

The official way to write Unicode strings into a file is not to do that.
Explicit is better then implicit - always explicitly pick an encoding,
and encode the Unicode string to that encoding. Doing so is possible in
any of the forms that you have shown.

Now, Python does not mandate any choice of encoding. The right way to
encode data is in the encoding that readers of your data expect it in.

For printing to the terminal, it is clear what the encoding needs to
be (namely, the one that is used by the terminal), hence Python choses
that one when printing to the terminal. When printing to the file, the
application needs to make a choice.

If you have no idea what encoding to use, your best choice is the one
returned by locale.getpreferredencoding(). This is the encoding that
the user is most likely to expect.

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


Game to test : MicroWar 2.0 alpha 6

2008-12-14 Thread Pierre-Alain Dorange
MicroWar 2.0 alpha 3 for test purpose

Download : http://microwar.sourceforge.net/

Presentation
-
MicroWar is "Space Invaders" style arcade game, in the cruel world of
micro-compter industry. You're a Macintosh faced to invading Wintel
hordes year after year, kill more PC.
Bonuses let you improve your Mac performances or restore life...

Minimum Configuration (Macintosh)

Processor : PowerPC G4 minimum
System : MacOS X 10.3.9 or more
Memory : 512 MB
Screen : 1024 x 768 pixels

The bundled application is only available for Mac now.
The source code, is therefore cross-platform and can run on Macintosh,
Windows and Linux : see source documentation for details

Change log :
-
* handle mouse for menus
* option to play the game with the keyboard (default) or the mouse
* loading advancement feedback on splash screen
* default option : fullscreen
* bug fix : display year information correctly for 0 and 1 line.
* first run screen, user can choose it default language
* automatic game update check over internet and download to the desktop
* adding Clarus Power-Up Bonus (give 5 super-bomb)
* adding Saucer explosion : generate Virus that can infect PC
* clean the screens handling

-- 
Pierre-Alain Dorange

Ce message est sous licence Creative Commons "by-nc-sa-2.0"

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


Re: Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-14 Thread Paul Boddie
On 14 Des, 22:13, "Martin v. Löwis"  wrote:
> > But shouldn't the production of an object's representation via repr be
> > a "safe" operation?
>
> It's a trade-off. It should also be legible.

Right. I can understand that unlike Python 2.x, a representation of a
string in Python 3.x (whose equivalent in Python 2.x would be a
Unicode object) must also be a string (as opposed to a byte string in
Python 2.x), and that no decision can be taken to choose "safe"
representations for characters which cannot be displayed in a
terminal. In examples, for Python 2.x...

>>> u"æøå"
u'\xe6\xf8\xe5'
>>> repr(u"æøå")
"u'\\xe6\\xf8\\xe5'"

...and for Python 3.x...

>>> "æøå"
'æøå'
>>> repr("æøå")
"'æøå'"

...with an ISO-8859-15 terminal. Python 2.x could conceivably be
smarter about encoding representations, but chooses not to be since
the smarter behaviour would need to involve knowing that an "output
situation" was imminent. Python 3.x, on the other hand, leaves issues
of encoding to the generic I/O pipeline, causing the described
problem.

Of course, repr will always work if its output does not get sent to
sys.stdout or an insufficiently capable output stream, but I suppose
usage of repr for debugging purposes, where one may wish to inspect
character values, must be superseded by usage of the ascii function,
as you point out. It's unfortunate that the default behaviour isn't
optimal at the interactive prompt for some configurations, though.

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


Re: Looking for the best way to translate an idiom

2008-12-14 Thread James Stroud

Paul Moore wrote:

I'm translating some code from another language (Lua) which has
multiple function return values. So, In Lua, it's possible to define a
function

function f()
return 1,2,3
end

which returns 3 values. These can then be used/assigned by the caller:

a,b,c = f()

So far, much like Python, but the key difference is that in Lua,
excess arguments are ignored - so you can do


py> class mytuple(tuple):
  def magic(self, astr):
names = astr.split()
for name, val in zip(names, self):
  globals()[name] = val
...
py> t = mytuple((1,2,3))
py> t.magic('a b')
py> a
1
py> b
2

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


Re: Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-14 Thread Martin v. Löwis
> It's unfortunate that the default behaviour isn't
> optimal at the interactive prompt for some configurations, though.

As I said, it's a trade-off. The alternative, if it was the default,
wouldn't be optimal at the interactive prompt for some other
configurations.

In particular, users of non-latin scripts have been complaining that
they can't read their strings - hence the change, which now actually
allows these users to read the text that is stored in the strings.

The question really is why John Machin has a string that contains
'\u9876' (which is a Chinese character), yet his terminal is incapable
of displaying that character. More likely, people will typically
encounter only characters in their data that their terminals are
also capable of displaying (or else the terminal would be pretty
useless)

In the long run, it might be useful to have an error handler on
sys.stdout in interactive mode, which escapes characters that
cannot be encoded (perhaps in a different color, if the terminal
supports colors, to make it clear that it is an escape sequence)

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


Re: subprocess to C program

2008-12-14 Thread Aaron Brady
On Dec 14, 6:32 am, bobicanprogram  wrote:
> On Dec 13, 10:09 pm, MRAB  wrote:
>
>
>
> > Aaron Brady wrote:
> > > On Dec 13, 7:51 pm, Grant Edwards  wrote:
> > >> On 2008-12-14, MRAB  wrote:
>
> >  I am writing a C process and I want to read data from a file that I
> >  write to in Python.  I'm creating a pipe in Python, passing it to the
> >  C process, and calling '_read'.  It gives me error 9, bad file number.
> > > snip
> >  meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9.  I want 'ct'
> >  to be 11 at this point.  Thanks in advance.
> > >>> It looks like the ids aren't system global.
> > >> They certainly aren't in Unix: Their a property of the process.
>
> > >> --
> > >> Grant
>
> > > I'm not on Unix.  It has to be possible somehow.  Do I need to set
> > > permissions on the IDs?  Are Stdin and Stdout my only options?  Or
> > > does Popen prevent sharing IDs somehow?
>
> > You'd be better off using sockets.
>
> You might also consider using SIMPL (http://www.icanprogram.com/simpl)
> SIMPL has had a Python interface for about 5 years now.   There is an
> online tutorial here. (http://www.icanprogram.com/06py/main.html)
>
> In one of your responses you mentioned that you were not on Unix (and
> I presume Linux).   SIMPL-Python has recently been extended to work
> transparently from a Windows OS as well.
>
> bob
> SIMPL project coordinator

The engine uses a disk-based FIFO for interprocess.  It's good if
you're looking for one- or two- way sequential.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] stable algorithm with complexity O(n)

2008-12-14 Thread greg

Lie Ryan wrote:
"You know what you just did? You've 
just found a problem that was supposed to be an example of unsolvable 
problem."


It has happened before, why not again?


There's a big difference between an unsolvable problem and an
unsolved problem. In the cases you're talking about, nobody
had solved the problem before, but neither had anybody proved
there was no solution.

In the case at hand, there is a proof that such an algorithm
is impossible. Overturning that would require finding a
flaw in the proof, which for such a simple proof seems very
unlikely.

That's not to say nobody should try, but I won't be holding
my breath.

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


Re: subprocess to C program

2008-12-14 Thread Aaron Brady
On Dec 13, 9:09 pm, MRAB  wrote:
> Aaron Brady wrote:
> > On Dec 13, 7:51 pm, Grant Edwards  wrote:
> >> On 2008-12-14, MRAB  wrote:
>
>  I am writing a C process and I want to read data from a file that I
>  write to in Python.  I'm creating a pipe in Python, passing it to the
>  C process, and calling '_read'.  It gives me error 9, bad file number.
> > snip
>  meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9.  I want 'ct'
>  to be 11 at this point.  Thanks in advance.
> >>> It looks like the ids aren't system global.
> >> They certainly aren't in Unix: Their a property of the process.
>
> >> --
> >> Grant
>
> > I'm not on Unix.  It has to be possible somehow.  Do I need to set
> > permissions on the IDs?  Are Stdin and Stdout my only options?  Or
> > does Popen prevent sharing IDs somehow?
>
> You'd be better off using sockets.

I got the 'stdin' solution to work.  The Python end worked fine.  I
just had to use the 'getchar' function instead of '_getch' function on
the C end.  Not obvious, I guess.  Ideally, I could block on input
from the console and stdin individually.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Output to file gets lost - don't know where to look ...

2008-12-14 Thread Scott David Daniels

uair01 wrote:

I will try the python program outside of IDLE.


Yes, running the program from the Linux shell instead of from IDLE
produces all output correctly.
Now I'll have to look for a new simple development environment :-(
I think I'll try SPE that has worked well for me ...


Or you could try to distill the problem to a simple case and by so
doing, improve IDLE for everyone.  I'd start by seeing if changing
>> .../idlelib/CallTipWindow.py", line 126, in hidetip
from:
>> self.label.destroy()
to:
   if self.label is not None:
  self.label.destroy()

and seeing if that quick-fix lets you go farther.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: stable algorithm with complexity O(n)

2008-12-14 Thread Aaron Brady
On Dec 14, 6:04 pm, greg  wrote:
> Lie Ryan wrote:
> > "You know what you just did? You've
> > just found a problem that was supposed to be an example of unsolvable
> > problem."
>
> > It has happened before, why not again?
>
> There's a big difference between an unsolvable problem and an
> unsolved problem. In the cases you're talking about, nobody
> had solved the problem before, but neither had anybody proved
> there was no solution.
>
> In the case at hand, there is a proof that such an algorithm
> is impossible. Overturning that would require finding a
> flaw in the proof, which for such a simple proof seems very
> unlikely.

It's more likely you'd circumvent the assumptions.  That is, find an
'outside-the-box' solution.  For instance, a deeply parallel
architecture could escape the assumption that you can only compare two
numbers at a time (per step).

The proof's conclusion is still true if its assumption is.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for the best way to translate an idiom

2008-12-14 Thread James Stroud

James Stroud wrote:

py> class mytuple(tuple):
  def magic(self, astr):
names = astr.split()
for name, val in zip(names, self):
  globals()[name] = val
...
py> t = mytuple((1,2,3))
py> t.magic('a b')
py> a
1
py> b
2

James



In case its not obvious:

def f():
  return mytuple((1,2,3))

f().magic('a b')

You can parameterize lobbing off values, or use more magic:

py> class mytuple(tuple):
...   def magic(self, astr):
... names = astr.split()
... for name, val in zip(names, self):
...   globals()[name] = val
...   def __add__(self, other):
... if isinstance(other, tuple):
...   return mytuple(tuple.__add__(self, other))
... else:
...   return mytuple(self[other:])
...
py> t = mytuple((1,2,3))
py> t + 1
(2, 3)
py> def f():
  return mytuple((1,2,3))
...
py> (f() + 1).magic('a b')
py> a
2
py> b
3

It's not as bad as a lot of the cynics are about to tell you it is. If 
it has any badness at all, it's because of the need (according to what I 
infer from your specification) to use the global namespace. If you want 
to modify a "more local" namespace, you can use some stack frame 
inspection to do some real magic:


py> import inspect
py> class mytuple(tuple):
  def magic(self, astr):
names = astr.split()
for name, val in zip(names, self):
  inspect.stack()[1][0].f_locals[name] = val
  def __add__(self, other):
if isinstance(other, tuple):
  return mytuple(tuple.__add__(self, other))
else:
  return mytuple(self[other:])
...
py> def f():
  return mytuple((6,7,8))
...
py> (f() + 1).magic('a b')
py> a
7
py> b
8

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


Python shows up checking votes

2008-12-14 Thread Scott David Daniels

I just saw an interesting post --

The video linked to on http://www.blog.wired.com in Kim Zetter's
"Threat Level" blog, there is a video describing the software
used to provide open access to ballots after an election.  The
software used for this system is an open-source system written
in Python.  Turns out they found election system failures in
California's Humboldt County using this software.  It also turns
out that the failure was not large enough to change the result of
any of the races or propositions this time.

By Kim Zetter's blog for 8-Dec-08 entitled
  "Unique Transparency Program Uncovers Problems with Voting Software"

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for the best way to translate an idiom

2008-12-14 Thread drobi...@gmail.com
On Dec 14, 11:19 am, Paul  Moore  wrote:
> I'm translating some code from another language (Lua) which has
> multiple function return values. So, In Lua, it's possible to define a
> function
>
>     function f()
>         return 1,2,3
>     end
>
> which returns 3 values. These can then be used/assigned by the caller:
>
>     a,b,c = f()
>
> So far, much like Python, but the key difference is that in Lua,
> excess arguments are ignored - so you can do
>
>     a = f()
> or even
>     a = f() + 1
>
> where in the latter, a is 2 (as addition only needs 1 argument, so the
> extra ones are discarded).
>
> This results in the code which I'm trying to translate having
> functions which return multiple arguments, the first of which is the
> "main" result, and the following values are "extra" results
> (specifically, the position at which a match is found, followed by the
> "captured" values of the match).
>
> I'm trying to find a natural equivalent in Python. So far, I've
> considered the following:
>
> - return a tuple (pos, captures). This is messy, because you end up
> far too often unpacking the tuple and throwing away the second value
> - return an object with pos and captures attributes. This is better,
> as you can do match(...).pos to get the position alone, but it doesn't
> really feel "pythonic" (all those calls with .pos at the end...)
> - have 2 calls, one to return just the position, one to return both.
> This feels awkward, because of the 2 method names to remember.
>
> To make things worse, Lua indexes strings from 1, so it can use a
> position of 0 to mean "no match" - so that a simple "did it match?"
> test looks like if (match())... - where in Python I need if
> (matchpos(...) != -1)... (Although if I return a match object, I can
> override __nonzero__ to allow me to use the simpler Lua form).
>
> Can anyone suggest a good idiom for this situation? At the moment, I'm
> returning a match object (the second option) which seems like the
> least bad of the choices (and it mirrors how the re module works,
> which is somewhat useful). But I'd like to know what others think. If
> you were using a pattern matching library, what interface would you
> prefer?
>
> I suspect my intuition isn't accurate here, as most of the use I've
> made of the library is in writing tests, which isn't typical use :-(
>
> Thanks for any assistance.
>
> Paul

I'm baffled by this discussion.
What's wrong with
   a, dontcare, dontcare2 = f()
   a = a + 1

 Simple, clear, and correct.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for the best way to translate an idiom

2008-12-14 Thread James Stroud

drobi...@gmail.com wrote:


I'm baffled by this discussion.
What's wrong with
   a, dontcare, dontcare2 = f()
   a = a + 1

 Simple, clear, and correct.


1. This can't apply to a generalized f() that may return an arbitrary 
number of arguments >= len(num_assignments_you_care_about).
2. The example chosen was misleading. You don't want to add 1 to the 
first element of the tuple, you want to move the "start" of the returned 
tuple up 1 and start assignment on the left from there.


James

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


Re: Looking for the best way to translate an idiom

2008-12-14 Thread James Stroud

James Stroud wrote:

  inspect.stack()[1][0].f_locals[name] = val


I just double checked this. Because of the way locals are implemented in 
cPython, this won't have the desired affect.


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


Re: [OT] stable algorithm with complexity O(n)

2008-12-14 Thread Steven D'Aprano
On Sun, 14 Dec 2008 21:42:33 +, Lie Ryan wrote:

> I'm sure someday, there will be a student who comes to class late and
> sees this on the board: "Design a comparison sorting algorithm that has
> better than O(n * log n) lower bound complexity." The unsuspecting
> student copied it, thinking it's a homework. He crunched to the problem,
> going to various meditations and yoga classes before finding a way that
> works just before deadline, handing out the work a bit late. Six weeks
> later, his professor called and said: "You know what you just did?
> You've just found a problem that was supposed to be an example of
> unsolvable problem."
> 
> It has happened before, why not again?
> http://www.snopes.com/college/homework/unsolvable.asp


Because as you described it, it *hasn't* happened before. There is the 
world of difference between an unsolvABLE problem and one that is 
unsolvED.

All the positive thinking in the world won't help you:

* make a four-sided triangle;

* write down a completely accurate rational expansion for pi or the 
square-root of 2;

* split a magnet into two individual poles;

* find an integer solution to 3*n = 7;

* solve the Halting Problem;

* fit n items into n-1 pigeonholes without putting two items in the one 
pigeonhole;

* create a compression algorithm that will compress random data;

* or design a comparison sort which does fewer than O(n*log n) two-way 
comparisons in the worst case, or fewer than O(n) comparisons in the best 
case.


Some things really don't have a solution, no matter how much power of 
positive thinking you apply to it.



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


Re: Removing None objects from a sequence

2008-12-14 Thread Stephen Thorne
On 2008-12-12, Filip Gruszczyński wrote:
> Hi!
> 
> I would like to iterate over a sequence nad ignore all None objects.
> The most obvious way is explicitly checking if element is not None,
> but it takes too much space. And I would like to get something faster.
> I can use
> [ sth for sth in self.__sth if not sth is None ], but I don't know if
> that's the best way. I checked itertools, but the only thing that
> seemed ok, was ifilter - this requires seperate function though, so
> doesn't seem too short. How can I get it the shortest and fastest way?

There's a little hack that will remove all elements from a list that
are 'False' when considered as a boolean. So None, [], '', False,
etc.

filter(None, myseq)

an example:

>>> l = ['1', 2, 0, None, '5']
>>> filter(None, l)
['1', 2, '5']

-- 
Regards,
Stephen Thorne
Development Engineer
NetBox Blue - 1300 737 060

Scanned by the NetBox from NetBox Blue
(http://netboxblue.com/)


Can you afford to be without a NetBox? 
Find out the real cost of internet abuse with our ROI calculator.
http://netboxblue.com/roi



Scanned by the NetBox from NetBox Blue
(http://netboxblue.com/)

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


Re: How do I manually uninstall setuptools (installed by egg)?

2008-12-14 Thread Stephen Thorne
On 2008-12-12, Nick Craig-Wood wrote:
> Failing that I'll use bdist_rpm then alien to convert to a deb which
> works well enough I find.

Ages ago there was a bdist_deb that was in the python bug tracker, long
since that bug tracker has been transitioned to another one, and that
attachment was lost.

Another pythoneer still had it a few years later, and I got it from him.

In an effort to help people create real packages from python software,
rpms and debs, I put together a small program to download source from
pypi and convert it into an OS installable package. This is known to
work on some redhat systems (modulo a problem with the redhat macro
for doing python byte compilation automatically on all packages), and
debian based systems.

You can find the work I did on:

https://launchpad.net/packaging
http://pypi.python.org/pypi/packaging

And more importantly, you can find bdist_deb.py here:
http://bazaar.launchpad.net/~jerub/packaging/trunk/annotate/11?file_id=bdist_deb.py-20080507003948-5c5mn3f68meq60hs-1

-- 
Regards,
Stephen Thorne
Development Engineer
NetBox Blue - 1300 737 060

Scanned by the NetBox from NetBox Blue
(http://netboxblue.com/)


Can you afford to be without a NetBox? 
Find out the real cost of internet abuse with our ROI calculator.
http://netboxblue.com/roi



Scanned by the NetBox from NetBox Blue
(http://netboxblue.com/)

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


Re: execution time

2008-12-14 Thread Steven D'Aprano
On Sun, 14 Dec 2008 18:35:24 +0100, Andreas Kostyrka wrote:

> On Sun, Dec 14, 2008 at 05:03:38PM +0100, David Hláčik wrote:
>> Hi guys,
>> 
>> #! /usr/bin/python
>> 
>> import random
>> import bucket2
>> 
>> data = [ random.randint(1,25) for i in range(5)] print "random data :
>> %s" % data
>> print "result: %s" %bucket2.sort(data)
>> 
>> How to write a test script which will outputs execution time for
>> bucket2.sort(data) ?
> 
> Well:
> 
> import time
> 
> starttime = time.time()
> 
> 
> 
> endtime = time.time()
> print "Whatever  does, it took %5.3fs to do." % (endtime -
> starttime)


Is subject to lots of timing errors for small code snippets. Sorting five 
numbers is (probably) going to be very quick, so the random timing errors 
will probably be larger than the time it actually takes to sort!


Just for reference, here's the size of errors from timing naively on my 
machine:

def timer(alist):
from time import time
t = time()
alist.sort()
return time() - t

def make_list():
from random import random
return [random() for i in range(5)]

data = [timer(make_list()) for i in range(100)]
mean = sum(data)/len(data)
average_error = sum(abs(x-mean) for x in data)/len(data)

print "The average timing is %f seconds." % mean
print "The average error is %f seconds." % average_error
print "Percentage error: %f%%" % (average_error/mean*100)


And here is the output:

The average timing is 0.50 seconds.
The average error is 0.89 seconds.
Percentage error: 177.953157%


What this tells us is that the likely error in any one timing of a small 
code snippet using time.time() directly is so large that it is useless 
for anything other than the most crude measurements. Using time() on its 
own is a good example of "measure with micrometer, mark with chalk, cut 
with axe". This is precisely the problem the timeit module is written to 
solve.



> Alternativly take a look at the timeit standard module.

I'd reverse that recommendation: start with the timeit module first, and 
if and only if it is unsuitable, consider writing your own solution.


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


Re: Removing None objects from a sequence

2008-12-14 Thread Lie Ryan
On Fri, 12 Dec 2008 22:55:20 +, Steven D'Aprano wrote:

> On Fri, 12 Dec 2008 21:18:36 +, Lie Ryan wrote:
>> Personally, I'd prefer VB's version:
>> foo IsNot bar
>> 
>> or in pseudo-python
>> foo isnot bar
>> 
>> since that would make it less ambiguous.
> 
> "a is not b" is no more ambiguous than "1+2*3". True, there's ambiguity
> if you are ignorant of the precedence rules, but that's no worse than
> saying that "+" is ambiguous if you don't know what "+" means.
> 
> "What's this 'is' operator??? It's ambiguous, it could mean ANYTHING!!!
> Panic panic panic panic!!!"
> 
> *wink*
> 
> You're allowed to assume the normal conventions, and (lucky for me!)
> despite being Dutch Guido choose to assume the normal English convention
> that "a is not b" means the same as "not (a is b)" rather than "a is
> (not b)". That's probably because the use-cases for the second would be
> rather rare.
> 
> So given the normal precedence rules of Python, there is no ambiguity.
> True, you have to learn the rules, but that's no hardship.

*I* know about the precedence rule, but a newbie or a tired programmer 
might not. He might want to reverse the truth value of argument b but 
instead has just reversed the whole expression. Probably in a slightly 
convoluted code like this:

if a is not(b and c): 
   ...


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


Re: [OT] stable algorithm with complexity O(n)

2008-12-14 Thread Roy Smith
Steven D'Aprano  wrote:

> All the positive thinking in the world won't help you:
> 
> * make a four-sided triangle;
> 
> * split a magnet into two individual poles;

These two are fundamentally different problems.

The first is impossible by definition.  The definition of triangle is, "a 
three-sided polygon".  Asking for a "four-sided triangle" is akin to asking 
for "a value of three which is equal to four".

The second is only "impossible" because it contradicts our understanding 
(based on observation) of how the physical universe works.  Our 
understanding could simply be wrong.  We've certainly been wrong before, 
and we will undoubtedly be proven wrong again in the future.  When it comes 
to things like electromagnetic theory, it doesn't take too many steps to 
get us to the fuzzy edge of quantum physics where we know there are huge 
questions yet to be answered.
--
http://mail.python.org/mailman/listinfo/python-list


Python User Group - Calgary, Alberta, Canada

2008-12-14 Thread Greg
Hi all, this is just a brief announcement regarding the resurrection
of the Python User Group in Calgary, Alberta, Canada.

Our first meeting will be on Wednesday, January 14, 2009.

Our official web site (albeit requiring a lot of work):
http://www.pythoncalgary.com/

We have a mailing list set up at:
http://groups.google.ca/group/pythoncalgary/

Calendar of Events:
http://www.google.com/calendar/hosted/pythoncalgary.com/embed?src=admin%40pythoncalgary.com&ctz=America/Edmonton

If you live in our around the Calgary area, please join the mailing
list and consider coming to our inaugural meeting in January. Venue
TBA.

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


Re: Removing None objects from a sequence

2008-12-14 Thread Steven D'Aprano
On Mon, 15 Dec 2008 02:11:10 +, Lie Ryan wrote:

>> So given the normal precedence rules of Python, there is no ambiguity.
>> True, you have to learn the rules, but that's no hardship.
> 
> *I* know about the precedence rule, but a newbie or a tired programmer
> might not. He might want to reverse the truth value of argument b but
> instead has just reversed the whole expression.

And? A newbie or a tired programmer might not know that a^b is bit-wise 
xor instead of exponentiation, or that range(n) doesn't include n, or 
even that len(alist) returns the length of a list. There's no limit to 
the potential mistakes that are possible for a programmer who is tired, 
inexperienced, intoxicated or just plain stupid enough. What's your 
point? Are you expecting Python to be mistake-proof?

There's a certain level of knowledge about the language necessary to 
program effectively, and learning that "is not" is a single operator is 
not particularly onerous.



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


Re: Python music sequencer timing problems

2008-12-14 Thread John O'Hagan
On Sun, 14 Dec 2008, Bad Mutha Hubbard wrote:
> John O'Hagan wrote:
> > On Wed, 10 Dec 2008, badmuthahubbard wrote:
[...]
> > from time import time, sleep
> >
> > start = time()
> > for event in music:
> > duration=len(event) #Really, the length of the event
> > play(event)
> > while 1:
> > timer = time()
> > remaining = start + duration - timer
> > if remaining < 0.001:
> > break
> > else:
> > sleep(remaining / 2)
> > stop(event)
> > start += duration
> >

> Very interesting approach, halving the remaining duration.  Right now
> I'm not working with note-offs, Csound takes care of the duration.  I
> just need to be able to call the notes at the right times.  
[...]

I'm also using the above code without the "stop(event)" line for playing 
non-midi stuff (fixed-length samples for example), which from the sound of it 
also applies to your requirement - IOW, you _can_ use it just to start notes 
at the right time, because the note-playing loop sleeps till then.
 
[...]
> I also like and respect Fluidsynth, but I'm working on a pretty
> microtonal system, and MIDI doesn't have enough microtonal support.
>
[...]
I'm certainly not trying to convert you to Fluidsynth - I'm more likely to 
convert to Csound - but just for the record, you can do microtonal stuff 
fairly easily using Fluidsynth's "settuning" command. In my program I can use 
any equal-tempered division of the octave by preceding each set of events 
which require it with this:

mesg = [ "select " + channel + " " + font
+  " " + bank+ " " + program +
"  \ntuning name 0 " + program + "\n"]

for key in xrange(128):
pitch = strkey - 60) * 12.0 / divisor) + 60) * 100)
mesg.append( "tune  " + bank + " " + program 
  + " " + str(key) + " " + pitch + "\n")

mesg.append("settuning " + channel + " " 
   + bank  " " + program + "\n")
mesg = ''.join(mesg)
fluidsynth_socket.send(mesg)

where "divisor" is the number you want to divide the octave by (the other 
names are self-descriptive). The reason for the "60"s in there is just to 
keep middle C where it is. 

For more complex/non-linear pitch-warping, the rest of the "pitch = " line 
could be replaced with any pitch-altering function taking "key" as an 
argument; but I haven't tried that yet. 

I'd be interested to hear about the microtonal system(s) you're using.

Regards,

John

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


Re: How do I manually uninstall setuptools (installed by egg)?

2008-12-14 Thread excord80
On Dec 9, 10:48 pm, excor...@gmail.com wrote:
>
> Anyway, the direction I'm heading is to try and use setuptools *less*.
> It seems like it might be too complicated for me. And, I notice that
> the mailing list for it (distutils-sig, if that's the right one) is
> loaded with questions on how to use it properly, so maybe I'm not
> alone.

Ah. This is interesting: http://www.b-list.org/weblog/2008/dec/14/packaging/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is slow

2008-12-14 Thread cm_gui

hahaha, do you know how much money they are spending on hardware to
make
youtube.com fast???

> By the way... I know of a very slow Python site called YouTube.com. In
> fact, it is so slow that nobody ever uses it.

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


  1   2   >