Re: 2to3 refactoring [was Re: Tuple parameter unpacking in 3.x]

2008-10-11 Thread Steven D'Aprano
On Sun, 05 Oct 2008 17:15:27 +0200, Peter Otten wrote:

> Steven D'Aprano wrote:
> 
>> PEP 3113 offers the following recommendation for refactoring tuple
>> arguments:
>> 
>> def fxn((a, (b, c))):
>> pass
>> 
>> will be translated into:
>> 
>> def fxn(a_b_c):
>> (a, (b, c)) = a_b_c
>> pass
>> 
>> and similar renaming for lambdas.
>> http://www.python.org/dev/peps/pep-3113/
>> 
>> 
>> I'd like to suggest that this naming convention clashes with a very
>> common naming convention, lower_case_with_underscores. That's easy
>> enough to see if you replace the arguments a, b, c above to something
>> more realistic:
>> 
>> def function(vocab_list, (result, flag), max_value)
>> 
>> becomes:
>> 
>> def function(vocab_list, result_flag, max_value)
>> 
>> Function annotations may help here, but not everyone is going to use
>> them in the same way, or even in a way that is useful, and the 2to3
>> tool doesn't add annotations.
>> 
>> It's probably impossible to avoid all naming convention clashes, but
>> I'd like to suggest an alternative which distinguishes between a
>> renamed tuple and an argument name with two words:
>> 
>> def function(vocab_list, (result, flag), max_value):
>> pass
>> 
>> becomes:
>> 
>> def function(vocab_list, t__result_flag, max_value):
>> result, flag = t__result_flag
>> pass
>> 
>> The 't__' prefix clearly marks the tuple argument as different from the
>> others. The use of a double underscore is unusual in naming
>> conventions, and thus less likely to clash with other conventions.
>> Python users are already trained to distinguish single and double
>> underscores. And while it's three characters longer than the current
>> 2to3 behaviour, the length compares favorably with the original tuple
>> form:
>> 
>> t__result_flag
>> (result, flag)
> 
> Let's see what the conversion tool does:
> 
> $ cat tmp.py
> g = lambda (a, b): a*b + a_b
> $ 2to3 tmp.py
> RefactoringTool: Skipping implicit fixer: buffer RefactoringTool:
> Skipping implicit fixer: idioms RefactoringTool: Skipping implicit
> fixer: ws_comma --- tmp.py (original)
> +++ tmp.py (refactored)
> @@ -1,1 +1,1 @@
> -g = lambda (a, b): a*b + a_b
> +g = lambda a_b1: a_b1[0]*a_b1[1] + a_b RefactoringTool: Files that need
> to be modified: RefactoringTool: tmp.py
> 
> So the current strategy is to add a numerical suffix if a name clash
> occurs. The fixer clearly isn't in final state as for functions instead
> of lambdas it uses xxx_todo_changeme.
> 
>> What do people think? Is it worth taking this to the python-dev list?
> 
> I suppose that actual clashes will be rare. If there is no clash a_b is
> the best name and I prefer trying it before anything else. I don't
> particularly care about what the fallback should be except that I think
> it should stand out a bit more than the current numerical suffix.
> xxx1_a_b, xxx2_a_b,... maybe?


Possibly you have misunderstood me. I'm not concerned with a clash 
between names, as in the following:

lambda a_b, (a, b): 
maps to -> lambda a_b, a_b: 

as I too expect they will be rare, and best handled by whatever mechanism 
the fixer users to fix any other naming clash.

I am talking about a clash between *conventions*, where there could be 
many argument names of the form a_b which are not intended to be two item 
tuples. 

In Python 2.x, when you see the function signature

def spam(x, (a, b))

it is clear and obvious that you have to pass a two-item tuple as the 
second argument. But after rewriting it to spam(x, a_b) there is no such 
help. There is no convention in Python that says "when you see a function 
argument of the form a_b, you need to pass two items" (nor should there 
be).

But given the deafening silence on this question, clearly other people 
don't care much about misleading argument names.

*wink*



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


prototpye wtp released

2008-10-11 Thread javascript fish
from:http://www.googlemother.com/wpblogs/?p=7281";>prototype
wtp
Prototype WTP 0.2 released,this release for Prototype 1.6.0

Prototype

Prototype is a JavaScript Framework that aims to ease development of
dynamic web applications. Featuring a unique, easy-to-use toolkit for
class-driven development and the nicest Ajax library around, Prototype
is quickly becoming the codebase of choice for web application
developers everywhere.
Eclipse WTP support javascript code content assistance,but does not
support prototype js.
prototypeWTP is a tool make Eclipse WTP support prototype js code
content assistance.
PDT(PHP Development Tools framework for the Eclipse platform) is based
on WTP,so the plug-in also support PDT.

prototypeWTP also support other tools based on WTP,such as MyEclipse
--
http://mail.python.org/mailman/listinfo/python-list


Re: Get "code object" of class

2008-10-11 Thread Okko Willeboordse
Thanks,

"Why do you even need the classes code object anyway?"

I need to instantiate and use the class in another process.
This other process doesn't has access to the py or pyc file
holding the m_class (source) code so I can't use pickle.

Something like;
In the first process (that has access to my_class (source) code) I do;

c = compile(inspect.getsource(my_class), "

Re: PyGUI as a standard GUI API for Python?

2008-10-11 Thread lkcl
> 3) Following the public rumor mill and the latest hype RIA i.e. the
> merge of web- and desktop applications with systems like Adobe AIR,
> JavaFX, Google Gears and MS Silverlight is the future of frontend
> development. With the exception of IronPython and Silverlight, Python
> hasn't even entered this game and no one knows if it ever will.

 http://pyjd.org
 tada :)
 (based on webkit, just like adobe air is).

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


Re: PyGUI as a standard GUI API for Python?

2008-10-11 Thread lkcl

> The role of Python is somewhat arbitrary. This could change only if
> Python becomes a client side language executed by AVM, V8 etc.

pyv8 - http://advogato.org/article/985.html
pyjs.py - standalone python-to-javascript compiler, see http://pyjs.org.

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


Re: PyGUI as a standard GUI API for Python?

2008-10-11 Thread lkcl
On Sep 17, 1:16 am, Todd Whiteman <[EMAIL PROTECTED]> wrote:
> Todd Whiteman wrote:
> > Mark Hammond's Python/Mozilla work has enabled products like Komodo,
> > Miro (Democracy) and the OLPC project to use Python as a major driver
> > for consistent cross-platform GUI applications.
>
> > Personally, I believe XULRunner has a lot to offer for Python GUI
> > development, I'm currently finishing up some documentation steps to show
> > off how to use it specifically for Python (I'll post it to this list
> > when it's finished).
>
> Here is the tutorial I've started in order to show off building a
> Python/XULRunner GUI 
> application.http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul...
>
> The details in this tutorial mostly targets a Windows/Linux platform
> (MacOSX is possible with a few deviations, I have tried to cover these
> deviations where applicable).
>
> Feedback is welcome.


oh for _goodness_ sake :)  i don't know whether to be derangedly-happy
and overexcited that pyxpcom and pydom exist, or whether to be annoyed
that i'll have to do _yet another_ port of the pyjamas widget set api
to another platform.

how come this stuff is so hard to find?  it's a _brilliant_ idea to be
running python in a web browser, direct.

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


Re: default value in __init__

2008-10-11 Thread Steven D'Aprano
On Fri, 10 Oct 2008 06:20:35 -0700, bearophileHUGS wrote:

>> I don't think simply re-executing the default argument expression on
>> each call works either: that would confuse at least as many people as
>> the current system.
> 
> May I ask you why? I think I don't agree, but I am not sure.

x = 100
def foo(a, b=x):
return a+b

first = foo(1)
x = 101
second = foo(1)

assert first == second


I think people will be rightly surprised that this fails.




>> It would be possible, but extremely annoying to limit default arguments
>> to being literal constants,
> 
> This is a possible solution, beside re-executing the default argument
> expression on each call.

That's no solution at all, because default arguments should not be 
limited to literal constants. That's unacceptable in my opinion.



>> unless you invent some kind of scheme for declaring that a type is safe
>> to use as a default argument.
> 
> Well, it seems functional-style programming may become more common in
> the future, and seeing languages like Scala, etc, maybe it can be useful
> to add to Python some way to define immutable classes (in an explicit
> way). Maybe subclasses of Immutable?

You're still assuming that the behaviour is a bug. It's not, it's a 
feature.


>> Even if you could change the behaviour of default arguments we would
>> still get equivalent regular questions from the people who initialise
>> class attributes with lists or dictionaries.
> 
> I have seen professional programmers too use class attributes instead of
> instance ones...

That's only a mistake if you don't mean to use class attributes instead 
of instance attributes.



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


comp.lang.python u see website get some doller

2008-10-11 Thread kavitha
www.artsandscience4.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to set the time of a directory?

2008-10-11 Thread [EMAIL PROTECTED]
On Oct 11, 1:27 am, "Timothy Grant" <[EMAIL PROTECTED]> wrote:
> On Fri, Oct 10, 2008 at 10:16 PM, oyster <[EMAIL PROTECTED]> wrote:
> > os.utime works only against files. so what to do for a directory?
> > thanx
>
> Not sure why you'd say that.
I am. He's running Windows.

>
> drwxr-xr-x  2 tjg  tjg       68 Oct 10 22:23 test
> ([EMAIL PROTECTED]) python
> Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16)
> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> import os
> >>> help(os.utime)
>
> Help on built-in function utime in module posix:
>
> utime(...)
>     utime(path, (atime, mtime))
>     utime(path, None)
>
>     Set the access and modified time of the file to the given values.  If the
>     second form is used, set the access and modified times to the current 
> time.
>
> >>> os.utime('test', None)
> >>> ^D
>
> ([EMAIL PROTECTED]) ls -ltr
> drwxr-xr-x  2 tjg  tjg       68 Oct 10 22:24 test
>
> --
> Stand Fast,
> tjg.  [Timothy Grant]


>>> os.utime('WinDir', None)
Traceback (most recent call last):
  File "(stdin)", line 1, in 
WindowsError: [Error 5] Access is denied: 'WinDir'
>>>


I consider this a bug. (Note that os.utime works for directories under
cygwin)


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


Re: default value in __init__

2008-10-11 Thread Steven D'Aprano
On Thu, 09 Oct 2008 01:39:30 -0700, kenneth (a.k.a. Paolo) wrote:

> On Oct 9, 10:14 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
>> kenneth wrote:
>> > the 'd' variable already contains the 'self.d' value of the first
>> > instance and not the default argument {}.
>>
>> > Am I doing some stupid error, or this is a problem ?
>>
>> No, it always contains the default argument because default values are
>> created just ONE
>> TIME.http://effbot.org/pyfaq/why-are-default-values-shared-between-
objects...
> 
> 
> Wow, it's a very "dangerous" behavior ...

No, it's very *useful* behaviour.


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


Re: type-checking support in Python?

2008-10-11 Thread Arnaud Delobelle
On Oct 7, 9:52 pm, Erik Max Francis <[EMAIL PROTECTED]> wrote:

> I have a unit system module (unity) in progress as well (it's working
> but it's as yet unreleased), but which takes a different approach which
> I think has more promise.  Instead of having multiple united types
> derived from different fundamental types, it has its own type Quantity
> which takes two arguments: the amount and the units (which are further
> data structures).  That way, the amount and the units are kept
> separately and the unit system doesn't know anything specific about the
> amount and only deals with the unit system.  Operations between
> quantities enforce the type system (either combining the units for
> operations like multiplication, or requiring that they be compatible for
> operations like addition or comparison), and simply perform the
> appropriate operations on the amount without enforcing any type.  This
> allows you to have united operations on integers, floating point
> numbers, decimals, vectors, matrices, quaternions -- whatever values you
> may want to support units.
>
> Mine is more of a dimensional analysis tool (as well as a general unit
> converter) since it allows you to define a basis of units, then define
> units within that basis and manipulate them -- thus it remembers the
> definitions of all the units it has encountered.  You can define whole
> new unit systems (e.g., c.g.s. vs. SI) and have them all relate to each
> other, or even define brand new unit systems (e.g., man-day-widgets for
> questions like, "If it takes one man three days to make two widgets, how
> many widgets can five men make in two weeks?").
>
> --
> Erik Max Francis && [EMAIL PROTECTED] &&http://www.alcyone.com/max/
>   San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
>    Those who forget the past are condemned to repeat it.
>     -- George Santayana

It's funny how many people have had the need for this!  I have written
a module that seems to be very similar.  It contains:

* A BasicDimension class whose objects are basis vectors in the
dimensions vector space.
* A Dimension class which is simply a vector in the dimension vector
space, which optionally can be named.

E.g.

distance = new_basic_dim('distance', 'metre')
mass = new_basic_dim('mass', 'gram')
time = new_basic_dim('time', 'second')

speed = new_dim('speed', distance/time)
accel = new_dim('accel', speed/time)

area = new_dim('area', distance**2)
volume = new_dim('volume', distance**3)

density = new_dim('density', mass/volume)

force = new_dim('force', mass*accel)

Then:

>>> volume/area
>>> distance

>>> speed*time
>>> distance

* A Units class whose objects can registered with a dimension

* DObject class whose objects are just objects with a dimension.  You
can do arithmetic with DObjects provided that you can do arithmetic
with their underlying objects.

>>> s = Units(time, 1)
>>> ms = Units(time, 0.001)
>>> s.symbol = 's'
>>> print DObject(2, s) + DObject(19, ms)
2.019 s
>>> m = Units(distance, 1)
>>> print DObject(3.0, m) / DObject(2.0, s)
1.5 [units distance*time**-1 1]
>>> Units(distance/time, 1).symbol = 'm/s'
>>> print DObject(3.0, m) / DObject(2.0, s)
1.5 m/s
>>> print DObject(23.0, s).convert_to(ms)
23000 ms

* You can also have separate 'Dimensions systems', e.g. you can have
speed, force, time as basic dimensions instead of distance, mass, time
(IOW you have a different basis for the dimensions vector space).
Then you can convert DObjects between systems.  Although this feature
is not working to my satisfaction.

I have designed this as part of a program to mark automatically online
maths/science worksheets, so speed is not really a consideration in my
implementation.

I have always thought of this as just a tool for my program, but I
suppose it can be seen as a sort of dynamic type checking system!

--
Arnaud

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


Re: PyGUI as a standard GUI API for Python?

2008-10-11 Thread lkcl
On Sep 3, 4:34 pm, Michael Palmer <[EMAIL PROTECTED]> wrote:

> So far, development of PyGUI seems to be a one-man effort, and it may
> be slowed down by the attempt to develop the API and the
> implementations concurrently. Could it be useful to uncouple the two,
> such that the API would be specified ahead of the implementation?


michael, i went back to the beginning of this thread, to reply to your
question, because i have some insights to share with you from my
failed attempts on porting pyjamas to the desktop - which you can
collect here: http://lkcl.net/pyjamas-desktop

there, you will find an IronPython-GtkSharp port; a pyqt4 port and a
pygtk2 port.  they were each failures in their own unique and special
ways.

to explain: pyjamas is a widget set api that looks desktop-like; you
write code in python, it's compiled to javascript; the DOM.py module
actually does things like document.getElementById() etc. etc. and in
this way you end up completely manipulating the DOM model, turning the
browser into just a giant desktop-like canvas.

in fact, the pyjamas widget set api is _so_ similar to a desktop api
that i decided to have a go at porting it _to_ the desktop.
eventually i succeeded.

the first attempt was with ironpython.  i actually got a long way with
this one - i chewed through the pyjamas examples in about a day.  i
had a small stumbling block implementing the HTML() widget, but
GtkSharp.HTML came to the rescue, there, and i was off again.
i then ran into a wall i decided not to bash my head against at such
an early stage (36 hours) - an implementation of XMLHTTPRequest
(remember - i was implementing every single bit of functionality that
a DOM model has access to).

so, i decided to port the ironpython port to pygtk2.  unfortunately,
whilst i got a lot further and managed to implement all of the
examples, there was no equivalent of HTML().  GTK itself totally lacks
a rich media content widget.  there is python-gtkhtml2 which is good,
but not good enough.  the much better gtkhtml3 library doesn't have
python bindings around it, and i wasn't in the mood to write any (and
hadn't at the time any experience with pygtk codegen.py).

also i heard that gtkhtml2 had been abandoned, and gtkhtml3 wasn't
going to be followed up on, and that there were rumours about webkit.

crucially - much more importantly - gtkhtml 2 and 3 have absolutely no
"automatic" resizing of the HTML content within them.  so, unless you
specify both the width and the height of the widget container, you end
up with a flatlined widget.  by that i mean a widget of say 200 pixels
in width but ZERO pixels in height!  and, as you may well know, if you
specify a width and height on a gtk widget, that's it: it's entirely
fixed.  there's no going back.  you're screwed.

this was an absolute killer.

with no foresight in the design of gtk or gtkhtml2 to make even a
_guess_ at the width and height of the content, the port was screwed.
i made half-hearted attempts to not specify width/height at all, but
all that that resulted in was piss-poor layout, and when you shrank
the app to small size, all the text disappeared because there was a
margin defaulting to 5px or so and all but the top left corner of the
text boxes would disappear!

so, there was no point in me attempting to make python bindings around
gtkhtml3, even though it has a system for inserting widgets into HTML
(using span ids).

and, even though there's python-gtkmozembed wrappers which would have
allowed me to embed flash plugins etc. into my application, thus
neatly emulating the way that html allows you to do that.

so - sadly - on to pyqt4.

well, i say sadly, but it was actually quite fun.  i'm doing a
complete comprehensive test of absolutely every single feature of the
major widget sets out there, crawling every single corner of their
functionality in order to map concepts one-for-one, and finding that
they don't really cope.

pyqt4.  again, i got a long long way.  the rich media support of qt4
allowed me to do widgets that looked reasonable.  i even had, by that
time, a non-asynchronous version of XMLHTTPRequest.  then i got to the
implementation of Grid() and FlexTable().  this is where it started to
go wrong.

pyqt4 has the concept of layouts.  a layout can be a horizontal
layout, vertical, grid, and you can even specify the percentage or
ratio of the width (or height) that individual cells can use. you
attach a layout to a widget; you can attach layouts to layouts.  you
can remove layouts from widgets.  what you _can't_ do is _remove_
layouts from layouts.

disappointingly, this was the killer, for me.  it was just getting...
too complicated.  i had already encountered advice that, in order to
implement the means to move widgets around, i should remove
*everything* and redo the layout.  it just... wasn't happening.

plus, i  think also that there are problems, again, with the HTML
layout: you can't _entirely_ stop text-squashing.  so, although pyqt4
was _better_, it sti

Re: Python pre-release announcements

2008-10-11 Thread Steven D'Aprano
On Wed, 08 Oct 2008 08:19:33 +1100, Ben Finney wrote:

>> I disagree.  These say exactly what has happened and tell me what I
>> want to know, which is that something new has been released, which is
>> to say, made available for download.
> 
> Which is entirely different from the “release” implicit in e.g. “release
> candidate”, hence they don't say what they appear to say. Since the
> latter term is unlikely to change, I'm asking that the announcements
> don't unnecessarily overload the meaning of “release”.

I've always hated the term "release candidate". It's been released, it is 
a release. A release candidate is something which may be released, but 
hasn't yet been chosen.


> > I disagree.  [ANN] could mean anything: planned? canceled? needs help?
> > ("Oh, 'released', why didn't you say so?")
> 
> As above, “released” is a poor term for this, since it *already* has
> connotations of “all done, out the door, ready to go” as evidenced
> in “release candidate” (not released, but we think it could be) and
> the distinction of the triumphant announcements that accompany
> *actual* releases.

I think you have it completely backwards. It's quite possible, even 
sensible, to release a draft paper, release an experimental prototype, or 
release an alpha version of software. I don't agree that "release" has 
any connotations of "all done" at all. Being released and being ready for 
release are orthogonal concepts: patients can be released from hospital 
before they are ready, and software can be released before it is in a fit 
state for production.

I don't know how some people have started using "released" to mean 
"production-ready", but it makes no sense to me and I wish they would 
stop. I think it is a poorly thought-out practice and it leads to people 
being confused when inaccurately titled "pre-release" versions are 
released.


[...]
> Whatever is chosen, please reserve “RELEASED” for the
> commonly-expected meaning of something akin to “no longer in
> intensive development or bug-hunting mode, now ready to go out on its
> own and be used with abandon by the masses”.


Commonly expected by who? That's certainly not any meaning of "released" 
in any dictionary I know of.




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


connection reset by peer error

2008-10-11 Thread gigs
I connect to web site with httplib.HTTPConnection. after some time i get this 
error: 104 "connection reset by peer". What exception i should use to catche 
this error


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


Re: connection reset by peer error

2008-10-11 Thread D'Arcy J.M. Cain
On Sat, 11 Oct 2008 15:52:48 +0200
gigs <[EMAIL PROTECTED]> wrote:
> I connect to web site with httplib.HTTPConnection. after some time i get this 
> error: 104 "connection reset by peer". What exception i should use to catche 
> this error

Well, what exception do you get?  Your traceback should tell you.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


pyserial: failed to readlines() after many hours running.

2008-10-11 Thread zxo102
Hello All,

I have a system. An instrument attched to 'com1' is wireless connected
to many sensors at different locations.  The instrument can forward
the  "commands" (from pyserial's write()) to those sensors.  Based on
the "commands",  the sensors keep sending corresponding data back to
the instrument which wraps up those data and put into "com1" . The
readlines() of pyserial pick up those data for processing.
The data ’string' does not have "\n".

With the following pythong script, if timeout = 0.1,  ser.readlines()
in thread1 failed to receive any data after approximate 20 hours. if
timeout=0.5,  ser.readlines() in thread1 failed to receive any data
after approximate 60 hours.  I am not sure the thread1 was dead or
not. But the whole script did not throw out any error information and
ser.write() in thread2 was ok and kept sending "commands" to com1.

I am testing "timeout = 1" right now, it will probably take more days
to fail to receive data.

Anybody knows how long I should set for "timeout"?  Since the data are
from different sensors, I have no idea when they arrive at com1 via
that instrument. If the timeout is set too long,  com1 (com1 has
buffer? Sorry, I don't know very much about hardwares) can not have
enough buffer to hold those coming data before ser.readlines(). Or how
does ser.readlines() work?

Should I use readline() instead of readlines()?

Thanks for your any help in advance.

The below is the script:


In thread 1:

import serial, time

ser=serial.Serial('com1', baudrate=9600, bytesize=8, parity='N',
stopbits=1, timeout=0.1,xonxoff=0, rtscts=0)

while 1:
 reading = ser.readlines()
 for i in range(len(reading)):
   if len(reading[i]) > 0:
aa = map(ord, reading[i])
bb = ["%02X"%aa[k] for k in range(len(aa))]
# do something here
  else:
pass
 time.sleep(ReadComSleepTime)
ser.close()

In thread 2:
...
while 1:
 ...
 ser.write("some commands here")
 ...
 time.sleep(30)



Best Regards

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


Re: extracting null pointer address from PyCObject with ctypes

2008-10-11 Thread Gordon Allott
Aaron "Castironpi" Brady wrote:
> 
> My pygame install just returns an integer in get_wm_info.  Take a
> look:
> 
 pygame.display.get_wm_info()
> {'window': 1180066, 'hglrc': 0}
 pygame.display.get_wm_info()['window']
> 1180066
 ctypes.c_void_p( _ )
> c_void_p(1180066)
> 
> You're suggesting yours looks like this:
> 
 pygame.display.get_wm_info()
> { ... 'display': ctypes.py_object( 1180066 ), ... }
> 
> What does type( display ) give you?
> --
> http://mail.python.org/mailman/listinfo/python-list

yes its different on windows and linux, windows only has a few items
where linux has many more. 'window' is just the window 'id'  at any rate
which is not the data I am after (which is internally an address to an
xlib structure)
this is what pygame.display.get_wm_info() returns on linux:
{'fswindow': 31457283, 'wmwindow': 31457284, 'window': 31457294,
'lock_func': , 'unlock_func': , 'display': }

note how the display object is a PyCObject, thats got the address I want
 inside it.


-- 
Gord Allott ([EMAIL PROTECTED])



signature.asc
Description: OpenPGP digital signature
--
http://mail.python.org/mailman/listinfo/python-list


Split entries from LDAP

2008-10-11 Thread Lars
Hi
I got some programming experience and I recently started looking into
Python. I've read much of the tutorial from 2.6 documentation. But it
was more interesting to get started on something I needed. I'm trying
to create a script that creates a variable list (just a txt file to be
included in bash scripts) with hosts from LDAP. The file will include
some static entries and the hosts based on 'cn', 'ipHostNumber' and I
might as well set the 'description' as commen,t when the list from
LDAP is created.
I got all the entries in the variable "raw_res" and I now got some
doubts on how to split each value up in every entry. Belove you can
see one of entries printed from the loop.
cn=world.dom.dk,ou=Hosts,o=Users,dc=dom,dc=dk', {'ipHostNumber':
['192.168.0.43'], 'cn': ['world.dom.dk'], 'description':
['Mail&webserver']})"

I've tried different things, but don't quite know to split the tuple.
The examples I've seen is with a nice clean list ("a", "b", "z"), and
mine is full of special characters and etc., so some direction would
be appreciated.


/Lars


--
#!/usr/bin/env python

import ldap, sys, ldif

# .: LDAP Connection Settings :.
server="NA"
username="NA"
passwd="NA"
basedn="NA"

try:
l = ldap.initialize(server)
l.protocol_version = ldap.VERSION3
l.simple_bind(username, passwd)
filter = '(objectClass=ipHost)'
attrs = ['cn','ipHostNumber','description']
raw_res = l.search_s( basedn, ldap.SCOPE_SUBTREE, filter, attrs )
except ldap.INVALID_CREDENTIALS:
print "Your username or password is incorrect."
sys.exit()
except ldap.LDAPError, e:
print e
sys.exit()

#print raw_res

for I in range(len(raw_res)):
print I, ": ",

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


Error code MP170

2008-10-11 Thread robin
PROBLEM

hi i'm Pauline Revelli'v just brought a canon pixma mp180/mp160. i
have installed the software and everything. the printer works fine but
the scanner dose not. it trys to scan but a thing comes up that says
its not plug in or cable not connected with numbers. the canon is
pluged in of cours becasue the printer works.

find solution here
http://pc-solution4u.blogspot.com/search/label/Canon%20PIXMA%20MP160%20All-In-One%20InkJet%20Printer
--
http://mail.python.org/mailman/listinfo/python-list


Ink level monitor on Canon Prixma...

2008-10-11 Thread robin
After the ink cartridge for the Canon Prixma MP 160 have been refilled
and test then I press the button Stop / Reset several times but
unfortunately the problem low ink indicator is still remaining as
before although I have done as some user online suggested. Please tell
me what to do the correct steps to resolve this issue.

find solution here
http://pc-solution4u.blogspot.com/search/label/Canon%20PIXMA%20MP160%20All-In-One%20InkJet%20Printer
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyserial: failed to readlines() after many hours running.

2008-10-11 Thread Grant Edwards
On 2008-10-11, zxo102 <[EMAIL PROTECTED]> wrote:

> I have a system. An instrument attched to 'com1' is wireless connected
> to many sensors at different locations.  The instrument can forward
> the  "commands" (from pyserial's write()) to those sensors.  Based on
> the "commands",  the sensors keep sending corresponding data back to
> the instrument which wraps up those data and put into "com1" . The
> readlines() of pyserial pick up those data for processing.
> The data ?string' does not have "\n".

If the data you're reading doesn't contain "\n", then you can't
use readline() or readlines().

-- 
Grant Edwards   grante Yow! I smell a RANCID
  at   CORN DOG!
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


I can't get the scanner to work on my mp160.

2008-10-11 Thread robin
PROBLEM

I have tried everything but I am unable to get the scanner to work . I
have reinstalled drivers checked connections I have windows 2000 and
all other requirements. There is a windows error code 31 that pops up.
This says check connections and make sure scanner is turned on.

find solution here

http://pc-solution4u.blogspot.com/search/label/Canon%20PIXMA%20MP160%20All-In-One%20InkJet%20Printer
--
http://mail.python.org/mailman/listinfo/python-list


sceanner connection to the pc

2008-10-11 Thread robin
PROBLEM

i have already installed the software canon mp 160..the machine can
print out the paper andn copy something perfectly..BUT, when i tried
to scan a paper to the PC,It can't work..there's is a message 'CANNOT
COMMUNICATE TO THE SCANNER. PLEASE TURN ON OR CONNECT THE MACHINE'
whereas i have turned it on..is there any body wants to help me with
this problem??

find solution here

http://pc-solution4u.blogspot.com/search/label/Canon%20PIXMA%20MP160%20All-In-One%20InkJet%20Printer
--
http://mail.python.org/mailman/listinfo/python-list


Scanning error

2008-10-11 Thread robin
PROBLEM

I connect to my laptop to scan pictures, and each time, each single
time the scanner will start scanning an inch but it stops and I get
the message Cannot communicate with scanner. Cable may be disconnected
or scanner may be turned off. Check status. Scanner driver will be
closed. Code: 2,155,0"The closest I get is it will scan one or two,
but same problem persists. Today I totally cannot scan one thing! What
is wrong?

find solution here
http://pc-solution4u.blogspot.com/search/label/Canon%20PIXMA%20MP160%20All-In-One%20InkJet%20Printer
--
http://mail.python.org/mailman/listinfo/python-list


Re: python debugger tips?

2008-10-11 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

Hi All,

I'm switching to python from perl, and like the language a ton, but I
find pdb and pydb to be vastly inferior debuggers to the perl version.

In particular, I've grown very used to stepping into arbitrary
functions interactively.  For instance, in perl you can do this:

casqa1:~> perl -de 42

Loading DB routines from perl5db.pl version 1.28
Editor support available.

Enter h or `h h' for help, or `man perldebug' for more help.

main::(-e:1):   42
  DB<1> sub foo {return 42}



  DB<2> s foo()
main::((eval 7)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:3):
3:  foo();


  DB<<3>> s
main::foo((eval 6)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:2):
2:  sub foo {return 42};
  DB<<3>>



Which is quite awesome; I don't have to restart the program if I want
to step through a given function call with a different set of values.


In your python shell:

import somelib
import pdb
pdb.runcall(somelib.somefunc, 42, foo='bar')


Also and IIRC, ipython (an alternative and more featurefull python 
shell) has some interesting stuff wrt/ pdb integration.


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


Re: HARD REAL TIME PYTHON

2008-10-11 Thread John Nagle

James Mills wrote:

$ ./bench.py -m latency -t 10 -f 100
Setting up latency Test...
Latency: 1.52 ms
Latency: 0.78 ms
Latency: 0.76 ms
Latency: 0.76 ms
Latency: 0.77 ms
Latency: 0.77 ms
Latency: 0.76 ms
Latency: 0.76 ms
Latency: 0.76 ms
Latency: 0.77 ms


Interesting.  Can you do something to get rid of that
transient on the first try?  What matters for hard real time
is the WORST value, not the average value.

Since Python is reference-counted, there's hope of using it
for hard real time.  If you use weak pointers for all back
pointers, and avoid pointer loops, you don't need garbage
collection.  Put the garbage collector into debug mode and
dump the garbage list after testing for a while to see if you
have any leaks.

CPython is slow, but can be made repeatable.

It helps if you run on a machine configured with no swap file,
(or an OS with no paging, like QNX) so you can be sure
there won't be any paging.  Then make sure you've gotten rid of
anything unwanted running in the background (always a headache
on Windows), and crank up the priority of your real-time task.

And put in a hardware stall timer.

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


Re: PyGUI as a standard GUI API for Python?

2008-10-11 Thread David Boddie
On Saturday 11 October 2008 11:19, lkcl wrote:

> pyqt4 has the concept of layouts.  a layout can be a horizontal
> layout, vertical, grid, and you can even specify the percentage or
> ratio of the width (or height) that individual cells can use. you
> attach a layout to a widget; you can attach layouts to layouts.  you
> can remove layouts from widgets.  what you _can't_ do is _remove_
> layouts from layouts.

You can remove layouts from layouts with the QLayout.removeItem() method.

> disappointingly, this was the killer, for me.  it was just getting...
> too complicated.  i had already encountered advice that, in order to
> implement the means to move widgets around, i should remove
> *everything* and redo the layout.  it just... wasn't happening.

You'll need to delete the contents of those layouts yourself - maybe that's
the real problem. You shouldn't need to redo the whole layout structure,
though.

> plus, i  think also that there are problems, again, with the HTML
> layout: you can't _entirely_ stop text-squashing.  so, although pyqt4
> was _better_, it still wasn't _enough_.

These days, you'd probably use PyQt4's WebKit integration for HTML
rendering, anyway, though I imagine that it doesn't help you much if
you're already using WebKit directly.

[...]

> QT4 lacks crucial layout management (layouts not being deletable from
> layouts), flow-layout, and variable-sized rich text.  they _do_ have
> proportional subdivision of layouts (allowing you to specify a fixed
> width on one cell and a percentage width on others) but it is very
> clumsy.

You can write your own layouts as well, but maybe that's more work than
you're prepared to do, especially now that you seem to have settled on
WebKit as your toolkit.

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


PyYAML: How to register my yaml.YAMLObject subclasses?

2008-10-11 Thread Matthew Wilson
I suspect the solution to my problem is something really trivial.

I wrote a module called pitz that contains a class Issue:

>>> pitz.Issue.yaml_tag
u'ditz.rubyforge.org,2008-03-06/issue'

Then I try to load a document with that same tag, but I get a
ConstructorError:

ConstructorError: could not determine a constructor for the tag
'!ditz.rubyforge.org,2008-03-06/issue'

I think there's some namespace/scoping problem, because when I define
the same class in my interpreter and then run yaml.load(issue_file),
everything works OK.

So, how do I tell yaml to build pitz.Issue instances when it runs across
that tag?

Do I need to use add_constructor?  If so, I'd *really* appreciate some
example usage.

Thanks!

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


Re: Efficient Bit addressing in Python.

2008-10-11 Thread Hendrik van Rooyen
"Aaron \"Castironpi\" Brady" wrote:

>This is tolerable. Â If you've got a better 'clear' operation than
>'xor', you're welcome to it.

*grin* xor is a toggle bit fuction, and I did not like the recursive
call in your code. so here is a module bsed on your BitSet:
(I hope my tabs survive the journey)


"""
Module with input and output int bit addressable classes.

Loosely based on Castironpi's BitSet code

"""

class inbits(object):
 """
 This is a 32 bit int of more or less addressable bits.
 """

 def __init__ (self, value = 0,*args ):
  """This constructs the int that keeps the bits,
 and makes a getbit function for each named bit from *args,
 so that we can retreive them by instance.bitname(),
 as well as by bool = instance[index_position]
  """

  self.value = value
  self.high_values = int('',16)
  for i,name in enumerate(args):
   def __getbit__(idx = i):
# Real i/o code has to be added here to read the right byte
return self.__getitem__(idx)
   self.__dict__[name] = __getbit__

 def __setitem__( self, index, value ):
  """Here we can set a bit based on its position."""

  if value:
   self.value |= (1 << index)
  else:
   self.value &= self.high_values ^ (1 << index)

 def __getitem__( self, index ):
  """This retreives a bit based on its position."""

  return 1 if self.value & (1<< index ) else 0

 def __repr__( self ):
  return repr( self.value )



class outbits(object):
 """
 This is a 32 bit int of more or less addressable bits.
 """

 def __init__ (self, value = 0,*args ):
  """This constructs the int that keeps the bits,
 and makes a setbit function for each named bit from *args,
 so that we can set them by instance.bitname(bool),
 as well as by instance[index_position] = bool
  """

  self.value = value
  self.high_values = int('',16)
  for i,name in enumerate(args):
   def __setbit__(value,idx = i):
self.__setitem__(idx,value)
# Real i/o code has to be added here to write the right byte out
   self.__dict__[name] = __setbit__

 def __setitem__( self, index, value ):
  """Here we can set a bit based on its position."""

  if value:
   self.value |= (1 << index)
  else:
   self.value &= self.high_values ^ (1 << index)

 def __getitem__( self, index ):
  """This retreives a bit based on its position."""

  return 1 if self.value & (1<< index ) else 0

 def __repr__( self ):
  return repr( self.value )



if __name__== '__main__':

 ins  = inbits(0,'b0','b1','b2','b3','b4','b5','b6','b7')
 outs = outbits(0,'b0','b1','b2','b3','b4','b5','b6','b7')
 ins[3] = 1
 outs.b4(1)
 print 'ins now',ins,'outs now',outs,'outs[4] is',outs[4],'ins.b3() is',ins.b3()


Comments are welcome...

- Hendrik




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


Re: Efficient Bit addressing in Python.

2008-10-11 Thread Hendrik van Rooyen
Ross Ridge  wrote:

>This is the code I use to convert large bit arrays to byte strings and
>back:
>
>import string
>import binascii
>import array

8<--- examples --

>I don't think you can do anything faster with standard modules, although
>it might not be efficient if you're only working with a single byte.

Thanks I was not aware of binascii module this looks powerful.

- Hendrik



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


Re: Efficient Bit addressing in Python.

2008-10-11 Thread Hendrik van Rooyen
Lie  wrote:

>> This of course means that there has to be another
>> thread active to actually do the i/o on a periodic basis,
>> gathering the outputs and writing them out, and reading
>> the inputs and scattering them to the various named input
>> bits
>
>Not necessarily. You've mentioned two ways.

True.

>> I would even not mind if I have to write:
>>
>> if e_stop():
>> put_everything_off()
>>
>> or:
>>
>> set(push,1)
>>
>
>PS: Umm, a little bit off note: set is a built-in name, I'm a little
>confused whether you meant on creating a "set" or setting the push bit
>to 1, if the latter case it might be better to use set and clear
>instead of passing a second parameter (and also to choose another
>name).
>
True. this was a brain fart - should have been setbit or something.

>.Alternatively, there is one more way:
>if bb.e_stop:
>bb.e_stop = 0
>where bb is some kind of "property bag" and .e_stop is a "property"
>instead of an "instance member".
>
what is the advantage?

8<-

>Rather than directly using getters and setters, I'd go with property.
>It (usually) makes a cleaner external interface of the class. And for
>the mess of having to write lots of boilerplate codes, you _could_
>dynamically generate the boilerplate code from a dictionary (of name
>to bit position) and currying (or something to that effect).
>Alternatively, you could also do some magic with getattr and setattr.

I am not too sure I know how...

- Hendrik

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


Looking for a web-based messaging system

2008-10-11 Thread John Oldweiler
Mike,

I hope you don't mind that I am reaching out to you this way.  I came
across your post on line and am looking for the exact same thing.   Did
you ever find something?

John 

 

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


Re: Porn Addiction Solutions?

2008-10-11 Thread Ph . T
BTW, this is the newsgroup of python.org, not python.com;
but python does have tools that let you synth new graphics from old,
and it would be interesting to know if there were
 any other programming approaches to this problem .

On Wed, Oct 8, 2008 at 12:07 PM, <[EMAIL PROTECTED]> wrote:

> Help, I'm addicted to porn. I've been spending a lot of time
> downloading hardcore porn and masturbating to it. It's ruining my
> life. I just found out that one of these sites somehow hacked my card
> and rang up $5K in charges which they won't even refund me. Even with
> that I haven't stopped my habit and it's only getting worse. How can I
> end this addiction?
>
> Any suggestions?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Americium Dream Documents
"(real opportunity starts with real documentation)
http://amerdreamdocs.tripod.com/ http://www.angelfire.com/psy/dr.addn/
--
http://mail.python.org/mailman/listinfo/python-list


Free to a good home - Python Pocket Reference

2008-10-11 Thread skip
Trying to get rid of stuff in preparation for moving I came across an unused
Python Pocket Reference by Mark Lutz (1st ed, published 1998).  If you'd
like it, drop me a note.  No charge for the book, but you pay the actual
postage.

-- 
Skip Montanaro - [EMAIL PROTECTED] - http://www.webfast.com/~skip/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python pre-release announcements

2008-10-11 Thread Terry Reedy

Steven D'Aprano wrote:

I've always hated the term "release candidate". It's been released, it is 
a release. A release candidate is something which may be released, but 
hasn't yet been chosen.


I agree.  They are candidates for the final release.  Suffix .c1, etc, 
instead of .rc1 would be sufficient.


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


Re: pyserial: failed to readlines() after many hours running.

2008-10-11 Thread Terry Reedy

Unknown wrote:

On 2008-10-11, zxo102 <[EMAIL PROTECTED]> wrote:


I have a system. An instrument attched to 'com1' is wireless connected
to many sensors at different locations.  The instrument can forward
the  "commands" (from pyserial's write()) to those sensors.  Based on
the "commands",  the sensors keep sending corresponding data back to
the instrument which wraps up those data and put into "com1" . The
readlines() of pyserial pick up those data for processing.
The data ?string' does not have "\n".


Do you have the option of having the instrument insert them between 
readings?




If the data you're reading doesn't contain "\n", then you can't
use readline() or readlines().


Use .read() instead.

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


Re: pyserial: failed to readlines() after many hours running.

2008-10-11 Thread Grant Edwards
On 2008-10-11, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2008-10-11, zxo102 <[EMAIL PROTECTED]> wrote:
>
>> I have a system. An instrument attched to 'com1' is wireless
>> connected to many sensors at different locations.  The
>> instrument can forward the "commands" (from pyserial's
>> write()) to those sensors.  Based on the "commands", the
>> sensors keep sending corresponding data back to the instrument
>> which wraps up those data and put into "com1" . The
>> readlines() of pyserial pick up those data for processing. The
>> data ?string' does not have "\n".
>
> If the data you're reading doesn't contain "\n", then you can't
> use readline() or readlines().

P.S.

To the OP: I normally block postings from google groups (which
is where almost all Usenet spam comes from), so I only saw your
posting because I was experimenting with my spam filtering.
I'll only see additional postings if you post from a real news
server or if somebody who does so quotes one of your postings.

Yes, that sort of sucks. But, until Google shuts off the spam
spigot, you're going to get short shrift if you post from
Google.

There are plenty of free news servers for the text groups like
c.l.p, or you can post to the mailing list via gmane.org.

-- 
Grant Edwards   grante Yow! They collapsed
  at   ... like nuns in the
   visi.comstreet ... they had no
   teen appeal!
--
http://mail.python.org/mailman/listinfo/python-list


how to acess mplayer with slavemode in python?

2008-10-11 Thread [EMAIL PROTECTED]
how to acess mplayer with slavemode in python?
--
http://mail.python.org/mailman/listinfo/python-list


What do _ast Load | Store | Del | AugLoad | AugStore | Param mean?

2008-10-11 Thread Eloff
In the _ast module Attribute, Subscript, Name, List, Tuple all have an
expr_context associated with them which is defined as:

expr_context = Load | Store | Del | AugLoad | AugStore | Param

I have no idea what they mean, and what's the difference between them.
I'm porting _ast to IronPython and this is the only part I've had
difficulty understanding. The only clue I've found is that all these
expressions are unique in that they can occur in assignment context.

Any insights at all?

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


Re: 2to3 refactoring [was Re: Tuple parameter unpacking in 3.x]

2008-10-11 Thread MRAB
On Oct 11, 8:23 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sun, 05 Oct 2008 17:15:27 +0200, Peter Otten wrote:
> > Steven D'Aprano wrote:
>
> >> PEP 3113 offers the following recommendation for refactoring tuple
> >> arguments:
>
> >> def fxn((a, (b, c))):
> >>     pass
>
> >> will be translated into:
>
> >> def fxn(a_b_c):
> >>     (a, (b, c)) = a_b_c
> >>     pass
>
> >> and similar renaming for lambdas.
> >>http://www.python.org/dev/peps/pep-3113/
>
> >> I'd like to suggest that this naming convention clashes with a very
> >> common naming convention, lower_case_with_underscores. That's easy
> >> enough to see if you replace the arguments a, b, c above to something
> >> more realistic:
>
> >> def function(vocab_list, (result, flag), max_value)
>
> >> becomes:
>
> >> def function(vocab_list, result_flag, max_value)
>
> >> Function annotations may help here, but not everyone is going to use
> >> them in the same way, or even in a way that is useful, and the 2to3
> >> tool doesn't add annotations.
>
> >> It's probably impossible to avoid all naming convention clashes, but
> >> I'd like to suggest an alternative which distinguishes between a
> >> renamed tuple and an argument name with two words:
>
> >> def function(vocab_list, (result, flag), max_value):
> >>     pass
>
> >> becomes:
>
> >> def function(vocab_list, t__result_flag, max_value):
> >>     result, flag = t__result_flag
> >>     pass
>
> >> The 't__' prefix clearly marks the tuple argument as different from the
> >> others. The use of a double underscore is unusual in naming
> >> conventions, and thus less likely to clash with other conventions.
> >> Python users are already trained to distinguish single and double
> >> underscores. And while it's three characters longer than the current
> >> 2to3 behaviour, the length compares favorably with the original tuple
> >> form:
>
> >> t__result_flag
> >> (result, flag)
>
> > Let's see what the conversion tool does:
>
> > $ cat tmp.py
> > g = lambda (a, b): a*b + a_b
> > $ 2to3 tmp.py
> > RefactoringTool: Skipping implicit fixer: buffer RefactoringTool:
> > Skipping implicit fixer: idioms RefactoringTool: Skipping implicit
> > fixer: ws_comma --- tmp.py (original)
> > +++ tmp.py (refactored)
> > @@ -1,1 +1,1 @@
> > -g = lambda (a, b): a*b + a_b
> > +g = lambda a_b1: a_b1[0]*a_b1[1] + a_b RefactoringTool: Files that need
> > to be modified: RefactoringTool: tmp.py
>
> > So the current strategy is to add a numerical suffix if a name clash
> > occurs. The fixer clearly isn't in final state as for functions instead
> > of lambdas it uses xxx_todo_changeme.
>
> >> What do people think? Is it worth taking this to the python-dev list?
>
> > I suppose that actual clashes will be rare. If there is no clash a_b is
> > the best name and I prefer trying it before anything else. I don't
> > particularly care about what the fallback should be except that I think
> > it should stand out a bit more than the current numerical suffix.
> > xxx1_a_b, xxx2_a_b,... maybe?
>
> Possibly you have misunderstood me. I'm not concerned with a clash
> between names, as in the following:
>
> lambda a_b, (a, b):
> maps to -> lambda a_b, a_b:
>
> as I too expect they will be rare, and best handled by whatever mechanism
> the fixer users to fix any other naming clash.
>
> I am talking about a clash between *conventions*, where there could be
> many argument names of the form a_b which are not intended to be two item
> tuples.
>
> In Python 2.x, when you see the function signature
>
> def spam(x, (a, b))
>
> it is clear and obvious that you have to pass a two-item tuple as the
> second argument. But after rewriting it to spam(x, a_b) there is no such
> help. There is no convention in Python that says "when you see a function
> argument of the form a_b, you need to pass two items" (nor should there
> be).
>
> But given the deafening silence on this question, clearly other people
> don't care much about misleading argument names.
>
> *wink*
>
Could it be a double underscore instead, eg a__b,
first_item__second_item?
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to set the time of a directory?

2008-10-11 Thread MRAB
On Oct 11, 1:18 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> On Oct 11, 1:27 am, "Timothy Grant" <[EMAIL PROTECTED]> wrote:> On Fri, Oct 
> 10, 2008 at 10:16 PM, oyster <[EMAIL PROTECTED]> wrote:
> > > os.utime works only against files. so what to do for a directory?
> > > thanx
>
> > Not sure why you'd say that.
>
> I am. He's running Windows.
>
>
>
>
>
> > drwxr-xr-x  2 tjg  tjg       68 Oct 10 22:23 test
> > ([EMAIL PROTECTED]) python
> > Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16)
> > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
> > Type "help", "copyright", "credits" or "license" for more information.>>> 
> > import os
> > >>> help(os.utime)
>
> > Help on built-in function utime in module posix:
>
> > utime(...)
> >     utime(path, (atime, mtime))
> >     utime(path, None)
>
> >     Set the access and modified time of the file to the given values.  If 
> > the
> >     second form is used, set the access and modified times to the current 
> > time.
>
> > >>> os.utime('test', None)
> > >>> ^D
>
> > ([EMAIL PROTECTED]) ls -ltr
> > drwxr-xr-x  2 tjg  tjg       68 Oct 10 22:24 test
>
> > --
> > Stand Fast,
> > tjg.  [Timothy Grant]
> >>> os.utime('WinDir', None)
>
> Traceback (most recent call last):
>   File "(stdin)", line 1, in 
> WindowsError: [Error 5] Access is denied: 'WinDir'
>
>
>
> I consider this a bug. (Note that os.utime works for directories under
> cygwin)

This in issue #214245 (2000-09-16). See also
http://mail.python.org/pipermail/python-bugs-list/2004-November/026124.html.
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2to3 refactoring [was Re: Tuple parameter unpacking in 3.x]

2008-10-11 Thread Aaron "Castironpi" Brady
On Oct 11, 2:23 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
snip
> I am talking about a clash between *conventions*, where there could be
> many argument names of the form a_b which are not intended to be two item
> tuples.
>
> In Python 2.x, when you see the function signature
>
> def spam(x, (a, b))
>
> it is clear and obvious that you have to pass a two-item tuple as the
> second argument. But after rewriting it to spam(x, a_b) there is no such
> help. There is no convention in Python that says "when you see a function
> argument of the form a_b, you need to pass two items" (nor should there
> be).
>
> But given the deafening silence on this question, clearly other people
> don't care much about misleading argument names.

No, we just document them. (ducks) And ambiguous is different from
misleading anyway.  If the docs say pass a 2-tuple as the 2nd
parameter...?
--
http://mail.python.org/mailman/listinfo/python-list


Re: extracting null pointer address from PyCObject with ctypes

2008-10-11 Thread Aaron "Castironpi" Brady
On Oct 11, 9:45 am, Gordon Allott <[EMAIL PROTECTED]> wrote:
> Aaron "Castironpi" Brady wrote:
>
> > My pygame install just returns an integer in get_wm_info.  Take a
> > look:
>
>  pygame.display.get_wm_info()
> > {'window': 1180066, 'hglrc': 0}
>  pygame.display.get_wm_info()['window']
> > 1180066
>  ctypes.c_void_p( _ )
> > c_void_p(1180066)
>
> > You're suggesting yours looks like this:
>
>  pygame.display.get_wm_info()
> > { ... 'display': ctypes.py_object( 1180066 ), ... }
>
> > What does type( display ) give you?
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> yes its different on windows and linux, windows only has a few items
> where linux has many more. 'window' is just the window 'id'  at any rate
> which is not the data I am after (which is internally an address to an
> xlib structure)
> this is what pygame.display.get_wm_info() returns on linux:
> {'fswindow': 31457283, 'wmwindow': 31457284, 'window': 31457294,
> 'lock_func': , 'unlock_func':  object at 0x89dfa88>, 'display': }
>
> note how the display object is a PyCObject, thats got the address I want
>  inside it.
>

What does print pythonapi.PyCObject_AsVoidPtr(display) give you?
--
http://mail.python.org/mailman/listinfo/python-list


Re: extracting null pointer address from PyCObject with ctypes

2008-10-11 Thread Gordon Allott
Aaron "Castironpi" Brady wrote:
> 
> What does print pythonapi.PyCObject_AsVoidPtr(display) give you?
> --
> http://mail.python.org/mailman/listinfo/python-list

Traceback (most recent call last):
  File "pygametest.py", line 125, in 
app = PyGameOGREApp()
  File "pygametest.py", line 33, in __init__
self._createWindow(width, height, fullscreen)
  File "pygametest.py", line 65, in _createWindow
print pythonapi.PyCObject_AsVoidPtr(display)
ctypes.ArgumentError: argument 1: : Don't
know how to convert parameter 1


-- 
Gord Allott ([EMAIL PROTECTED])



signature.asc
Description: OpenPGP digital signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: extracting null pointer address from PyCObject with ctypes

2008-10-11 Thread Aaron "Castironpi" Brady
On Oct 11, 1:59 pm, Gordon Allott <[EMAIL PROTECTED]> wrote:
> Aaron "Castironpi" Brady wrote:
>
> > What does print pythonapi.PyCObject_AsVoidPtr(display) give you?
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Traceback (most recent call last):
>   File "pygametest.py", line 125, in 
>     app = PyGameOGREApp()
>   File "pygametest.py", line 33, in __init__
>     self._createWindow(width, height, fullscreen)
>   File "pygametest.py", line 65, in _createWindow
>     print pythonapi.PyCObject_AsVoidPtr(display)
> ctypes.ArgumentError: argument 1: : Don't
> know how to convert parameter 1
>
> --
> Gord Allott ([EMAIL PROTECTED])
>
>  signature.asc
> < 1KViewDownload

If anyone knows this better, feel free to step in.

Put this before the call:

ctypes.pythonapi.PyCObject_AsVoidPtr.restype = ctypes.c_void_p
ctypes.pythonapi.PyCObject_AsVoidPtr.argtypes = [ ctypes.py_object ]

The reason is that this is the default signature, which is wrong:

>>> ctypes.pythonapi.PyCObject_AsVoidPtr.restype

>>> ctypes.pythonapi.PyCObject_AsVoidPtr.argtypes
>>>

There are other ways to prototype it if you like, too.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Free to a good home - Python Pocket Reference

2008-10-11 Thread Evans
On 11 Oct, 16:59, [EMAIL PROTECTED] wrote:
> Trying to get rid of stuff in preparation for moving I came across an unused
> Python Pocket Reference by Mark Lutz (1st ed, published 1998).  If you'd
> like it, drop me a note.  No charge for the book, but you pay the actual
> postage.
>
> --
> Skip Montanaro - [EMAIL PROTECTED] -http://www.webfast.com/~skip/

I was giving away a few weeks ago myself, but none them was a Python
book.
http://www.jroller.com/evans/entry/giving_away_unused_books I wouldn't
mind having it... will mail you directly.

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


Re: extracting null pointer address from PyCObject with ctypes

2008-10-11 Thread Gordon Allott
Aaron "Castironpi" Brady wrote:
 ctypes.pythonapi.PyCObject_AsVoidPtr.restype
> 
 ctypes.pythonapi.PyCObject_AsVoidPtr.argtypes


thank you so much, this works perfectly :)


-- 
Gord Allott ([EMAIL PROTECTED])



signature.asc
Description: OpenPGP digital signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyGUI as a standard GUI API for Python?

2008-10-11 Thread lkcl
On Oct 11, 3:31 pm, David Boddie <[EMAIL PROTECTED]> wrote:
> On Saturday 11 October 2008 11:19, lkcl wrote:
>
> > pyqt4 has the concept of layouts.  a layout can be a horizontal
> > layout, vertical, grid, and you can even specify the percentage or
> > ratio of the width (or height) that individual cells can use. you
> > attach a layout to a widget; you can attach layouts to layouts.  you
> > can remove layouts from widgets.  what you _can't_ do is _remove_
> > layouts from layouts.
>
> You can remove layouts from layouts with the QLayout.removeItem() method.

 yes... it didn't work.  a layout within a layout - i think it was a
QHorizontalLayout within a QGridLayout - didn't want to be removed.
it's probably a bug.
> These days, you'd probably use PyQt4's WebKit integration for HTML
> rendering, anyway, though I imagine that it doesn't help you much if
> you're already using WebKit directly.

 [see below...]

> You can write your own layouts as well, but maybe that's more work than
> you're prepared to do,

 definitely.

> especially now that you seem to have settled on
> WebKit as your toolkit.

 well, it just made vast amounts of sense - cut out all the middle
men.  if you're going to pull in a 17mb binary dependency, why do it
in a clumsy way?

 in order to pull in flash plugins and other material, the accepted
method in pygtk2 is to use python-gtk-mozplugger.  that's crazy.
embed an _entire_ web browser, just to pull in a flash component.
likewise, for doing a single bit of HTML, in pyqt4 and/or pygtk2, pull
in a 17mb binary dependency using python-webkit-qt4 and/or
pywebkitgtk, _just_ to display _one_ bit of HTML text??  _that's_
crazy.

especially as webkit actually has far better rendering capability,
features and flexibility than any of the standard desktop widget sets
which had been designed for the job!

wonderfully ironic...

oh - for completeness, if anyone's reading this and goes "no chance i
will _ever_ convert to the pyjamas API because i've spent so much time
writing pygtk2 apps" - there is a project by luis pamirez, where he
has _reimplemented_ gtk.py, gobject.py and gdk.py to sit _on top_ of
the pyjamas DOM model.

at present, it's only available in the subversion repository of
http://code.google.com, and you'll need to check out a revision some
time around sep 2007 of the llpamies branch.

basically, what that will give you is a means to run your pygtk2
applications... in a web browser!

very cool.  i'll do a port to pyjamas-desktop at some time, if i have
a need for it, and will be happy to help guide anyone who wants to
spend the time on it themselves.

> especially now that you seem to have settled on WebKit as your toolkit.

well, it's not _my_ toolkit - i just use it.  but you're right
inasmuch as i won't be initiating any new applications using pyqt4 or
pygtk2, not out of personal choice, anyway.

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


Re: book recommendation for Python newbie?

2008-10-11 Thread nage

I would have a look on Amazon at Python Programming: An Introduction to
Computer Science (Paperback)


-- 
nage

nage's Profile: http://nettechguide.com/forums/member.php?u=268
View this thread: http://nettechguide.com/forums/showthread.php?t=2242601

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


Re: PyGUI as a standard GUI API for Python?

2008-10-11 Thread lkcl
ofhttp://code.google.com, and you'll need to check out a revision some
> time around sep 2007 of the llpamies branch.

 rsrrmsrrwssrrfssnrssrr :)

 http://code.google.com/p/pyjamas then follow through to svn
instructions, bearing in mind that, other than the llpamies branch,
that code is out-of-date.
--
http://mail.python.org/mailman/listinfo/python-list


unicode .replace not working - why?

2008-10-11 Thread Kurt Peters
I'm using the code below to read a pdf document, and it has no line feeds 
or carriage returns in the imported text.  I'm therefore trying to just 
replace the symbol that looks like it would be an end of line (found by 
examining the characters in the "for loop") unichr(167).
  Unfortunately, the replace isn't working, does anyone know what I'm 
doing wrong?  I tried a number of things so I left comments in place as a 
subset of the bunch of things I tried to no avail.

Any help?
Kurt

#!/usr/bin/python
# -*- coding: utf-8 -+-
from pyPdf import PdfFileWriter, PdfFileReader
import unicodedata
fileencoding = "utf-16-LE" #"iso-8859-1" # "utf-8"
doc = PdfFileReader(file(r"C:\Documents and Settings\kpeters\My Documents
\SUA.pdf", "rb")

# print the title of document1.pdf
print "title = %s" % (doc.getDocumentInfo().title)
print "Subject:", doc.getDocumentInfo().subject
print "PDF Version:", doc.getDocumentInfo().producer
page4 = doc.getPage(3)
textu= page4.extractText()
#textu=textu.decode(fileencoding)
print type(textu)
#print type(textu.encode(fileencoding))
#textu=textu.encode(fileencoding)  #Converts to str
fn = unichr(167)
print('The char is %s' % fn)
textu.replace(unichr(167),'\n')
#print unicodedata.bidirectional(fn)   unichr(167)
for i, c in enumerate(textu):
if (i!=302):
print('# %d has char %s, ord: %d , char: %s, category %s, and 
Name: %s' % (i, c, ord(c), unichr(ord(c)), unicodedata.category(c), 
unicodedata.name(c)))

#if (ord(c)==167):
#print('Found it!')
#textu[i]='\n'
print('')
print textu
print textu.encode(fileencoding)
--
http://mail.python.org/mailman/listinfo/python-list


regular expression question (re module)

2008-10-11 Thread Faheem Mitha
Hi,

I need to match a string of the form

capital_letter underscore capital_letter number

against a string of the form

anything capital_letter underscore capital_letter number
some_stuff_not_starting with a number

Eg D_A1 needs to match with DUKE1_plateD_A1.CEL, but not any of
DUKE1_plateD_A10.CEL, Duke1_PlateD_A11v2.CEL,
DUKE1_plateD_A12.CEL.

Similarly D_A10 needs to match DUKE1_plateD_A10.CEL, but not any
of DUKE1_plateD_A1.CEL, Duke1_PlateD_A11v2.CEL,
DUKE1_plateD_A12.CEL.

Similarly D_A11 needs to match Duke1_PlateD_A11v2.CEL, but not any
of DUKE1_plateD_A1.CEL, DUKE1_plateD_A10.CEL,
DUKE1_plateD_A12.CEL.

Thanks in advance. Please cc me with any reply. 
Faheem.

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


Re: how to acess mplayer with slavemode in python?

2008-10-11 Thread Matthias Bläsing
Am Sat, 11 Oct 2008 10:46:51 -0700 schrieb [EMAIL PROTECTED]:

> how to acess mplayer with slavemode in python?

Have a look at:
http://developer.berlios.de/projects/lbrc/

the magic is done in LBRC/MPlayer.py there are two variants present - one 
utiliasing a FIFO, the other starting mplayer with a pipe opened.

HTH

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


Re: regular expression question (re module)

2008-10-11 Thread bearophileHUGS
Faheem Mitha:
> I need to match a string of the form
> ...

Please, show the code you have written so far, with your input-output
examples included (as doctests, for example), and we can try to find
ways to help you remove the bugs you have.

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


class point in python

2008-10-11 Thread [EMAIL PROTECTED]
i am looking for a python implementation of this class, a point X,Y
representation

http://msdn.microsoft.com/en-us/library/system.drawing.point_methods.aspx

is there any library that has this class?

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


Re: PyGUI as a standard GUI API for Python?

2008-10-11 Thread David Boddie
On Saturday 11 October 2008 21:40, lkcl wrote:
> On Oct 11, 3:31 pm, David Boddie <[EMAIL PROTECTED]> wrote:

>> You can remove layouts from layouts with the QLayout.removeItem() method.
> 
>  yes... it didn't work.  a layout within a layout - i think it was a
> QHorizontalLayout within a QGridLayout - didn't want to be removed.
> it's probably a bug.

Was it detached from the layout, but still visible?

[...]

>  in order to pull in flash plugins and other material, the accepted
> method in pygtk2 is to use python-gtk-mozplugger.  that's crazy.
> embed an _entire_ web browser, just to pull in a flash component.
> likewise, for doing a single bit of HTML, in pyqt4 and/or pygtk2, pull
> in a 17mb binary dependency using python-webkit-qt4 and/or
> pywebkitgtk, _just_ to display _one_ bit of HTML text??  _that's_
> crazy.

Sure, if all you want to do is display one bit of HTML text. It always
helps if you choose the most appropriate libraries for each task.

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


Re: PyGUI as a standard GUI API for Python?

2008-10-11 Thread Terry Reedy

lkcl wrote:

I got the impression that there is currently no Windows binary 
available.  Correct?  If not, perhaps someone trustworthy will someday 
donate one.


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


Re: How to do regular BASH work in Python?

2008-10-11 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Michael
Torrie wrote:

> But unfortunately Python is definitely not a shell-scripting language
> and some things that are easy in bash are really, really hard in
python ...

Why not combine the two
.
--
http://mail.python.org/mailman/listinfo/python-list


Re: unicode .replace not working - why?

2008-10-11 Thread John Machin
On Oct 12, 7:05 am, Kurt Peters <[EMAIL PROTECTED]> wrote:
> I'm using the code below to read a pdf document, and it has no line feeds
> or carriage returns in the imported text.  I'm therefore trying to just
> replace the symbol that looks like it would be an end of line (found by
> examining the characters in the "for loop") unichr(167).
>   Unfortunately, the replace isn't working, does anyone know what I'm
> doing wrong?  I tried a number of things so I left comments in place as a
> subset of the bunch of things I tried to no avail.

This is the first time I've ever looked inside a PDF file, and *only*
one file, but:

import pyPdf, sys
filename = sys.argv[1]
doc = pyPdf.PdfFileReader(open(filename, "rb"))
for pageno in range(doc.getNumPages()):
page = doc.getPage(pageno)
textu = page.extractText()
print "pageno", pageno
print type(textu)
print repr(textu)

gives me  and text with lots of \n at places where
you'd expect them.

The only problem I can see is that where I see (and expect) quotation
marks (U+201C and U+201D) when viewing the file with Acrobat Reader,
the repr is showing \ufb01 and \ufb02. Similar problems with em-dashes
and apostrophes. I had a bit of a poke around:

1. repr(result of FlateDecode) includes *both* the raw bytes \x93 and
\x94, *and* the octal escapes \\223 and \\224 (which pyPdf translates
into \x93 and \x94).

2. Then pyPdf appears to push these through a fixed transformation
table (_pdfDocEncoding in generic.py) and they become \ufb01 and
\ufb02.

3. However:
|>>> '\x93\x94'.decode('cp1252') # as suspected
|u'\u201c\u201d' # as expected
|>>>

AFAICT there is only one reference to encoding in the pyPdf docs: "if
pyPdf was unable to decode the string's text encoding" ...

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


Re: connection reset by peer error

2008-10-11 Thread gigs

D'Arcy J.M. Cain wrote:

On Sat, 11 Oct 2008 15:52:48 +0200
gigs <[EMAIL PROTECTED]> wrote:
I connect to web site with httplib.HTTPConnection. after some time i get this 
error: 104 "connection reset by peer". What exception i should use to catche 
this error


Well, what exception do you get?  Your traceback should tell you.


i dont remember now
my problem is now that i need to wait few hours to get this error. now i close 
my connection after one hour and reconnect. so i dont get that error anymore, 
but i would like to catch that error and reconect after it happens.


i dont have time to wait for that error now.
--
http://mail.python.org/mailman/listinfo/python-list


Unicode equality from raw_input

2008-10-11 Thread Damian Johnson
Hi, when getting text via the raw_input method it's always a string (even if
it contains non-ASCII characters). The problem lies in that whenever I try
to check equality against a Unicode string it fails. I've tried using the
unicode method to 'cast' the string to the Unicode type but this throws an
exception:

>>> a = raw_input("text: ")
text: おはよう
>>> b = u"おはよう"
>>> a == b
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both
arguments to Unicode - interpreting them as being unequal
False
>>> type(a)

>>> type(b)

>>> unicode(a)
Traceback (most recent call last):
  File "", line 1, in 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0:
ordinal not in range(128)
>>> str(b)
Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3:
ordinal not in range(128)


After a couple hours of hair pulling I think it's about time to admit
defeat. Any help would be appreciated! -Damian
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyserial: failed to readlines() after many hours running.

2008-10-11 Thread zxo102
On 10月11日, 下午11时00分, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On2008-10-11,zxo102<[EMAIL PROTECTED]> wrote:
>
> > I have a system. An instrument attched to 'com1' is wireless connected
> > to many sensors at different locations.  The instrument can forward
> > the  "commands" (from pyserial's write()) to those sensors.  Based on
> > the "commands",  the sensors keep sending corresponding data back to
> > the instrument which wraps up those data and put into "com1" . The
> > readlines() of pyserial pick up those data for processing.
> > The data ?string' does not have "\n".
>
> If the data you're reading doesn't contain "\n", then you can't
> use readline() or readlines().
>
> --
> Grant Edwards   grante Yow! I smell a RANCID
>   at   CORN DOG!
>visi.com

But readlines() can read data out of 'com1' for many hours. Maybe I
should try read().

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


Re: pyserial: failed to readlines() after many hours running.

2008-10-11 Thread zxo102
On 10月12日, 上午1时13分, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Unknown wrote:
> > On2008-10-11,zxo102<[EMAIL PROTECTED]> wrote:
>
> >> I have a system. An instrument attched to 'com1' is wireless connected
> >> to many sensors at different locations.  The instrument can forward
> >> the  "commands" (from pyserial's write()) to those sensors.  Based on
> >> the "commands",  the sensors keep sending corresponding data back to
> >> the instrument which wraps up those data and put into "com1" . The
> >> readlines() of pyserial pick up those data for processing.
> >> The data ?string' does not have "\n".
>
> Do you have the option of having the instrument insert them between
> readings?
>
>
>
> > If the data you're reading doesn't contain "\n", then you can't
> > use readline() or readlines().
>
> Use .read() instead.

I can not have the instrument insert "\n" between readings. That is
out of my control. I can try read(). Thanks.

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


Define a 2d Array?

2008-10-11 Thread Jillian Calderon
Hi.

How do I define a 2d list?

For instance, to define a 4 by 5 list, I wanted to do this:
n=4
m=5
world = [n][m]
However, it gives me an invalid syntax error saying the index is out
of range.
I know this is a real newbie question, but if you could help me out,
I'd really appreciate it!

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


Re: What do _ast Load | Store | Del | AugLoad | AugStore | Param mean?

2008-10-11 Thread Benjamin
On Oct 11, 12:57 pm, Eloff <[EMAIL PROTECTED]> wrote:
> In the _ast module Attribute, Subscript, Name, List, Tuple all have an
> expr_context associated with them which is defined as:
>
> expr_context = Load | Store | Del | AugLoad | AugStore | Param
>
> I have no idea what they mean, and what's the difference between them.
> I'm porting _ast to IronPython and this is the only part I've had
> difficulty understanding. The only clue I've found is that all these
> expressions are unique in that they can occur in assignment context.
>
> Any insights at all?

They refer to how the expression is used in its context. You can cross
AugLoad and AugStore off because they are not used by the current
implementation. I hope this code examples will explain the rest:

Load:
a = 2
Module(body=[Assign(targets=[Name(id='a', ctx=Store())],
value=Num(n=2))])

Store:
print a
Module(body=[Print(dest=None, values=[Name(id='a', ctx=Load())],
nl=True)])

Del:
del a
Module(body=[Delete(targets=[Name(id='a', ctx=Del())])])

Param:
def f(a): pass
Module(body=[FunctionDef(name='f', args=arguments(args=[Name(id='a',
ctx=Param())], vararg=None, kwarg=None, defaults=[]), body=[Pass()],
decorator_list=[])])

I hope that helps!
>
> Thanks,
> -Dan

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


Decrease code redundancy without breaking references

2008-10-11 Thread bmalinova
My settings file
---
from global_settings import *

SITE_FOLDER   = 'mypipe'
SITE_DOMAIN   = 'localhost'
SITE_NAME = 'My Pipe'
SITE_ID   = 1

TEMPLATE_DIRS = ("/clients/"+SITE_FOLDER+"/templates", "/packages/apps/
templates")
MEDIA_FILES_PREFIX = 'http://'+SITE_DOMAIN+'/media/'
VIDEO_FILES_URL = 'http://'+SITE_DOMAIN+'/video/'
VIDEO_FILES_ROOT = '/clients/'+SITE_FOLDER+'/video'
__

The  first 4 settings are unique to every setting file.

The last 4 lines (TEMPLATE_DIRS - MEDIA_ROOT) are always based on the
SITE_FOLDER  and SITE_DOMAIN and are the same in all my config files.

How can I separate the last 4 lines repetitive lines (I need to DRY
the code)?

Frank
http://vizualbod.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Define a 2d Array?

2008-10-11 Thread skip

Jill> How do I define a 2d list?

Python doesn't truly have 2d lists in the way you might think of 2d arrays
in C or Fortran.  It has 1d lists which can contain any Python object,
including other lists.  If you wanted to create a 4x5 list you'd do
something like this:

N = 4
M = 5
mylist = []
for i in range(N):
mylist.append([0.0] * M)

If you are looking to do numeric work with such multidimensional lists you
should consider the builtin array object or the numpy package:

http://docs.python.org/dev/library/array.html#module-array
http://numpy.scipy.org/

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


Re: Efficient Bit addressing in Python.

2008-10-11 Thread Ross Ridge
Ross Ridge  wrote:
>I don't think you can do anything faster with standard modules, although
>it might not be efficient if you're only working with a single byte.

Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
>Thanks I was not aware of binascii module this looks powerful.

Not really.  It's just used as part of a trick to quickly convert a byte
string in to a bit string (a byte string with just 0s and 1s).

Unfortunately fromr you other posts you do seem to be working on
a single byte a time, so my technique probably won't be efficient.
You probably want just want to be using constants and bit masking.
Something like:


PAC_EMERGENCY_STOP   = 0x01  # bit #0 on output port 0
PAC_OUTPUT_0_1   = 0x02  # replace with names for other functions
PAC_OUTPUT_0_2   = 0x04
PAC_PNEUMATIC_PUSHER = 0x08  # bit #3 on output port 0
...

def gpio_bit_on(port, bit):
r = gpio_in(port)
r |= bit
r = gpio_out(port)

def gpio_bit_off(port, bit):
r = gpio_in(port)
r &= ~bit
r = gpio_out(port)

class pac(object):
def everything_off(self):
gpio_out(PAC_OUTPUT_PORT_0, 0)
gpio_out(PAC_OUTPUT_PORT_1, 0)
gpio_out(PAC_OUTPUT_PORT_2, 0)
...
gpio_out(PAC_OUTPUT_PORT_7, 0)

def emergency_stop(self):
gpio_bit_on(PAC_OUTPUT_PORT_0, PAC_EMERGENCY_STOP)

def pusher_on(self):
gpio_bit_on(PAC_OUTPUT_PORT_0, PAC_PNEUMATIC_PUSHER)

def pusher_off(self):
gpio_bit_off(PAC_OUTPUT_PORT_0, PAC_PNEUMATIC_PUSHER)


Bit twiddling like this is pretty basic.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  [EMAIL PROTECTED]
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode equality from raw_input

2008-10-11 Thread Chris Rebert
In order to convert a byte sequence to Unicode, Python needs to know
the encoding being used. When you don't specify a encoding, it tries
ASCII, which obviously errors if your byte sequence isn't ASCII, like
in your case.

Figure out what encoding your terminal/system is set to, then use the
.decode() method to change the bytes to a unicode object. E.g.:

bytestring = raw_input("text: ")
as_unicode = bytestring.decode('utf8') #assuming the encoding is UTF-8
print as_unicode == u"おはよう" #==> True

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


2008/10/11 Damian Johnson <[EMAIL PROTECTED]>:
> Hi, when getting text via the raw_input method it's always a string (even if
> it contains non-ASCII characters). The problem lies in that whenever I try
> to check equality against a Unicode string it fails. I've tried using the
> unicode method to 'cast' the string to the Unicode type but this throws an
> exception:
>
 a = raw_input("text: ")
> text: おはよう
 b = u"おはよう"
 a == b
> __main__:1: UnicodeWarning: Unicode equal comparison failed to convert both
> arguments to Unicode - interpreting them as being unequal
> False
 type(a)
> 
 type(b)
> 
 unicode(a)
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0:
> ordinal not in range(128)
 str(b)
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3:
> ordinal not in range(128)
>
>
> After a couple hours of hair pulling I think it's about time to admit
> defeat. Any help would be appreciated! -Damian
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Decrease code redundancy without breaking references

2008-10-11 Thread Chris Rebert
for cfg in settings_modules:
cfg.TEMPLATE_DIRS = ("/clients/"+ cfg.SITE_FOLDER+"/templates",
"/packages/apps/templates")
cfg.MEDIA_FILES_PREFIX = 'http://'+ cfg.SITE_DOMAIN+'/media/'
cfg.VIDEO_FILES_URL = 'http://'+ cfg.SITE_DOMAIN+'/video/'
cfg.VIDEO_FILES_ROOT = '/clients/'+ cfg.SITE_FOLDER+'/video'


Without more information about how your code is structured, it's hard
to give more precise advice.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


On Sat, Oct 11, 2008 at 7:28 PM,  <[EMAIL PROTECTED]> wrote:
> My settings file
> ---
> from global_settings import *
>
> SITE_FOLDER   = 'mypipe'
> SITE_DOMAIN   = 'localhost'
> SITE_NAME = 'My Pipe'
> SITE_ID   = 1
>
> TEMPLATE_DIRS = ("/clients/"+SITE_FOLDER+"/templates", "/packages/apps/
> templates")
> MEDIA_FILES_PREFIX = 'http://'+SITE_DOMAIN+'/media/'
> VIDEO_FILES_URL = 'http://'+SITE_DOMAIN+'/video/'
> VIDEO_FILES_ROOT = '/clients/'+SITE_FOLDER+'/video'
> __
>
> The  first 4 settings are unique to every setting file.
>
> The last 4 lines (TEMPLATE_DIRS - MEDIA_ROOT) are always based on the
> SITE_FOLDER  and SITE_DOMAIN and are the same in all my config files.
>
> How can I separate the last 4 lines repetitive lines (I need to DRY
> the code)?
>
> Frank
> http://vizualbod.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode equality from raw_input

2008-10-11 Thread Karen Tracey
2008/10/11 Damian Johnson <[EMAIL PROTECTED]>

> Hi, when getting text via the raw_input method it's always a string (even
> if it contains non-ASCII characters). The problem lies in that whenever I
> try to check equality against a Unicode string it fails. I've tried using
> the unicode method to 'cast' the string to the Unicode type but this throws
> an exception:
>

Python needs to know the encoding of the bytestring in order to convert it
to unicode.  If you don't specify an encoding, ascii is assumed, which
doesn't work for any bytestrings that actually contain non-ASCII data.
Since you are reading the string from standard input, try using the encoding
associated with stdin:

>>> a = raw_input("text: ")
text: おはよう
>>> b = u"おはよう"
>>> import sys
>>> unicode(a,sys.stdin.encoding) == b
True

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


Re: What do _ast Load | Store | Del | AugLoad | AugStore | Param mean?

2008-10-11 Thread Eloff
On Oct 11, 9:22 pm, Benjamin <[EMAIL PROTECTED]> wrote:
> Load:
> a = 2
> Module(body=[Assign(targets=[Name(id='a', ctx=Store())],
> value=Num(n=2))])
>
> Store:
> print a
> Module(body=[Print(dest=None, values=[Name(id='a', ctx=Load())],
> nl=True)])
>
> Del:
> del a
> Module(body=[Delete(targets=[Name(id='a', ctx=Del())])])
>
> Param:
> def f(a): pass
> Module(body=[FunctionDef(name='f', args=arguments(args=[Name(id='a',
> ctx=Param())], vararg=None, kwarg=None, defaults=[]), body=[Pass()],
> decorator_list=[])])
>
> I hope that helps!
>

Very much! Thank you for such a clear explanation!

Cheers,
-Dan



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


ANN: starpy-1.0.0a13

2008-10-11 Thread Godson Gera
Hi All,

 I am happy to announce new release of starpy (Asterisk protocols
for Twisted http://starpy.sf.net ) on behalf of starpy team.

 starpy-1.0.0a13 can be downloaded from here
https://sourceforge.net/project/showfiles.php?group_id=164040

This release contains addition of many manager commands to manager API.
Following is a list of newly added commands.


   1. agentLogoff
   2. dbGet
   3. dbPut
   4. extensionState
   5. getConfig
   6. meetmeMute
   7. meetmeUnmute
   8. park
   9. pauseMonitor
   10. playDTMF
   11. queuePause
   12. sipShowPeers
   13. unpauseMonitor
   14. updateConfig (read AMI documentation before using this )
   15. userEvent
   16. waitEvent
   17. zapDNDoff
   18. zapDNDon
   19. zapDialOffhook
   20. zapHangup
   21. zapRestart
   22. zapShowChannels
   23. zapTransfer


   - Those are all the new manager Actions that were added. Queues action is
   there but it won't work cause AMI returns improperly formatted lines, same
   case with IAXPeers action, as AgentCallbackLogin is deprecated and is not
   functioning properly it was not included.
   - Bug fix in queueStatus manager API, in collectDeferred argument
   'QueueStatusEnd' is changed to 'QueueStatusComplete'. Now the deferred fires
   properly.
   - Bug fix in fastagi playback (not a standard AGI command, was created by
   Mike as a workaround for buggy streamFile command back in Asterisk 1.2 days.
   Now streamFile is working properly so you might not be using this playback
   ).


Those are all the changes that are involved in this release if you find any
bugs or hope for any new features let me know.

Have fun with starpy,
Godson Gera
--
http://mail.python.org/mailman/listinfo/python-list


Re: unicode .replace not working - why?

2008-10-11 Thread Kurt Peters
I had done that about 21 revisions ago.  Nevertheless, why would you think 
that would work, when the code as shown doesn't?
kurt


"Dennis Lee Bieber" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Sat, 11 Oct 2008 15:05:43 -0500, Kurt Peters
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
>
>> textu.replace(unichr(167),'\n')
>
> Might I suggest:
>
> textu = textu.replace(fn, "\n") #you already created fn as the character
> -- 
> Wulfraed Dennis Lee Bieber KD6MOG
> [EMAIL PROTECTED] [EMAIL PROTECTED]
> HTTP://wlfraed.home.netcom.com/
> (Bestiaria Support Staff: [EMAIL PROTECTED])
> HTTP://www.bestiaria.com/ 


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


Most compact "X if X else Y" idiom

2008-10-11 Thread jbperez808
I find myself having to do the following:

  x = (some complex expression)
  y = x if x else "blah"

and I was wondering if there is any built-in idiom that
can remove the need to put (some complex expression)
in the temporary variable x.

e.g. something like the below:

 y= foobar ((some complex expression), "blah")

I realized foobar() can be easily coded as:
  def foobar(a,b):
if a: return a
else: return b

But I was wondering if there was a built-in function or syntax
that already does this.
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-11 Thread Aaron "Castironpi" Brady
On Oct 10, 12:30 pm, Duncan Booth <[EMAIL PROTECTED]>
wrote:
> [EMAIL PROTECTED] wrote:
> >> I don't think simply re-executing the default argument
> >> expression on each call works either: that would confuse at least as
> >> many people as the current system.
>
> > May I ask you why? I think I don't agree, but I am not sure.
>
(snip)
> I wonder whether it is the way the default argument expressions are
> embedded inside the function that causes the confusion? If for example
> default arguments were defined like this:
>
> class C:
>   @default(d={})
>   def __init__(self, i=10, d):
>     self.d = d
>     self.i = i
>
> would moving the expression before the 'def' make people less inclined to
> be suprised that the object is shared?

You could of course define a wrapper to do call-time assignment:

@calltime( d= dict, e= tuple )
def foo( self, d, e ):

If this decorator appeared in the standard library, newbies would be
able to stumble upon it.

I don't think either semantic is more obvious from the syntax alone.
It could mean either thing just as reasonably, and if Python defined
the opposite, we'd be getting opposite complaints.

On one hand, note that the return statement does not follow the same
convention:

>>> def f(): return [ 0, 1 ]
...
>>> f().append( 2 )
>>> f()
[0, 1]

It constructs a new object each time.  In light of this, the burden of
proof could even fall on Python for the inconsistency.  That is,
assuming that it's well- and always defined.
--
http://mail.python.org/mailman/listinfo/python-list


please solve

2008-10-11 Thread shweta mani
hi folks,
i have been assigned a project on Python. i need to execute a remote
shell script file from a windows machine through SSH twisted or
paramiko. if it is a normal file then directly with the command  sh
.sh it is getting executed.
self.conn.sendRequest(self, 'exec', common.NS(sh test1.sh), wantReply
= 1)
but if a shell scripts asks for user input, this particular way does
not wait for user input. it just print the echo part .
is there any way so that interactive type of scripts can be executed
in Paramiko or Twisted Conch in a windows machine (remote login in a
unix machine through Paramiko SSH or Twisted)
i did try with another way in Paramiko which helps in opening a remote
window by creating an instance of SSHClient and invoking the method
invoke_shell(with some parametes) but remote shell window is not
opening.the method specifies starts a terminal shell window in SSH
server.
To my interpretation it is somewaht opening a terminal window like
putty.
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-11 Thread Aaron "Castironpi" Brady
On Oct 11, 4:41 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Fri, 10 Oct 2008 06:20:35 -0700, bearophileHUGS wrote:
snip
> > I have seen professional programmers too use class attributes instead of
> > instance ones...
>
> That's only a mistake if you don't mean to use class attributes instead
> of instance attributes.

Off topic: That gives me an idea for an interesting technique.

class Foo( HasInstanceVars ):
class InstanceVars:
x= 0
y= None
z= [ 0, 1 ]

The __init__ method in HasInstanceVars adds any InstanceVars members
to the instance members.  It's not terribly different than using
__init__-- slightly slower, slightly clearer.  It could even include a
'__initvars__' variable which adds constructor parameters by name to
the instance.  It's marginally problematic how to create new objects
each time Foo is instantiated.  You could require factories, pickle-
unpickle the contents, require 'deepcopy' compatibility, execute a
string, or call a function which uniquely executes the class
statement.

>>> foo= Foo()
>>> foo.x+= 1
>>> foo2= Foo()
>>> foo2.x
0
>>> foo.x
1

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


Re: Most compact "X if X else Y" idiom

2008-10-11 Thread Terry Reedy

[EMAIL PROTECTED] wrote:

I find myself having to do the following:

  x = (some complex expression)
  y = x if x else "blah"

and I was wondering if there is any built-in idiom that
can remove the need to put (some complex expression)
in the temporary variable x.


A common idiom for this particular case where the if-expression is also 
the conditional or the basic of the conditional expression is


y = 
if not y: y = "blah"

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


Re: Most compact "X if X else Y" idiom

2008-10-11 Thread Aaron "Castironpi" Brady
On Oct 12, 12:01 am, [EMAIL PROTECTED] wrote:
> I find myself having to do the following:
>
>   x = (some complex expression)
>   y = x if x else "blah"
>
> and I was wondering if there is any built-in idiom that
> can remove the need to put (some complex expression)
> in the temporary variable x.
>
> e.g. something like the below:
>
>  y= foobar ((some complex expression), "blah")
>
> I realized foobar() can be easily coded as:
>   def foobar(a,b):
>     if a: return a
>     else: return b
>
> But I was wondering if there was a built-in function or syntax
> that already does this.

You could take your chances on 'or', as follows:

>>> (6+ (3<< 1) ) or 'blah'
12
>>> (6- (3<< 1) ) or 'blah'
'blah'

You don't need to use the ternary statement:

y = (some complex expression)
if not y:
   y = "blah"

If you find yourself using it a lot, why not add it to your site's
utilities modules?  Take your time, and if you find numerous uses,
present them and make the case Python should have a built-in to do it,
something like 'ditto' marks:

(6- (3<< 1) ) if ditto else 'blah'

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


Re: Most compact "X if X else Y" idiom

2008-10-11 Thread Steven D'Aprano
On Sat, 11 Oct 2008 22:01:46 -0700, jbperez808 wrote:

> I find myself having to do the following:
> 
>   x = (some complex expression)
>   y = x if x else "blah"
> 
> and I was wondering if there is any built-in idiom that can remove the
> need to put (some complex expression) in the temporary variable x.

Use short-circuit Booleans:

y = x or "blah"

If x is any true value (non-zero number, non-empty string etc.) then y 
will be set to x; but if x is any false value (zero, empty string, None, 
empty list, etc.) then y will be set to "blah".


However, this technique doesn't work for arbitrary tests. For example, 
you can't simplify the following:

x = (some complex expression)
y = x if 100<=x<250 else "blah"

(at least I can't think of any way).





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


Re: Most compact "X if X else Y" idiom

2008-10-11 Thread Steven D'Aprano
On Sun, 12 Oct 2008 05:30:33 +, Steven D'Aprano wrote:

> Use short-circuit Booleans:
> 
> y = x or "blah"

Except of course you don't use x, you use the complex expression.

y = (some complex expression) or "blah"



Sorry for the itchy posting finger.



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


Re: Most compact "X if X else Y" idiom

2008-10-11 Thread jbperez808
Thanks, folks.

Short-circuit boolean was the syntax I had in mind which
momentarily escaped me, but the "if not x: x='blah'" idiom
was instructive as well.
--
http://mail.python.org/mailman/listinfo/python-list


Canon mp160 drivers

2008-10-11 Thread robin
PROBLEM
i lost my canon mp160 drivers for the printer and scanner. how to i
download from the drivers for the printerI lost my start up disk for
my canon mp180 all in one printer.How can I download another oneNeed
to find the drivers to downloadmy computer has much viruses and i
installed it. after finishedinstalling, i cannot print more because
the software is lost

visit in this 
sitehttp://www.usa.canon.com/consumer/controller?act=DownloadDetailAct&fcategoryid=238&modelid=13368
MP160 driver 1.01 Win98SE/ME/2000/XPhttp://www.driversdown.com/drivers/
Canon-PIXMA-MP160-driver_74508.shtmlMP160 driver 1.10 Windows Vista/
Vista-64http://www.driversdown.com/drivers/Canon-PIXMA-MP160-
driver_74507.shtml

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


Canon PIXMA MP160 All-In-One InkJet Printer

2008-10-11 Thread robin
PROBLEM

I have a very basic question... how to take black and white print? I
am getting colored print even if I press black button on the printer.
Please advice.I'll be thankful if you please let me know the steps to
make sure that how can I make sure that my printer settings at
computer level are correct to take black and print.

find solution here
http://pc-solution4u.blogspot.com/search/label/Canon%20PIXMA%20MP160%20All-In-One%20InkJet%20Printer
--
http://mail.python.org/mailman/listinfo/python-list


E5 and 2,114,0 errors

2008-10-11 Thread robin
PROBLEM

I've just bought a second hand MP160,which I only intended to used as
a scanner.I can't get the scanner to operate due to an E5 error on the
display,and a 2,114,0 error which appears as a pop-up when I attempt
to scan.Although empty,the cartridges are of the correct type and are
seated properly.When I remove the cartridges completely the error
codes do not change.Is an empty cartridge enough to cause this issue?

find solution here
http://pc-solution4u.blogspot.com/search/label/Canon%20PIXMA%20MP160%20All-In-One%20InkJet%20Printer
--
http://mail.python.org/mailman/listinfo/python-list


ink level reset

2008-10-11 Thread robin
PROBLEM

I need to know how to reset the ink level counter of the Canon MP160.
It says " Low ink" when I just refilled the ink tanks. Please help. I
need the tricks or software that resets the counter.

find solution here

http://pc-solution4u.blogspot.com/search/label/Canon%20PIXMA%20MP160%20All-In-One%20InkJet%20Printer
--
http://mail.python.org/mailman/listinfo/python-list