Re: [Python-Dev] [RELEASED] Python 3.2 beta 1

2010-12-07 Thread Łukasz Langa
Wiadomość napisana przez Georg Brandl w dniu 2010-12-06, o godz. 22:46:

> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
> 
> On behalf of the Python development team, I'm happy to announce the
> first of two beta preview releases of Python 3.2.
> 
> Python 3.2 is a continuation of the efforts to improve and stabilize the
> Python 3.x line.  Since the final release of Python 2.7, the 2.x line
> will only receive bugfixes, and new features are developed for 3.x only.
> 
> Since PEP 3003, the Moratorium on Language Changes, is in effect, there
> are no changes in Python's syntax and built-in types in Python 3.2.
> Development efforts concentrated on the standard library and support for
> porting code to Python 3.  Highlights are:
> 
> [snip]

* configparser 1.1: new API using the mapping protocol access, support for 
pluggable interpolation handlers, additional interpolation handler 
(ExtendedInterpolation) which supports the zc.buildout syntax, support for 
alternative option/value delimiters, support for customization of accepted INI 
file structure (e.g. comment prefixes, name of the DEFAULT section, 
indentation, empty lines in multiline values, etc.), support for specifying 
encoding for read operations, ConfigParser class deprecated in favor of 
SafeConfigParser, lots of other small changes.

-- 
Best regards,
Łukasz Langa
tel. +48 791 080 144
WWW http://lukasz.langa.pl/

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


Re: Collision of rotated rectangles without pygame

2010-12-07 Thread John Nagle

On 12/5/2010 2:49 PM, Martin Manns wrote:

Hello,

I am looking for a Python library for 2D collision checks of rotated
rectangles. Currently, I have found vizier 0.5b that is based on pygame.

Since I do not want to add a pygame dependency to my app, I replaced the
pygame.rect.Rect by a wxPython wx.Rect (see code below).

However, collision checks do not work correctly, i. e. identical rects
are not found to be colliding:


   Probably because you seem to be trying to compute the intersection
point for coincident lines, which is not well-defined.

   I don't have time to debug this, but you might want to get some
basic books on game programming and graphics.

   Incidentally, a dictionary lookup in Python is far more expensive
than computing trig functions.  If you need to speed this up
for large numbers of rectangles, there are algorithms that are
several orders of magnitude faster.  Realistically, though,
this is the kind of problem that runs slow in CPython.

   This is why you don't write your own collision library.
(I once did, for 3D, but that was in 1996, when it was
cutting-edge technology.)

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


Using logging module to log either to screen or a file

2010-12-07 Thread RedBaron
Hi,
I am beginner to python and i am writing a program that does a lot of
things. One of the requirements is that the program shud generate a
log file. I came across python loggging module and found it very
useful. But I have a few problems
Suppose by giving option '-v' along with the program the user can turn
off logging to a file and instead display log on the screen. Since I
am using a config file for logging, how do I accomplish this.
I tried to define two handlers (fil and screen) and added it to my
logger. But that logs data to both screen and the file. I need to log
it to only one. How do I dynamically remove one of the handler from
the logger based on user option. As a precursor how do i reference the
handlers defined in config file in the code??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception handling in Python 3.x

2010-12-07 Thread Mark Wooding
John Nagle  writes:

>PEP 255, like too much Python literature, doesn't distinguish
> clearly between the language definition and implementation detail.  It
> says "The mechanics of StopIteration are low-level details, much like
> the mechanics of IndexError in Python 2.1".  Applications shouldn't be
> explicitly using StopIteration.

You've twisted the words by quoting them out of context, and have
attempted to force a misinterpretation of `low-level details' as
`implementation detail'.

That text comes from a question-and-answer section, in response to the
question `why not force termination to be spelled "StopIteration"?'.
This is a fine answer to the question: the details of the (preexisting
-- see PEP 234) iteration protocol are abstracted by the generator
syntax.  But it doesn't at all mean that the StopIteration exception
isn't an official, use-visible part of Python.

>IronPython doesn't do StopIteration the same way CPython does.
>
> http://ironpython.codeplex.com/wikipage?title=IPy1.0.xCPyDifferences

IronPython's behaviour when you try to fetch items from a spent
generator is different.  It still implements the same iterator protocol,
and raises StopIteration when it has no more items to yield.

You're not stupid, but you'd have to be in order to think that these
references support your claim that

> >> You're not entitled to assume that StopIteration is how a generator
> >> exits.  That's a CPyton thing; generators were a retrofit, and
> >> that's how they were hacked in.  Other implementations may do
> >> generators differently.

I don't want to conclude that you're not arguing in good faith but I'm
not seeing many other possibilities.

-- [mdw]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP8 compliance and exception messages ?

2010-12-07 Thread shearichard
On Dec 6, 6:21 pm, Ben Finney  wrote:
> shearichard  writes:
> > Hi - PEP8 says lines should not exceed 79 characters in length
> > (http://www.python.org/dev/peps/pep-0008/).
>
> > So if you've got some code that looks like this :
>
> > raise fooMod.fooException("Some message which is quite long")
>
> PEP 8 also says those names are poorly chosen. Better:
>
>     raise foomod.FooException("Some message which is quite long")
>
> > raise fooMod.fooException("\
> >         Some message \
> >         which is quite long")
>
> Take advantage of the parsing of string literals and parenthesis:
>
>     raise foomod.FooException(
>         "Some message"
>         " which is quite long")
>
> and for the sake of my eyes, avoid camelCase.

OK you got me ! Thanks for pointing this out, I will take a look at
the relevant section
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP8 compliance and exception messages ?

2010-12-07 Thread shearichard
On Dec 7, 9:17 am, Andreas Waldenburger 
wrote:
> On Mon, 6 Dec 2010 00:22:49 -0500 Andreas Waldenburger 
>  wrote:
>
>
>
> > On Sun, 5 Dec 2010 19:52:54 -0800 Chris Rebert 
> > wrote:
>
> > > On Sun, Dec 5, 2010 at 7:40 PM, shearichard 
> > > wrote:
> > > > Hi - PEP8 says lines should not exceed 79 characters in length
> > > > (http://www.python.org/dev/peps/pep-0008/).
>
> > > > So if you've got some code that looks like this :
>
> > > > raise fooMod.fooException("Some message which is quite long")
>
> > > > ... and assuming a certain amount of indenting you're going to
> > > > break that guideline.
>
> > > > [etc.]
>
> > > [...]
> > > Alternatively, you could disregard PEP 8 on this point on the
> > > grounds that the 79/80 characters per line limit is outdated.
>
> > Maybe, but it's not outmoded.
>
> As a more useful (I hope) reply, my opinion in this case is to just make the 
> line a little longer. Even if you can't read it all at once, it is pretty 
> obvious what comes next: The rest of the error message. There is no 
> additional functionality hidden there, and you don't need to see it all at 
> once to grasp the meaning of the code.
>
> /W
>
> --
> To reach me via email, replace INVALID with the country code of my home
> country.  But if you spam me, I'll be one sour Kraut.

Thanks to everyone for their helpful replies.

Thanks for the pointers towards implicit (or explicit) string
concatenation - just what was needed.

I appreciate everyone has different opinions by I'm happy to try to
stick with 79 character lines for the meantime - largely for the 'may
have a wide screen but like to have lots of files open in slim
windows' reason.

regards

Richard.

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


v = vte.Terminal() AttributeError: 'module' object has no attribute 'Terminal'

2010-12-07 Thread Steve
Hi,

I try to run a terminal emulation using Python+Gtk+Vte. Before develop
my own sources, i'm testing some examples like this ;
http://www.eurion.net/python-snippets/snippet/Embed%20a%20VTE%20terminal.html

But when i try to run, i get this message error;

v = vte.Terminal()
AttributeError: 'module' object has no attribute 'Terminal'

I'm using ubuntu 9.10 karmic. I've installed (apt-get) python-gtk, /2,
-dev, libvte...

Anyone know if there's a bug on this using karmic, or i must to
download and compile gtk/vte from sources?

thanks,

Steve,


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


Calling FORTAN dll functions from Python

2010-12-07 Thread Alex van der Spek
Does anyone know how to call functions from FORTRAN dlls in Python? Is it 
even possible? I browsed the documentation for Python 2.6.1 and the Python/C 
API comes close to what I would like to do but it is strictly limited to C.


Unfortunately the passing of arguments in C and FORTRAN is very different, 
not to mention the differences with strings where FORTRAN expects a hidden 
length argument. It could call the FORTRAN dll from C and call the C 
functions from Python but is that my only option?


For reference: I am using Python 2.6.1 FORTRAN powerstation 4.0. It is not 
an option to translate the FORTRAN code to C (using f2c) as the source code 
is the official ASME version of calculating steam tables.


I am interested in a solution that will work on Windows (XP and Vista) as 
well as Linux (Ubuntu 10.4) although the latter would not use dlls but code 
resources.


I am a beginner in Python. The fact that I still use and can use FORTRAN 
gives away my age. Mixed language programming is not an issue for me (C/VB, 
VB/FORTRAN, C/FORTRAN) but Python is new. Just pointing me to relevant 
documentation would be helpful in its own right.


Thank you in advance,
Alex van der Spek 


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


Re: Calling FORTAN dll functions from Python

2010-12-07 Thread Stefan Behnel

Alex van der Spek, 07.12.2010 12:11:

Does anyone know how to call functions from FORTRAN dlls in Python? Is
it even possible?


Sure, have a look at fwrap and Cython.

Stefan

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


is py2exe still active ?

2010-12-07 Thread Anders Persson
Hi!
When a look att py2exe homepage it is not looking like mutch happen,
as a beginner i was thinking to start with Python 3, but i like to now
if py2exe will be for 3 too.

Is any one have any info ?

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


Books recommendation

2010-12-07 Thread Octavian Rasnita
Hello,

Do you have, or can I find elsewhere a recommendation for books,tutorials and 
sites appropriate for beginners?

I have a lot of experience in Perl but I am interested to also learn Python for:
- web development (with frameworks similar with Catalyst and Ruby on Rails, 
good templating systems, good ORMS and form processors)
- Desktop apps with WxPython
- Create MS Windows apps, executables, dlls, ActiveX, OS interaction...
- Text parsing, regular expressions...

I am also interested to find where I can get Python modules from and how... 
similar tools and sites with cpan and ppm for Perl.

Thank you.

Octavian

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


Re: Books recommendation

2010-12-07 Thread Anders Persson
You can't compile Python to exe files, but there is program packing
your script to a exe files, look att

www.py2exe.org

Beware that you must have py2exe version match your pythonversion and
att current time the highest version is 2.7.

/A


On Dec 7, 2:39 pm, "Octavian Rasnita"  wrote:
> Hello,
>
> Do you have, or can I find elsewhere a recommendation for books,tutorials and 
> sites appropriate for beginners?
>
> I have a lot of experience in Perl but I am interested to also learn Python 
> for:
> - web development (with frameworks similar with Catalyst and Ruby on Rails, 
> good templating systems, good ORMS and form processors)
> - Desktop apps with WxPython
> - Create MS Windows apps, executables, dlls, ActiveX, OS interaction...
> - Text parsing, regular expressions...
>
> I am also interested to find where I can get Python modules from and how... 
> similar tools and sites with cpan and ppm for Perl.
>
> Thank you.
>
> Octavian

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


Fresher career in Management work.

2010-12-07 Thread gaurav
Recent recruitment you can reach your goal. Careers recruitment.
http://managementjobs.webs.com/itm.htm
http://topcareer.webs.com/businessmanagement.htm

Latest government works to earn money, other vacancies in office jobs.
http://printmediajobs.webs.com/index.htm  http://rojgars1.webs.com/gov.htm
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using logging module to log either to screen or a file

2010-12-07 Thread Jean-Michel Pichavant

RedBaron wrote:

Hi,
I am beginner to python and i am writing a program that does a lot of
things. One of the requirements is that the program shud generate a
log file. I came across python loggging module and found it very
useful. But I have a few problems
Suppose by giving option '-v' along with the program the user can turn
off logging to a file and instead display log on the screen. Since I
am using a config file for logging, how do I accomplish this.
I tried to define two handlers (fil and screen) and added it to my
logger. But that logs data to both screen and the file. I need to log
it to only one. How do I dynamically remove one of the handler from
the logger based on user option. As a precursor how do i reference the
handlers defined in config file in the code??
  

your logger has a public 'handlers' attribute.

consoleHandlers = [h for h in logger.handlers if h.__class__ is 
logging.StreamHandler] # the list of handlers logging to the console 
(assuming they are instances of the StreamHandler class)


if consoleHandlers:
   h1 = consoleHandlers[0]
   h1.filter = lambda x:True # enable the handler
   h1.filter = lambda x:False # disable the handler


JM


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


Re: is py2exe still active ?

2010-12-07 Thread Cbast
On Dec 7, 8:23 am, Anders Persson  wrote:
> Hi!
> When a look att py2exe homepage it is not looking like mutch happen,
> as a beginner i was thinking to start with Python 3, but i like to now
> if py2exe will be for 3 too.
>
> Is any one have any info ?

I don't have the answer about py2exe, but I'm using cxFreeze to create
executables with Python 3.1, if it's what you're looking for.

http://cx-freeze.sourceforge.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


sqlite3 and UTF-8

2010-12-07 Thread Ale Ghelfi

I try to connect a database sqlite by sqlite3, but return an error.

>>> rowset = cur.fetchall()
Traceback (most recent call last):
  File "", line 1, in 
rowset = cur.fetchall()
OperationalError: Could not decode to UTF-8 column 'DATO' with text 
'Document n°10'


What's happend? thank you
--
http://mail.python.org/mailman/listinfo/python-list


kinterbasdb error connection

2010-12-07 Thread Ale Ghelfi

(i'm under Ubuntu 10.10 amd64 and python 2.6 and kinterbasdb 3.2 )
I try to connect my database of firebird 2.5 by kinterbasdb.
But python return this error :

>>> c = 
kinterbasdb.connect(dsn="/media/VINACCIA.FDB",user="user",password="password",charset="UTF-8")

Traceback (most recent call last):
  File "", line 1, in 
c = 
kinterbasdb.connect(dsn="/media/VINACCIA.FDB",user="user",password="password",charset="UTF-8")
  File "/usr/lib/pymodules/python2.6/kinterbasdb/__init__.py", line 
435, in connect

return Connection(*args, **keywords_args)
  File "/usr/lib/pymodules/python2.6/kinterbasdb/__init__.py", line 
612, in __init__

b.dsn, b.dpb, b.dialect, timeout
OperationalError: (-902, 'isc_attach_database: \n  I/O error during 
"open" operation for file "/media/VINACCIA.FDB"\n  Error while trying to 
open file\n  Permission denied')


By terminal of Ubuntu this is the permission of database:
$ls -l /media/VINACCIA.FDB
-rw-r--r-- 1 grappale grappale 1720320 2010-12-06 17:33 /media/VINACCIA.FDB

Where am i wrong? Please. Thank you!
--
http://mail.python.org/mailman/listinfo/python-list


use of __new__ to permit "dynamic" completion within (any?) IDE ?

2010-12-07 Thread gst
Hi,

I met a situation where I was passing an object created in/with an
upper level module class to a lower level module class' instance in
one of its __init__ argument and saving a ref of the upper object in
that lower level class' new instance.

But in my IDE I want the completion to also work from within the lower
level module when it's refering to the object passed from the upper
level:


Well, I'm sure I'm not very clear in my terms (and probably a bit long
in the sentence) so here it is in code:


files:
module1.py
subpackage/module2.py


file module1.py:

from subpackage.module2 import class2

class class1(object):

def __new__(cls, _self=None, *args, **kwargs):
if _self:  ## we've been passed an instance already
initialyzed
 ## so directly return it instead of creating a
new object.
return _self
return object.__new__(cls)

def __init__(self, _self=None, *args, **kwargs):
if _self:  ## we've been passed an instance already
initialyzed
 ## so directly returns
## assert(self is _self) ?
return
self.object2 = class2(object1=self, "blip", "blop")
# others init


file module2.py:

class class2(object):

def __init__(self, object1, *args, **kwargs):

from ..module1 import class1

self.object1 = class1(_self=object1)## instead of:
self.object1 = object1

## others functions and/or init..
## where  now I've completion working on self.object1 :
## if I add(or remove) fields/methods in module1 (and save) then
## I have them available(or disappeared) in the completion when
executed from this submodule.
## This ofcourse permits to save me of remembering all of the
class1 attributes/methods when I'm working with self.object1 from
within one of class2 methods.


What do you think of this ?

I guess there can be others ways of doing this..  ?

Thanks,

Regards,

Greg.

note: I'm using Eclipse 3.5.2 with pydev so (I don't really know how
others IDE can handle this case) .

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


Re: kinterbasdb error connection

2010-12-07 Thread Christian Heimes
Am 07.12.2010 16:35, schrieb Ale Ghelfi:
> (i'm under Ubuntu 10.10 amd64 and python 2.6 and kinterbasdb 3.2 )
> I try to connect my database of firebird 2.5 by kinterbasdb.
> But python return this error :
> 
>  >>> c = 
> kinterbasdb.connect(dsn="/media/VINACCIA.FDB",user="user",password="password",charset="UTF-8")
> Traceback (most recent call last):
>File "", line 1, in 
>  c = 
> kinterbasdb.connect(dsn="/media/VINACCIA.FDB",user="user",password="password",charset="UTF-8")
>File "/usr/lib/pymodules/python2.6/kinterbasdb/__init__.py", line 
> 435, in connect
>  return Connection(*args, **keywords_args)
>File "/usr/lib/pymodules/python2.6/kinterbasdb/__init__.py", line 
> 612, in __init__
>  b.dsn, b.dpb, b.dialect, timeout
> OperationalError: (-902, 'isc_attach_database: \n  I/O error during 
> "open" operation for file "/media/VINACCIA.FDB"\n  Error while trying to 
> open file\n  Permission denied')
> 
> By terminal of Ubuntu this is the permission of database:
> $ls -l /media/VINACCIA.FDB
> -rw-r--r-- 1 grappale grappale 1720320 2010-12-06 17:33 /media/VINACCIA.FDB
> 
> Where am i wrong? Please. Thank you!

Are you using classic mode or super mode? I have no experience with
classic mode but for super mode, the firebird user or group needs
permission to enter the directory (rx for / and /media) and to alter the
file (rw for media/VINACCIA.FDB). I suggest that you change the
permission to 664 and the group of the file to firebird.

Christian

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


Re: sqlite3 and UTF-8

2010-12-07 Thread Peter Otten
Ale Ghelfi wrote:

> I try to connect a database sqlite by sqlite3, but return an error.
> 
>  >>> rowset = cur.fetchall()
> Traceback (most recent call last):
>File "", line 1, in 
>  rowset = cur.fetchall()
> OperationalError: Could not decode to UTF-8 column 'DATO' with text
> 'Document n°10'
> 
> What's happend? thank you

How did you enter the data into the database? If it was with a script under 
your control modify it to feed unicode instead of str to the database.

Otherwise, if you know the encoding used in the database maybe setting  
Connection.text_factory

actual_encoding = ... # whatever
def decode(s): 
return s.decode(actual_encoding)

db = sqlite3.connect(...)
db.text_factory = decode


helps (untested). See also

http://docs.python.org/library/sqlite3.html#sqlite3.Connection.text_factory

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


Re: Books recommendation

2010-12-07 Thread Octavian Rasnita
Thank you for your help.

I have succeeded to create a Windows executable with py2exe.

I've seen that the source code of the sample script is hidden. Do you know if 
it happens the same if the script uses other Python modules I will make?
(Will py2exe hide the source code of those modules also?)

Thanks.

Octavian

- Original Message - 
From: "Anders Persson" 
Newsgroups: comp.lang.python
To: 
Sent: Tuesday, December 07, 2010 4:14 PM
Subject: Re: Books recommendation


You can't compile Python to exe files, but there is program packing
your script to a exe files, look att

www.py2exe.org

Beware that you must have py2exe version match your pythonversion and
att current time the highest version is 2.7.

/A


On Dec 7, 2:39 pm, "Octavian Rasnita"  wrote:
> Hello,
>
> Do you have, or can I find elsewhere a recommendation for books,tutorials and 
> sites appropriate for beginners?
>
> I have a lot of experience in Perl but I am interested to also learn Python 
> for:
> - web development (with frameworks similar with Catalyst and Ruby on Rails, 
> good templating systems, good ORMS and form processors)
> - Desktop apps with WxPython
> - Create MS Windows apps, executables, dlls, ActiveX, OS interaction...
> - Text parsing, regular expressions...
>
> I am also interested to find where I can get Python modules from and how... 
> similar tools and sites with cpan and ppm for Perl.
>
> Thank you.
>
> Octavian

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


Re: Task Engine Framework?

2010-12-07 Thread Adam Tauno Williams
On Mon, 2010-12-06 at 15:11 -0800, Nate wrote: 
> Hello,
> I'm in the process of developing a task engine / workflow module for
> my Python application and I'm wondering if anyone knows of existing
> code that could be used or adapted.  Since I know that's far too
> generic a question, let me share my goals:
> 1) Support long running operations (think backing up millions of
> files) where:
>- The operation can be paused (application closed) and the
> operation resumed later.
>- Individual tasks can be chained, run in parallel, or looped over
> (the workflow part)

We have something like that in OIE (OpenGroupware Integration Engine).
.  These things tend to turn out
to be quite specific [and thus not generic].  But if you have any
questions feel free to ask.  The focus in OIE was the ability to
describe processes in BPML and facilitate process management [creating,
queuing, parking (stopping for later resume) of business / ETL tasks.
Parts of the code aren't especially elegant but it does move a fairly
large amount of data every day.

> 2) Would like to graph each defined operation (task A starts task B
> with parameters... ) for documenting algorithms in Software Design
> Document
> 3) Each individual task in the operation would a self-contained
> class.  I'd imagine implementing its action by defining a doTask()
> method
> Hopefully that's clear.  I just feel like someone must have already
> solved this elegantly.  I greatly enjoy Python and I look forward to
> proving its use as a valuable language for a Masters student even
> though everyone thinks I should use C# :-).


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


Re: v = vte.Terminal() AttributeError: 'module' object has no attribute 'Terminal'

2010-12-07 Thread bruno.desthuilli...@gmail.com
On 7 déc, 12:05, Steve  wrote:
> Hi,
>
> I try to run a terminal emulation using Python+Gtk+Vte. Before develop
> my own sources, i'm testing some examples like this 
> ;http://www.eurion.net/python-snippets/snippet/Embed%20a%20VTE%20termi...
>
> But when i try to run, i get this message error;
>
>     v = vte.Terminal()
> AttributeError: 'module' object has no attribute 'Terminal'


Before any other thing, make sure the "vte" module you imported is the
expected one. Edit your script that way:


# import vte
try:
import vte
except:
error = gtk.MessageDialog (None, gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
'You need to install python bindings for libvte')
error.run()
sys.exit (1)
else:
print "using wte module : %s" % vte


and check the module path this prints to your stdout.

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


Re: sqlite3 and UTF-8

2010-12-07 Thread Ale Ghelfi

i try this :


actual_encoding = ... # whatever
def decode(s):
 return s.decode(actual_encoding)

db = sqlite3.connect(...)
db.text_factory = decode


but now the error is :

>>> rowset = cur.fetchall()
Traceback (most recent call last):
  File "", line 1, in 
rowset = cur.fetchall()
  File "", line 2, in decode
return s.decode(enc)
  File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb0 in position 33: 
invalid start byte

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


find memory leaks in running program

2010-12-07 Thread Marco Hornung
Hey,

--
questions
--
1. What are the best tools to analyze pythons memory stack, while it is running?
2. Is there a possibility to analyze the memory stack of a program with 
external programs? (without to change the source code - I am only interested in 
the object size)
3. Can I sort of "break" into the memory to see what objects consume how much 
memory?

--
my scenario
--
I have to debug a multithreaded server, which is written in the 
twisted-framework. One of the processes has some sort of memory leak - After 
one of our jobs is finished the main process has still over 59% of the entire 
memory allocated. I will probably have to recreate our scenario and equip our 
server with some memory sensors - but  it takes 12h to reproduce the scenario 
and I will have to change the source code(at least I do not know of other 
options).
Therefore I am looking for quicker possibilities to look into what causes our 
memory leak.

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


Re: sqlite3 and UTF-8

2010-12-07 Thread Peter Otten
Ale Ghelfi wrote:

> i try this :
> 
>> actual_encoding = ... # whatever
>> def decode(s):
>>  return s.decode(actual_encoding)
>>
>> db = sqlite3.connect(...)
>> db.text_factory = decode
> 
> but now the error is :
> 
>  >>> rowset = cur.fetchall()
> Traceback (most recent call last):
>File "", line 1, in 
>  rowset = cur.fetchall()
>File "", line 2, in decode
>  return s.decode(enc)
>File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode
>  return codecs.utf_8_decode(input, errors, True)
> UnicodeDecodeError: 'utf8' codec can't decode byte 0xb0 in position 33:
> invalid start byte

So you specified

actual_encoding = "UTF-8"

? That's pointless because UTF-8 is the default, and you've already seen 
that failing. You can set

db.text_factory = str

but you'll probably run into problems with that later, e. g. when you try to 
display the retrieved data.

So again, what data do you expect to find in the column(s) you can't decode 
properly?

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


Re: Task Engine Framework?

2010-12-07 Thread Nate
On Dec 7, 8:32 am, Adam Tauno Williams  wrote:
> On Mon, 2010-12-06 at 15:11 -0800, Nate wrote:
> > Hello,
> > I'm in the process of developing a task engine / workflow module for
> > my Python application and I'm wondering if anyone knows of existing
> > code that could be used or adapted.  Since I know that's far too
> > generic a question, let me share my goals:
> > 1) Support long running operations (think backing up millions of
> > files) where:
> >    - The operation can be paused (application closed) and the
> > operation resumed later.
> >    - Individual tasks can be chained, run in parallel, or looped over
> > (the workflow part)
>
> We have something like that in OIE (OpenGroupware Integration Engine).
> .  These things tend to turn out
> to be quite specific [and thus not generic].  But if you have any
> questions feel free to ask.  The focus in OIE was the ability to
> describe processes in BPML and facilitate process management [creating,
> queuing, parking (stopping for later resume) of business / ETL tasks.
> Parts of the code aren't especially elegant but it does move a fairly
> large amount of data every day.
>
>
>
>
>
>
>
> > 2) Would like to graph each defined operation (task A starts task B
> > with parameters... ) for documenting algorithms in Software Design
> > Document
> > 3) Each individual task in the operation would a self-contained
> > class.  I'd imagine implementing its action by defining a doTask()
> > method
> > Hopefully that's clear.  I just feel like someone must have already
> > solved this elegantly.  I greatly enjoy Python and I look forward to
> > proving its use as a valuable language for a Masters student even
> > though everyone thinks I should use C# :-).

Thank you,

I'll take a look at the project.  At the very least, seeing someone
else's solution would be helpful.  I'm trying desperately hard to keep
the code simple :-)

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


Re: Books recommendation

2010-12-07 Thread Mauro Caceres
>
>
> I am also interested to find where I can get Python modules from and how...
> similar tools and sites with cpan and ppm for Perl.
>
>
You should look at http://pypi.python.org/pypi, for modules.
pip (http://pip.openplans.org/) is a tool used to install python modules.

enjoy


-- 
Mauro Cáceres
-- 
http://mail.python.org/mailman/listinfo/python-list


select on multiprocessing Listener class

2010-12-07 Thread Thomas Burdick
The multiprocessing module has some wrappers for sockets and while the
Client object is selectable the Listener is not, I'm wondering if that
could be changed or if there's a way to do it already that I'm not
seeing?

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


Re: v = vte.Terminal() AttributeError: 'module' object has no attribute 'Terminal'

2010-12-07 Thread edicionsdigitals.com edicions digitals xarxa social slu
Solved! A really dummy error: I've a vte.py file in the same folder,
so import vte found this first than the needed!

Thanks! (and sorry)

Steve,

On 7 Des, 17:34, "bruno.desthuilli...@gmail.com"
 wrote:
> On 7 déc, 12:05, Steve  wrote:
>
> > Hi,
>
> > I try to run a terminal emulation using Python+Gtk+Vte. Before develop
> > my own sources, i'm testing some examples like this 
> > ;http://www.eurion.net/python-snippets/snippet/Embed%20a%20VTE%20termi...
>
> > But when i try to run, i get this message error;
>
> >     v = vte.Terminal()
> > AttributeError: 'module' object has no attribute 'Terminal'
>
> Before any other thing, make sure the "vte" module you imported is the
> expected one. Edit your script that way:
>
> # import vte
> try:
>     import vte
> except:
>     error = gtk.MessageDialog (None, gtk.DIALOG_MODAL,
> gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
>         'You need to install python bindings for libvte')
>     error.run()
>     sys.exit (1)
> else:
>     print "using wte module : %s" % vte
>
> and check the module path this prints to your stdout.

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


win32com pythonwin extensions part of stdlib?

2010-12-07 Thread harijay
Hi I am using Python 2.6.5 on Windows.

I wanted to start using the win32com extensions which I understand are
"essentially part of the stdlib" ( quoted in
http://tgolden.sc.sabren.com/python/win32_how_do_i.html)
Since I didnt have the extensions as standard  I went to sourceforge
to get the module.

However when I tried to do a distutils install of the python
extensions for windows downloaded from sourceforge , I found out I
need some proprietary components from Microsoft visual studio
7)."vcsvarsall.bat" needed.

My question is : Can I use the win32com extensions on a licensed
windows setup without having access to Visual Studio components.

I did see some places where they suggested compiling with mingw32 ,
but the compilation didnt work.

Any help in getting the module running would be greatly appreciated
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Task Engine Framework?

2010-12-07 Thread Tim Chase

On 12/07/2010 10:56 AM, Nate wrote:

On Dec 7, 8:32 am, Adam Tauno Williams  wrote:

I'm in the process of developing a task engine / workflow module for
my Python application and I'm wondering if anyone knows of existing
code that could be used or adapted.  Since I know that's far too
generic a question, let me share my goals:
1) Support long running operations (think backing up millions of
files) where:
- The operation can be paused (application closed) and the
operation resumed later.
- Individual tasks can be chained, run in parallel, or looped over
(the workflow part)


We have something like that in OIE (OpenGroupware Integration Engine).
.


I'll take a look at the project.  At the very least, seeing someone
else's solution would be helpful.  I'm trying desperately hard to keep
the code simple :-)


You might also want to look at Celery[1] which may do some (if 
not all) of what you're looking for.


-tkc

[1]
http://celeryproject.org





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


Re: win32com pythonwin extensions part of stdlib?

2010-12-07 Thread Godson Gera
Not sure what you are trying to do but you can get a standalone binaries
from http://sourceforge.net/projects/pywin32/ which gets installed without
any issues. If for some reason you are still having issues, you can try
ActiveState Python which come bundled with pywin32 packages.


On Tue, Dec 7, 2010 at 11:32 PM, harijay  wrote:

> Hi I am using Python 2.6.5 on Windows.
>
> I wanted to start using the win32com extensions which I understand are
> "essentially part of the stdlib" ( quoted in
> http://tgolden.sc.sabren.com/python/win32_how_do_i.html)
> Since I didnt have the extensions as standard  I went to sourceforge
> to get the module.
>
> However when I tried to do a distutils install of the python
> extensions for windows downloaded from sourceforge , I found out I
> need some proprietary components from Microsoft visual studio
> 7)."vcsvarsall.bat" needed.
>
> My question is : Can I use the win32com extensions on a licensed
> windows setup without having access to Visual Studio components.
>
> I did see some places where they suggested compiling with mingw32 ,
> but the compilation didnt work.
>
> Any help in getting the module running would be greatly appreciated
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 

Python Consultant India 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32com pythonwin extensions part of stdlib?

2010-12-07 Thread Ian
On Dec 7, 11:02 am, harijay  wrote:
> Hi I am using Python 2.6.5 on Windows.
>
> I wanted to start using the win32com extensions which I understand are
> "essentially part of the stdlib" ( quoted 
> inhttp://tgolden.sc.sabren.com/python/win32_how_do_i.html)
> Since I didnt have the extensions as standard  I went to sourceforge
> to get the module.
>
> However when I tried to do a distutils install of the python
> extensions for windows downloaded from sourceforge , I found out I
> need some proprietary components from Microsoft visual studio
> 7)."vcsvarsall.bat" needed.
>
> My question is : Can I use the win32com extensions on a licensed
> windows setup without having access to Visual Studio components.
>
> I did see some places where they suggested compiling with mingw32 ,
> but the compilation didnt work.
>
> Any help in getting the module running would be greatly appreciated

There are pre-built binary distributions available on sourceforge.
Why not just use one of those?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is py2exe still active ?

2010-12-07 Thread Octavian Rasnita
This packager is also nice.

If someone cares, I've discovered a small bug in it.
If Python is installed on another drive than C under Windows, the cxfreeze.bat 
file still calls Python on the drive C and it doesn't work until it is 
corrected.

Octavian

- Original Message - 
From: "Cbast" 
Newsgroups: comp.lang.python
To: 
Sent: Tuesday, December 07, 2010 5:00 PM
Subject: Re: is py2exe still active ?


On Dec 7, 8:23 am, Anders Persson  wrote:
> Hi!
> When a look att py2exe homepage it is not looking like mutch happen,
> as a beginner i was thinking to start with Python 3, but i like to now
> if py2exe will be for 3 too.
>
> Is any one have any info ?

I don't have the answer about py2exe, but I'm using cxFreeze to create
executables with Python 3.1, if it's what you're looking for.

http://cx-freeze.sourceforge.net/
-- 
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is py2exe still active ?

2010-12-07 Thread Grant Edwards
On 2010-12-07, Anders Persson  wrote:

> When a look att py2exe homepage it is not looking like mutch happen,

Why do you say that?  The homepage was update last month.  If you
click on "recent changes" the last wiki page edit was less than two
weeks ago, and there ahve been 19 posts to four different threads on
the mailing list so far this month.

> as a beginner i was thinking to start with Python 3, but i like to
> now if py2exe will be for 3 too.
>
> Is any one have any info ?

Probably.

https://lists.sourceforge.net/lists/listinfo/py2exe-users

-- 
Grant Edwards   grant.b.edwardsYow! Don't SANFORIZE me!!
  at   
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Books recommendation

2010-12-07 Thread Kee Nethery

On Dec 7, 2010, at 5:39 AM, Octavian Rasnita wrote:

> Do you have, or can I find elsewhere a recommendation for books,tutorials and 
> sites appropriate for beginners?

I have found that Python for Dummies is the book I use the most. It has lots of 
examples that work and that I can build upon. The O'Reilly books talk about the 
language but are scarce on actual code.

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


Re: win32com pythonwin extensions part of stdlib?

2010-12-07 Thread harijay
Using the "binary" offered on sourceforge and calling
"python setup.py install"

Has the install asking for "vcsvarsall.bat" . So this does not seem to
be a binary build



On Dec 7, 1:27 pm, Ian  wrote:
> On Dec 7, 11:02 am, harijay  wrote:
>
>
>
>
>
>
>
>
>
> > Hi I am using Python 2.6.5 on Windows.
>
> > I wanted to start using the win32com extensions which I understand are
> > "essentially part of the stdlib" ( quoted 
> > inhttp://tgolden.sc.sabren.com/python/win32_how_do_i.html)
> > Since I didnt have the extensions as standard  I went to sourceforge
> > to get the module.
>
> > However when I tried to do a distutils install of the python
> > extensions for windows downloaded from sourceforge , I found out I
> > need some proprietary components from Microsoft visual studio
> > 7)."vcsvarsall.bat" needed.
>
> > My question is : Can I use the win32com extensions on a licensed
> > windows setup without having access to Visual Studio components.
>
> > I did see some places where they suggested compiling with mingw32 ,
> > but the compilation didnt work.
>
> > Any help in getting the module running would be greatly appreciated
>
> There are pre-built binary distributions available on sourceforge.
> Why not just use one of those?

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


Re: win32com pythonwin extensions part of stdlib?

2010-12-07 Thread Tim Golden

You want something from here:

  http://sourceforge.net/projects/pywin32/files/pywin32/Build%20214/

Which one you need will depend on your architecture
and the version of Python you're running

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


Re: RCX using python serial help

2010-12-07 Thread MRAB

On 06/12/2010 15:37, Astan Chee wrote:

Hi,
I've got a lego mindstorm RCX 1.0 (but firmware is 2.0) that uses one of
those old serial IR towers to control the microcontroller. I've had a
look around at python's serial documentation as well as the RCX's
documentation and I'm trying to write something to control the RCX
directly using python. Several examples from of doing this in python
include using lnp (i think) and that doesn't quite run well in windows.
I've had a look at the C++ code and some protocol documentation here:
http://www.generation5.org/content/2001/rob08.asp and converted it to
python. I've attached it at the end of the email. So now I've figured
out how to check for the battery level and it seems to work (I've tested
it on my RCX) but I'm confused with the other documentation (e.g.
http://graphics.stanford.edu/~kekoa/rcx/ ) about how to do this in
python or what this all means. I was wondering if anyone can help me
complete these? or maybe help me do it step-by-step?
Thanks for any help.
Below is the python code I've been working on:
import time
import serial
import struct
import binascii
def tcbin(x, y=8):
"""
 This function returns the padded, two's complement representation
of x, in y-bits.
 It is conventional for y to be 8, 16, 32 or 64, though y can have
any non-zero positive value.
"""
 if x >= 0:
 binstr = bin(x)
 # pad with leading zeros
 while len(binstr) < y + 2:
 binstr = "0b0" + binstr[2:]
 return binstr
 return bin((2**y) + x) # x is negative
def bitcompliment(hex_code):
 return hex(int(tcbin(~(ord(hex_code))),2))

def processOutput(raw_data,output):
 outputStatus = True
 pos = 0
 for i in range(3):
 if raw_data[i] != output[i]:
 outputStatus = False
 pos+=1
 if outputStatus:
 print "output OK"
 else:
 print "problem with output"
 outputCompliment = True
 while outputCompliment:
 if hex(ord(output[pos])) == bitcompliment(output[pos+1]):
 print "output compliment OK"
 else:
 print "problem with output compliment"
 pos+=2
 if hex(ord(output[pos])) == '0x55' and hex(ord(output[pos+1]))
== '0xff' and hex(ord(output[pos+2])) == '0x0':
 pos+=3
 outputCompliment = False
 if hex(ord(output[pos])) == '0xcf' or hex(ord(output[pos])) == '0xc7':
 #battery checker
 pos+=2
 if hex(ord(output[pos])) == bitcompliment(output[pos+1]) and
hex(ord(output[pos+2])) == bitcompliment(output[pos+3]):
 s = ((ord(output[pos+2]) * 256) + ord(output[pos])) / 1000.0
 print "Battery is at " + str(s) + " Volts"
 else:
 for i in range(len(output[pos:]),len(output),2):
 print hex(ord(output[i]))
 if i+1 < len(output):
 if hex(ord(output[i])) == bitcompliment(output[i+1]):
 print "message OK. contents: " + hex(ord(output[i]))

# configure the serial connections (the parameters differs on the device
you are connecting to)
ser = serial.Serial(
  port='COM1',
  baudrate=2400,
  parity=serial.PARITY_ODD,
  stopbits=serial.STOPBITS_ONE,
  bytesize=serial.EIGHTBITS
)
raw_data = '\x55\xff\x00\x38\xc7\x38\xc7'
result = ser.write(raw_data)
out = ''
time.sleep(1) #pause for a second
while ser.inWaiting() > 0:
 out+=ser.read(1)
processOutput(raw_data,out)


Here's my version of your code:

import time
import serial
import struct
import binascii

# not needed!
def tcbin(x, y=8):
"""
This function returns the padded, two's complement representation 
of x, in y-bits.
It is conventional for y to be 8, 16, 32 or 64, though y can have 
any non-zero positive value.

"""
return "0b" + bin((2 ** y) + x)[-y : ]

def byte_complement(hex_code):
return (~ord(hex_code)) & 0xff

def process_output(raw_data, output):
output_status = raw_data[ : 3] == output[ : 3]
if output_status:
print "output OK"
else:
print "problem with output"
pos = 3
output_complement = True
while output_complement:
if ord(output[pos]) == byte_complement(output[pos + 1]):
print "output complement OK"
else:
print "problem with output complement"
pos += 2
if ord(output[pos]) == 0x55 and ord(output[pos + 1]) == 0xff 
and ord(output[pos + 2]) == 0x00:

pos += 3
output_complement = False
if ord(output[pos]) == 0xcf or ord(output[pos]) == 0xc7:
# battery checker
pos += 2
if ord(output[pos]) == byte_complement(output[pos + 1]) and 
ord(output[pos + 2]) == byte_complement(output[pos + 3]):

s = ((ord(output[pos + 2]) * 256) + ord(output[pos])) / 1000.0
print "Battery is at %s Volts" % s
else:
for i in range(len(output[pos : ]), len(output), 2):
print hex(ord(output[i]))
if i + 1 < len(output):
 

Re: win32com pythonwin extensions part of stdlib?

2010-12-07 Thread harijay
Thanks Ian for your reply.
I downloaded the zip file linked by the "Download Binaries/View All
files link" . All that gave me was a zip file which unpacked to the
source and documentation implying I had to use distutils.
If instead I  looked at the Build 214 link on sourceforge which
corresponds to the latest build ( same time stamp as the link labeled
"Download Binaries / View all Files")
There was an exe file corresponding to my python version.
Which came with an installer that installed the binaries


Thanks for your help I looked in the right place.

Hari

On Dec 7, 3:14 pm, harijay  wrote:
> Using the "binary" offered on sourceforge and calling
> "python setup.py install"
>
> Has the install asking for "vcsvarsall.bat" . So this does not seem to
> be a binary build
>
> On Dec 7, 1:27 pm, Ian  wrote:
>
>
>
>
>
>
>
> > On Dec 7, 11:02 am, harijay  wrote:
>
> > > Hi I am using Python 2.6.5 on Windows.
>
> > > I wanted to start using the win32com extensions which I understand are
> > > "essentially part of the stdlib" ( quoted 
> > > inhttp://tgolden.sc.sabren.com/python/win32_how_do_i.html)
> > > Since I didnt have the extensions as standard  I went to sourceforge
> > > to get the module.
>
> > > However when I tried to do a distutils install of the python
> > > extensions for windows downloaded from sourceforge , I found out I
> > > need some proprietary components from Microsoft visual studio
> > > 7)."vcsvarsall.bat" needed.
>
> > > My question is : Can I use the win32com extensions on a licensed
> > > windows setup without having access to Visual Studio components.
>
> > > I did see some places where they suggested compiling with mingw32 ,
> > > but the compilation didnt work.
>
> > > Any help in getting the module running would be greatly appreciated
>
> > There are pre-built binary distributions available on sourceforge.
> > Why not just use one of those?

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


Re: win32com pythonwin extensions part of stdlib?

2010-12-07 Thread harijay
Thanks Tim for your reply. I did get that build .
Also thanks for the examples. Looking forward to using the module

Hari

On Dec 7, 3:22 pm, Tim Golden  wrote:
> You want something from here:
>
>    http://sourceforge.net/projects/pywin32/files/pywin32/Build%20214/
>
> Which one you need will depend on your architecture
> and the version of Python you're running
>
> TJG

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


Python creates "locked" temp dir

2010-12-07 Thread utabintarbo
I am using tempfile.mkdtemp() to create a working directory on a
remote *nix system through a Samba share. When I use this on a Windows
box, it works, and I have full access to the created dir. When used on
a Linux box (through the same Samba share), the created directory
shows as "locked", and I am unable to access. Obviously, I need
access. Any clues?

Background/environment:
Python 2.6.5 on Red Hat Enterprise Linux 5.3

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


Re: find memory leaks in running program

2010-12-07 Thread shearichard
On Dec 8, 5:51 am, Marco Hornung  wrote:
> Hey,
>
> --
> questions
> --
> 1. What are the best tools to analyze pythons memory stack, while it is 
> running?
> 2. Is there a possibility to analyze the memory stack of a program with 
> external programs? (without to change the source code - I am only interested 
> in the object size)
> 3. Can I sort of "break" into the memory to see what objects consume how much 
> memory?
>
> --
> my scenario
> --
> I have to debug a multithreaded server, which is written in the 
> twisted-framework. One of the processes has some sort of memory leak - After 
> one of our jobs is finished the main process has still over 59% of the entire 
> memory allocated. I will probably have to recreate our scenario and equip our 
> server with some memory sensors - but  it takes 12h to reproduce the scenario 
> and I will have to change the source code(at least I do not know of other 
> options).
> Therefore I am looking for quicker possibilities to look into what causes our 
> memory leak.
>
> Regards,
> Marco

I haven't used this myself but sometime ago I bookmarked yappi which
may go some way towards helping you ...

http://code.google.com/p/yappi/
http://code.google.com/p/yappi/wiki/apiyappi

... also sometime ago I was at presentation (Pycon NZ 2009) where the
twisted.manhole functionality was used to hook a remote console up to
a running twisted task and examine the interior of the target task.
Can't remember the details but someone else here may be able to help.
This touches upon the idea ...

http://stackoverflow.com/questions/1721699/is-there-any-remote-console-for-twisted-server

... and in turn references Heapy which I'd forgotten about but may
also be useful in your circs ...

http://guppy-pe.sourceforge.net/

regards

Richard.



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


using trace to do 'in place' evaluation of variables

2010-12-07 Thread Edward Peschko
All,

I've been using the trace module for python (as per
http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html),
and would very much like to have a feature there that I've implemented
for perl already.

Namely, I would like output in the format as described on that page,
but with the ability to have the running window partitioned into 2,
like:


/tmp/file.py:13: yy = 12 |   = 12
/tmp/file.py14:  xx = yy |   = 12

where the window on the left shows the actual source code, and the
right shows how that code eval's (ie: how the scalars resolve based on
their current scope.)

Is this possible given the current trace functionality? I've found it
an *incredible* time saver with my perl code, especially for hard to
find data bugs - to debug I simply look for a pattern which is
associated with a given bug, and then backtrack that pattern to where
it first appeared in my code.

Also, is there a good archive searcher for the python-list archives?
Short of doing a complete download of
http://mail.python.org/pipermail/python-list/ and indexing it, I don't
see how I can do a decent pattern search on previous archive entries..

Thanks much,

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


Re: Collision of rotated rectangles without pygame

2010-12-07 Thread Martin Manns
On Tue, 07 Dec 2010 00:53:27 -0800
John Nagle  wrote:

> On 12/5/2010 2:49 PM, Martin Manns wrote:
> Probably because you seem to be trying to compute the intersection
> point for coincident lines, which is not well-defined.

I found the problem: 
pygame returns one pixel more for the right border than wx.

> Incidentally, a dictionary lookup in Python is far more expensive
> than computing trig functions.  If you need to speed this up
> for large numbers of rectangles, there are algorithms that are
> several orders of magnitude faster.  Realistically, though,
> this is the kind of problem that runs slow in CPython.

This was taken from the vizier code. I fixed it.

> This is why you don't write your own collision library.
> (I once did, for 3D, but that was in 1996, when it was
> cutting-edge technology.)

Is there a pure Python collision library other than vizier?

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


Re: is py2exe still active ?

2010-12-07 Thread Steve Holden
Octavian:

It's great that you want to let people know about bugs. Put yourself in
the position of the package maintainer, however. She or he doesn't spend
all day working on cxFreeze, and probably doesn't even do a Google
search on cxFreeze very often. So they are unlikely to find out about
this problem form your well-intentioned note.

It's just possible nobody does care, as I can't find a link to an issue
tracker - the best I could advise in this case would be to join the
mailing list by visiting

  https://lists.sourceforge.net/lists/listinfo/cx-freeze-users

regards
 Steve

On 12/7/2010 6:49 PM, Octavian Rasnita wrote:
> This packager is also nice.
> 
> If someone cares, I've discovered a small bug in it.
> If Python is installed on another drive than C under Windows, the 
> cxfreeze.bat file still calls Python on the drive C and it doesn't work until 
> it is corrected.
> 
> Octavian
> 
> - Original Message - 
> From: "Cbast" 
> Newsgroups: comp.lang.python
> To: 
> Sent: Tuesday, December 07, 2010 5:00 PM
> Subject: Re: is py2exe still active ?
> 
> 
> On Dec 7, 8:23 am, Anders Persson  wrote:
>> Hi!
>> When a look att py2exe homepage it is not looking like mutch happen,
>> as a beginner i was thinking to start with Python 3, but i like to now
>> if py2exe will be for 3 too.
>>
>> Is any one have any info ?
> 
> I don't have the answer about py2exe, but I'm using cxFreeze to create
> executables with Python 3.1, if it's what you're looking for.
> 
> http://cx-freeze.sourceforge.net/


-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17   http://us.pycon.org/
See Python Video!   http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparisons of incompatible types

2010-12-07 Thread John Nagle

On 12/6/2010 4:17 PM, Steven D'Aprano wrote:

On Mon, 06 Dec 2010 08:59:12 -0800, TomF wrote:


I'm aggravated by this behavior in python:

x = "4"
print x<  7# prints False



I can't imagine why this design decision was made.


You've never needed to deal with an heterogeneous list?

data = ["Fred", "Barney", 2, 1, None]
data.sort()

Nevertheless, I agree that in hindsight, the ability to sort such lists
is not as important as the consistency of comparisons.


   If you're thinking hard about this, I recommend viewing Alexander
Stepanov's talk at Stanford last month:

   http://www.stanford.edu/class/ee380/Abstracts/101103.html

He makes the point that, for generic programs to work right, the
basic operations must have certain well-defined semantics.  Then
the same algorithms will work right across a wide variety of
objects.

   This is consistent with Python's "duck typing", but inconsistent
with the current semantics of some operators.

   For example, "+" as concatenation makes "+" non-commutative.
In other words,

a + b

is not always equal to

b + a

which is not good.

Important properties to have across all types:

a + b == b + a

Exactly one of

a > b
a = b
a < b

is true, or an type exception must be raised.

The basic Boolean identities

(a or b) == (b or a)
not (a or b) == (not a) and (not b)
not (not a) == a

should all hold, or an type exception should be raised.
With Python accepting both "True" and "1" as sort of
equivalent, there are cases where those don't hold.

John Nagle

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


Re: Collision of rotated rectangles without pygame

2010-12-07 Thread Steve Holden
On 12/7/2010 9:53 AM, John Nagle wrote:
> On 12/5/2010 2:49 PM, Martin Manns wrote:
>> Hello,
>>
>> I am looking for a Python library for 2D collision checks of rotated
>> rectangles. Currently, I have found vizier 0.5b that is based on pygame.
>>
>> Since I do not want to add a pygame dependency to my app, I replaced the
>> pygame.rect.Rect by a wxPython wx.Rect (see code below).
>>
>> However, collision checks do not work correctly, i. e. identical rects
>> are not found to be colliding:
> 
>Probably because you seem to be trying to compute the intersection
> point for coincident lines, which is not well-defined.
> 
>I don't have time to debug this, but you might want to get some
> basic books on game programming and graphics.
> 
>Incidentally, a dictionary lookup in Python is far more expensive
> than computing trig functions.  If you need to speed this up
> for large numbers of rectangles, there are algorithms that are
> several orders of magnitude faster.  Realistically, though,
> this is the kind of problem that runs slow in CPython.
> 
That appears to be (from a rather limited investigation) a wild-assed
assertion unjustified by anything other than preconceptions.

With d as a dict containing 100 random numbers from (0,1) I see this:

>>> def fm():
... x = random.random()
... return math.sin(x)
...
>>> def fd():
... x = random.random()
... return x in d
...
>>> timeit.timeit(fm)
0.58099985122680664
>>> timeit.timeit(fd)
0.5524577636719
>>>

Of course it's possible that the random number generation is dominating,
but I'd still like to see some proof. I know for a fact that dict lookup
has been extensively optimized, and while I am no longer involved in
numerical computing it seems to me there's still a lot to do to compute
a sin unless your CPU will do it for you.

regards
 Steve

>This is why you don't write your own collision library.
> (I once did, for 3D, but that was in 1996, when it was
> cutting-edge technology.)
> 
> John Nagle


-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17   http://us.pycon.org/
See Python Video!   http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/

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


Re: Comparisons of incompatible types

2010-12-07 Thread Carl Banks
On Dec 6, 4:17 pm, Steven D'Aprano  wrote:
> On Mon, 06 Dec 2010 08:59:12 -0800, TomF wrote:
> > I'm aggravated by this behavior in python:
>
> > x = "4"
> > print x < 7    # prints False
> > I can't imagine why this design decision was made.
>
> You've never needed to deal with an heterogeneous list?
>
> data = ["Fred", "Barney", 2, 1, None]
> data.sort()

Not once, ever.


> Nevertheless, I agree that in hindsight, the ability to sort such lists
> is not as important as the consistency of comparisons.

I think that feeling the need to sort non-homogenous lists is
indictative of bad design.

If the order of the items doesn't matter, then there must be some
small bit of homogeneity to exploit to use as a sort criterion.  In
that case you should use key= parameter or DSU.


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


Re: Comparisons of incompatible types

2010-12-07 Thread Carl Banks
On Dec 7, 3:08 pm, John Nagle  wrote:
> The basic Boolean identities
>
>         (a or b) == (b or a)
>         not (a or b) == (not a) and (not b)
>         not (not a) == a
>
> should all hold, or an type exception should be raised.
> With Python accepting both "True" and "1" as sort of
> equivalent, there are cases where those don't hold.

For better or worse (and I say worse, but YMMV) "and" and "or" are not
boolean operators in Python but special-form expressions that resemble
boolean semantics in some instances, but not (as you mention above) in
others.

Likewise, the comparison operators <, >, >=, and <= aren't well-
ordered; sets use these operators to indicate topological ordering.

IMO having the operators adhere to defined properties would be a good
thing.  It would improve code reusability since the operators could be
expected to act in consistent ways, but Python isn't that language.
So you might as well use the operators for whatever seems like it
works, + for concatenation, > for superset, and so on.


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


Re: Perceived inconsistency in py3k documentation

2010-12-07 Thread Steve Holden
On 12/6/2010 8:00 PM, Antoine Pitrou wrote:
> On Sun, 05 Dec 2010 14:47:38 -0500
> Terry Reedy  wrote:
>> On 12/5/2010 3:31 AM, Greg wrote:
>>
>> For future reference,
>>
>>> 1) At http://docs.python.org/py3k/reference/datamodel.html:
>>> 2) At http://docs.python.org/py3k/library/stdtypes.html:
>>
>> do not work because of the trailing :s, at least not with FireFox.
> 
> Work fine here. The problem isn't Firefox, it is your e-mail or news
> client.
> 
> Antoine.
> 
> 
In my case also the links don't work, because my newsreader
(Thunderbird) makes the assumption that the colons are part of the URLs.
This behavior is common enough that people need to be aware of it.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17   http://us.pycon.org/
See Python Video!   http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RCX using python serial help

2010-12-07 Thread MRAB

On 06/12/2010 15:37, Astan Chee wrote:

Hi,
I've got a lego mindstorm RCX 1.0 (but firmware is 2.0) that uses one of
those old serial IR towers to control the microcontroller. I've had a
look around at python's serial documentation as well as the RCX's
documentation and I'm trying to write something to control the RCX
directly using python. Several examples from of doing this in python
include using lnp (i think) and that doesn't quite run well in windows.
I've had a look at the C++ code and some protocol documentation here:
http://www.generation5.org/content/2001/rob08.asp and converted it to
python. I've attached it at the end of the email. So now I've figured
out how to check for the battery level and it seems to work (I've tested
it on my RCX) but I'm confused with the other documentation (e.g.
http://graphics.stanford.edu/~kekoa/rcx/ ) about how to do this in
python or what this all means. I was wondering if anyone can help me
complete these? or maybe help me do it step-by-step?
Thanks for any help.

[snip]
Here's a brief summary of the protocol:

A command or request to the microcontroller is a packet consisting of a 
header, an opcode, arguments, and a checksum.


The header used in the documentation is 0x55, 0xFF, 0x00.

The opcode is 1 byte, followed by its one's complement.

The argument is 0 or more bytes, each followed by its one's complement.

	The checksum is the sum of the opcode and the arguments, modulo 256, 
followed by its one's complement.


A reply from the microcontroller is also a packet consisting of a 
header, an opcode, arguments, and a checksum.


The header is the same as the original command or request.

	The opcode is the one's complement of the original opcode, followed by 
its one's complement (ie, the original opcode).


The argument is 0 or more bytes, each followed by its one's complement.

	The checksum is the sum of the opcode and the arguments, modulo 256, 
followed by its one's complement.


The microcontroller will ignore a packet whose opcode is the same as the 
previous one; this is to prevent unintended duplicates due to 
communication errors.


Each opcode has 2 alternatives, one with bit 3 clear and the other with 
bit 3 set (bitwise-ored with 0x08), so if you do want to send a command 
or request with the same opcode as the previous packet you can just use 
the alternative form.

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


Re: Exception handling in Python 3.x

2010-12-07 Thread Steve Holden
On 12/7/2010 5:58 AM, John Nagle wrote:
>PEP 255, like too much Python literature, doesn't distinguish clearly
> between the language definition and implementation detail. It says
> "The mechanics of StopIteration are low-level details, much like the
> mechanics of IndexError in Python 2.1".  Applications shouldn't be
> explicitly using StopIteration.
>  
So you don't think that we should rely on iterables with no __iter__()
method to raise IndexError to terminate iterations when their
__getitem__() is called with an invalid index? The IndexError mechanism
was, to the best of my less-than-complete knowledge, used by all pre-2.2
implementations. The quoted paragraph appears to be intended to reassure
the applications programmer that there is no normal need to handle
StopIteration specially - just as there was no need to handle IndexError
specially.

>IronPython doesn't do StopIteration the same way CPython does.
> 
> http://ironpython.codeplex.com/wikipage?title=IPy1.0.xCPyDifferences
> 
Perhaps not, but the only difference is what happens on repeated calls
to next() after the iterator is exhausted. The iterator still terminates
by raising a StopIteration error.

I have no idea what Shed Skin does, but to the extent that iterators
don't raise StopIteration on exhaustion I'd say it is in error.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17   http://us.pycon.org/
See Python Video!   http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/

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


Re: Exception handling in Python 3.x

2010-12-07 Thread Steve Holden
On 12/7/2010 1:48 AM, MRAB wrote:
> Perhaps Python could use Guido's time machine to check whether the
> sequence will yield another object in the future. :-)

Since there's only one time machine that would effectively be a lock
across all Python interpreters.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17   http://us.pycon.org/
See Python Video!   http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparisons of incompatible types

2010-12-07 Thread Mark Wooding
John Nagle  writes:

[Stepanov]
> makes the point that, for generic programs to work right, the basic
> operations must have certain well-defined semantics.  Then the same
> algorithms will work right across a wide variety of objects.
>
> This is consistent with Python's "duck typing", but inconsistent with
> the current semantics of some operators.

This isn't a disaster.  You should check that the arguments define the
necessary operations and obey the necessary axioms.  Python is already
dynamically typed: this kind of proof-obligation is already endemic in
Python programming, so you've not lost anything significant.

> For example, "+" as concatenation makes "+" non-commutative.  In other
> words,
>
>   a + b
>
> is not always equal to
>
>   b + a
>
> which is not good.

I think I probably agree with this.  Concatenation yields a nonabelian
monoid (usually with identity); `+' is pretty much universally an
abelian group operator (exception: natural numbers, where it's used in
an abelian monoid which extends to a group in a relatively obvious way).
But then we'd need another operator symbol for concatenation.
Nonnegative integers act on strings properly, but the action doesn't
distribute over concatenation, which is also a shame.  i.e.,

n*(a + b) != n*a + n*b

But it's a familiar notation, by no means peculiar to Python, and
changing it would be difficult.

> Exactly one of
>
>   a > b
>   a = b
>   a < b
>
> is true, or an type exception must be raised.

This will get the numerical people screaming.  Non-signalling NaNs are
useful, and they don't obey these axioms.

I think, more generally, that requiring a full total order (rather than
either a preorder or a partial order) is unnecessarily proscriptive.
Sorting only requires a preorder, for example, i.e., { (a, b) | a <= b
<= a } is an equivalence relation, and the preorder naturally induces a
total order on the equivalence classes.  Topological sorting requires
only a partial order, and makes good use of the notation.  As an
example, sets use `<=' to denote subsetness, which is well known to be a
partial order.

(I presume you weren't going to deny

a <= b iff a < b or a == b

or

a < b iff b > a

because that really would be bad.)

> The basic Boolean identities
>
>   (a or b) == (b or a)
>   not (a or b) == (not a) and (not b)
>   not (not a) == a
>
> should all hold, or an type exception should be raised.

The first of these contradicts the axiom

x => x or _|_ == x

which is probably more useful.  The last can't usefully be true since
`not' is lossy.  But I think that, for all values a, b,

not (a or b) == not (b or a) == (not a) and (not b)
not (not (not a)) == not a

which is probably good enough.  (The application of `not' applies a
boolean coercion, which canonifies adequately.)

-- [mdw]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparisons of incompatible types

2010-12-07 Thread Mark Wooding
Carl Banks  writes:

> I think that feeling the need to sort non-homogenous lists is
> indictative of bad design.

Here's a reason you might want to.

You're given an object, and you want to compute a hash of it.  (Maybe
you want to see whether someone else's object is the same as yours, but
don't want to disclose the actual object, say.)  To hash it, you'll need
to serialize it somehow.  But here's a problem: objects like
dictionaries and sets don't impose an ordering on their elements.  For
example, the set { 1, 'two' } is the same as the set { 'two', 1 } -- but
iterating the two might well yield the elements in a different order.
(The internal details of a hash table tend to reflect the history of
operations on the hash table as well as its current contents.)

The obvious answer is to apply a canonical ordering to unordered objects
like sets and dictionaries.  A set can be serialized with its elements
in ascending order; a dictionary can be serialized as key/value pairs
with the keys in ascending order.  But to do this, you need an
(arbitrary, total) order on all objects which might be set elements or
dictionary keys.  The order also needs to be dependent only on the
objects' serializable values, and not on any incidental facts such as
memory addresses or whatever.

-- [mdw]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparisons of incompatible types

2010-12-07 Thread Ben Finney
Carl Banks  writes:

> On Dec 6, 4:17 pm, Steven D'Aprano  +comp.lang.pyt...@pearwood.info> wrote:
> > Nevertheless, I agree that in hindsight, the ability to sort such
> > lists is not as important as the consistency of comparisons.
>
> I think that feeling the need to sort non-homogenous lists is
> indictative of bad design.

It can also be indicative of code written for a Python that doesn't have
sets.

Comparing two list objects to see whether they have the same items in
any sequence can be done with::

set(foolist) == set(barlist)

but, if there is no ‘set’ type, it's fine to write::

sorted(foolist) == sorted(barlist)

So there's no design error in wanting heterogenerous sequences to sort;
it can be quite Pythonic (until the advent of the ‘set’ type).

And, of course, that code needs to continue to work in Python 2.x;
hence, the comparison of incompatible types cannot be fixed without
breaking backward compatibility. Hence it's not fixed until Python 3.x.

-- 
 \“All opinions are not equal. Some are a very great deal more |
  `\robust, sophisticated and well supported in logic and argument |
_o__) than others.” —Douglas Adams |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparisons of incompatible types

2010-12-07 Thread Paul Rubin
Ben Finney  writes:
> but, if there is no ‘set’ type, it's fine to write::
> sorted(foolist) == sorted(barlist)

what about dictionaries?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparisons of incompatible types

2010-12-07 Thread Ben Finney
Paul Rubin  writes:

> Ben Finney  writes:
> > but, if there is no ‘set’ type, it's fine to write::
> > sorted(foolist) == sorted(barlist)
>
> what about dictionaries?

Creating a needless dict for each list would make the code even less
clear, I'd think. (We're talking here about design, which is why clarity
of communicating semantic intent is a concern.)

Of course, the ‘set’ type is an even clearer way of communicating the
intent; so, the above doesn't need to work in Python 3, which can break
code written before the advent of the ‘set’ type.

-- 
 \   “But Marge, what if we chose the wrong religion? Each week we |
  `\  just make God madder and madder.” —Homer, _The Simpsons_ |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparisons of incompatible types

2010-12-07 Thread BartC



"Carl Banks"  wrote in message 
news:bf4be9a7-a079-4454-9969-60e9be305...@k14g2000pre.googlegroups.com...

On Dec 6, 4:17 pm, Steven D'Aprano  wrote:

On Mon, 06 Dec 2010 08:59:12 -0800, TomF wrote:
> I'm aggravated by this behavior in python:

> x = "4"
> print x < 7# prints False
> I can't imagine why this design decision was made.

You've never needed to deal with an heterogeneous list?

data = ["Fred", "Barney", 2, 1, None]
data.sort()


Not once, ever.



Nevertheless, I agree that in hindsight, the ability to sort such lists
is not as important as the consistency of comparisons.


I think that feeling the need to sort non-homogenous lists is
indictative of bad design.


Using a simple "<" comparison, perhaps. But can't a list be sorted by other 
criteria? For example, by comparing the string representations of each 
element.


So some sorts will make sense, and others (such as "<" or ">") won't.

--
Bartc 


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


completely implicit interpolation based on a frame object

2010-12-07 Thread Edward Peschko
All,

Ok, it looks like in order to implement a tracer that does
interpolation, I'm going to have to hack around with frames.

Perl's interpolation is fairly straightforward, to do interpolation of
$a == 1 all you need to do is put quotes around "$a == 1" to have $a
evaluated.

So, I'd like to do the same thing with python. It looks like I can do
the same thing with frames, ie:

 interpolate_frame(frame, "if not wx.Platform == '__WXMAC' ")

would interpolate wx based off of the frame that you passed to
interpolate_frame, because wx is in the f_locals or f_globals
dictionary.

Hence, this would become:

loc_wx = _first_defined(frame.f_locals["wx"], frame.f_globals["wx"])
return "if not ", loc_wx.Platform , " == \"__WXMAC\""

which would then do the interpolation.

I guess my question is - has something like this been released? I see
some close hits, namely Evan Forsmark's
http://www.evanfosmark.com/2008/06/string-interpolation-in-python/

but I don't see anything exact, and getting this right would be fairly
tricky, so I was hoping for canned solution.

Any ideas would be great on this, including pitfalls that people see
in implementing it.


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


group 0 in the re module

2010-12-07 Thread Yingjie Lan
Hi, 

According to the doc, group(0) is the entire match.

>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist") 
>>> m.group(0) # The entire match 'Isaac Newton' 

But if you do this:
>>> import re
>>> re.sub(r'(\d{3})(\d{3})', r'\0 to \1-\2', '757234')
'\x00 to 757-234'

where I expected
'757234 to 757-234'

Then I found that in python re '\0' is considered an octal number.
So, is there anyway to refer to the entire match by an escaped
notation?

Thanks,

Yingjie


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


convert assembly data (double words and bytes) in two tupple

2010-12-07 Thread joblack
I have two assembly data txt files, one has the structure:

0E1459D1Fh, 0AB58FAAEh, 4303E35Bh, 55FA3020h, 0E66D76ADh,
0EF434544h, ...

and the other has the structure:

53h, 6, 6Bh, 0D4h, 40h, 35h, 0B5h, 33h, 0AFh, 30h, 0B3h,
66h, ...

(I removed the dd and db with awk)

Now I want both of them in a tupple (like map1 = ( ... ) and map2 =
( ...) in my source code so I can index them..

Any idea how to give python a hint that the h at the end of the number
means it's a hex number? Or do I have to torture myself with regex to
get it right?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: group 0 in the re module

2010-12-07 Thread MRAB

On 08/12/2010 02:23, Yingjie Lan wrote:

Hi,

According to the doc, group(0) is the entire match.


m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
m.group(0) # The entire match 'Isaac Newton'


But if you do this:

import re
re.sub(r'(\d{3})(\d{3})', r'\0 to \1-\2', '757234')

'\x00 to 757-234'

where I expected
'757234 to 757-234'

Then I found that in python re '\0' is considered an octal number.
So, is there anyway to refer to the entire match by an escaped
notation?


Use \g<0>.

This notation works in the replacement template for both named and
numbered groups:

>>> re.sub(r'(\d{3})(\d{3})', r'\g<0> to \g<1>-\g<2>', '757234')
'757234 to 757-234'
>>> re.sub(r'(?P\d{3})(?P\d{3})', r'\g<0> to 
\g-\g', '757234')

'757234 to 757-234'
--
http://mail.python.org/mailman/listinfo/python-list


Re: convert assembly data (double words and bytes) in two tupple

2010-12-07 Thread Chris Rebert
On Tue, Dec 7, 2010 at 6:36 PM, joblack  wrote:
> I have two assembly data txt files, one has the structure:
>
> 0E1459D1Fh, 0AB58FAAEh, 4303E35Bh, 55FA3020h, 0E66D76ADh,
> 0EF434544h, ...
>
> and the other has the structure:
>
> 53h, 6, 6Bh, 0D4h, 40h, 35h, 0B5h, 33h, 0AFh, 30h, 0B3h,
> 66h, ...
>
> (I removed the dd and db with awk)
>
> Now I want both of them in a tupple (like map1 = ( ... ) and map2 =
> ( ...) in my source code so I can index them..
>
> Any idea how to give python a hint that the h at the end of the number
> means it's a hex number? Or do I have to torture myself with regex to
> get it right?

No regex necessary whatsoever:

# will be inefficient if file is huge
f = open("path/to/assembly/file/1")
content = f.read()
f.close()
map1 = [int(hexnum[:-1], 16) for hexnum content.split(", ")]
# do same thing for 2nd file

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Collision of rotated rectangles without pygame

2010-12-07 Thread Ian
On Dec 7, 4:11 pm, Steve Holden  wrote:
> >>> timeit.timeit(fm)
> 0.58099985122680664
> >>> timeit.timeit(fd)
> 0.5524577636719
>
> Of course it's possible that the random number generation is dominating,

I think that it is.  Moving the random number generation out into
setup:

>>> t1 = timeit.Timer("sin(x.next())", "from math import sin, radians; import 
>>> random; x = iter([random.random() for i in xrange(100)])")
>>> t1.timeit(100)
0.45154733352978838

>>> t2 = timeit.Timer("d[x.next()]", "import math, random; x = 
>>> iter([random.randrange(360) for i in xrange(100)]); d = dict((i, 
>>> math.sin(math.radians(i))) for i in xrange(360))")
>>> t2.timeit(100)
0.21765364033694823

Of course, the dict approach assumes that all angles will be an
integer number of degrees.  One could add precision, but looking up
specific float values in a dict is dicey, so then one has to switch to
decimal math, and that's going to add extra overhead -- probably
enough to tip the scales in favor of math.sin.

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


Re: convert assembly data (double words and bytes) in two tupple

2010-12-07 Thread MRAB

On 08/12/2010 02:36, joblack wrote:

I have two assembly data txt files, one has the structure:

0E1459D1Fh, 0AB58FAAEh, 4303E35Bh, 55FA3020h, 0E66D76ADh,
0EF434544h, ...

and the other has the structure:

53h, 6, 6Bh, 0D4h, 40h, 35h, 0B5h, 33h, 0AFh, 30h, 0B3h,
66h, ...

(I removed the dd and db with awk)

Now I want both of them in a tupple (like map1 = ( ... ) and map2 =
( ...) in my source code so I can index them..

Any idea how to give python a hint that the h at the end of the number
means it's a hex number? Or do I have to torture myself with regex to
get it right?


If you insist on not using regex (:-)) then:

>>> text = "53h, 6, 6Bh, 0D4h, 40h, 35h, 0B5h, 33h, 0AFh, 30h, 0B3h, 66h"
>>> data = [t.strip() for t in text.split(",")]
>>> data
['53h', '6', '6Bh', '0D4h', '40h', '35h', '0B5h', '33h', '0AFh', '30h', 
'0B3h', '66h']

>>> data = [int(d[ : -1], 16) if d[-1] == "h" else int(d) for d in data]
>>> data
[83, 6, 107, 212, 64, 53, 181, 51, 175, 48, 179, 102]
--
http://mail.python.org/mailman/listinfo/python-list


Re: group 0 in the re module

2010-12-07 Thread Yingjie Lan
: Use \g<0>.


Thanks! 

Though I wish all \1, \2, ..., should also be forbidden.
Such a mixture of things looks like a patch work.

No offense meant.

Yingjie



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


Re: Comparisons of incompatible types

2010-12-07 Thread TomF

On 2010-12-07 16:09:17 -0800, Mark Wooding said:


Carl Banks  writes:


I think that feeling the need to sort non-homogenous lists is
indictative of bad design.


Here's a reason you might want to.

You're given an object, and you want to compute a hash of it.  (Maybe
you want to see whether someone else's object is the same as yours, but
don't want to disclose the actual object, say.)  To hash it, you'll need
to serialize it somehow.  But here's a problem: objects like
dictionaries and sets don't impose an ordering on their elements.  For
example, the set { 1, 'two' } is the same as the set { 'two', 1 } -- but
iterating the two might well yield the elements in a different order.
(The internal details of a hash table tend to reflect the history of
operations on the hash table as well as its current contents.)

The obvious answer is to apply a canonical ordering to unordered objects
like sets and dictionaries.  A set can be serialized with its elements
in ascending order; a dictionary can be serialized as key/value pairs
with the keys in ascending order.  But to do this, you need an
(arbitrary, total) order on all objects which might be set elements or
dictionary keys.  The order also needs to be dependent only on the
objects' serializable values, and not on any incidental facts such as
memory addresses or whatever.


I have no argument that there might be an extra-logical use for such an 
ordering which you might find convenient.  This is the point you're 
making.  sort() and sorted() both take a cmp argument for this sort of 
thing.   My complaint is with Python adopting nonsensical semantics 
("shoe" < 7) to accomodate it.


By analogy, I often find it convenient to have division by zero return 
0 to the caller for use in calculations.  But if Python defined 0/0==0 
I'd consider it broken.


-Tom

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


Re: default behavior

2010-12-07 Thread Piet van Oostrum
Steven D'Aprano  writes:

> You don't need the space between strings and the attribute access: 
> "1".zfill(2) is fine. You only need it for numbers, due to the ambiguity 
> between the decimal point and dotted attribute access.

Personally I prefer parentheses: (1).conjugate
-- 
Piet van Oostrum 
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]
Nu Fair Trade woonartikelen op http://www.zylja.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Books recommendation

2010-12-07 Thread Oshan
hi kee,

i'm a beginner too.. when i asked the same question, some python gurus
recommended these books and videos.
in fact it worked.. so now i'm forwarding the same to you...


1. Core Python Programming by Wesley J. Chun
2. python quick reference guide - *http://rgruet.free.fr/#QuickRef.*
3. Python Phrasebook: Essential Code and Commands by Brad Dayley
4. Python pocket reference by mark luts (O'reilly)
5. PYTHON FOR SOFTWARE DESIGN - How to Think Like a Computer Scientist by
allen B Downey

6. Thenewboston video tutorials - *
http://www.thenewboston.com/?cat=40&pOpen=tutorial*
7. Showmedo video tutorials - *http://showmedo.com/videotutorials/python*

there are so many resources on internet for python. i have mentioned only
few, which i used to read.

all the best !!!

oshan.







On Wed, Dec 8, 2010 at 12:30 AM, Kee Nethery  wrote:

>
> On Dec 7, 2010, at 5:39 AM, Octavian Rasnita wrote:
>
> > Do you have, or can I find elsewhere a recommendation for books,tutorials
> and sites appropriate for beginners?
>
> I have found that Python for Dummies is the book I use the most. It has
> lots of examples that work and that I can build upon. The O'Reilly books
> talk about the language but are scarce on actual code.
>
> Kee Nethery
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using logging module to log either to screen or a file

2010-12-07 Thread RedBaron
On Dec 7, 7:33 pm, Jean-Michel Pichavant 
wrote:
> RedBaron wrote:
> > Hi,
> > I am beginner to python and i am writing a program that does a lot of
> > things. One of the requirements is that the program shud generate a
> > log file. I came across python loggging module and found it very
> > useful. But I have a few problems
> > Suppose by giving option '-v' along with the program the user can turn
> > off logging to a file and instead display log on the screen. Since I
> > am using a config file for logging, how do I accomplish this.
> > I tried to define two handlers (fil and screen) and added it to my
> > logger. But that logs data to both screen and the file. I need to log
> > it to only one. How do I dynamically remove one of the handler from
> > the logger based on user option. As a precursor how do i reference the
> > handlers defined in config file in the code??
>
> your logger has a public 'handlers' attribute.
>
> consoleHandlers = [h for h in logger.handlers if h.__class__ is
> logging.StreamHandler] # the list of handlers logging to the console
> (assuming they are instances of the StreamHandler class)
>
> if consoleHandlers:
>     h1 = consoleHandlers[0]
>     h1.filter = lambda x:True # enable the handler
>     h1.filter = lambda x:False # disable the handler
>
> JM

Thanks JM,
This works like charm. I had also though on similar lines bt I was
using isinstance(). I have two handlers - logging.RotatingFIleHandler
and StreamHandler. isinstance() was weird in the sense that no matter
which handle I checked for being 'StreamHandler' I always got true.
Also instead of setting filter to false, I was popping from the
handlers list...Silly me
Thanks a ton
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: completely implicit interpolation based on a frame object

2010-12-07 Thread Steve Holden
On 12/8/2010 2:49 AM, Edward Peschko wrote:
> All,
> 
> Ok, it looks like in order to implement a tracer that does
> interpolation, I'm going to have to hack around with frames.
> 
> Perl's interpolation is fairly straightforward, to do interpolation of
> $a == 1 all you need to do is put quotes around "$a == 1" to have $a
> evaluated.
> 
> So, I'd like to do the same thing with python. It looks like I can do
> the same thing with frames, ie:
> 
>  interpolate_frame(frame, "if not wx.Platform == '__WXMAC' ")
> 
> would interpolate wx based off of the frame that you passed to
> interpolate_frame, because wx is in the f_locals or f_globals
> dictionary.
> 
> Hence, this would become:
> 
> loc_wx = _first_defined(frame.f_locals["wx"], frame.f_globals["wx"])
> return "if not ", loc_wx.Platform , " == \"__WXMAC\""
> 
> which would then do the interpolation.
> 
> I guess my question is - has something like this been released? I see
> some close hits, namely Evan Forsmark's
> http://www.evanfosmark.com/2008/06/string-interpolation-in-python/
> 
> but I don't see anything exact, and getting this right would be fairly
> tricky, so I was hoping for canned solution.
> 
> Any ideas would be great on this, including pitfalls that people see
> in implementing it.
> 
http://docs.python.org/library/string.html#template-strings

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17   http://us.pycon.org/
See Python Video!   http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/

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