Re: lacking follow-through

2008-09-12 Thread Terry Reedy

Carl Banks wrote:


I'm surprised there is anyone who still gives castironpi credit for
being fully human.


His recent posts have generally been quite different from those of some 
months ago.  Even he recognizes that they were somewhat weird and has 
tried to do better.


Did he ever make any degrading attacks on people like the above, to 
deserve receiving such?  This reminds me of my elementary school, where 
people who made social mistakes were sometimes never allowed to recover 
but were dumped on for years.


tjr

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


Re: ctypes: Get full contents of character array

2008-09-12 Thread Aaron "Castironpi" Brady
On Sep 12, 6:38 pm, [EMAIL PROTECTED] wrote:
> Hello!
>
> I wanted to get the full contents of a character array stored in a
> struct, i.e.
> _fields_ = [...("array", c_char * 12)...]
> however, ctypes seems to try to return struct.array as a Python string
> rather than a character array, and stops as soon as it encounters a
> null within the character array.
>
> I ended up having to define a dummy struct
> class dummystruct(Structure):
>     _fields_ = []
>
> and declare array as:
> ("array", dummystruct)
>
> then use string_at(byref(struct.array), 12).
>
> Is this really the best way of doing it? Is there no better way to
> work around ctypes 'guess what you want' behaviour?
>
> Thanks in advance,
> Rodrigo

Rodrigo,

If you have the option to change your declaration to c_byte* 12, you
have more options.  This example prints the null character you wanted.

from ctypes import *
import struct
class S( Structure ):
_fields_= [
( 'array', c_byte* 12 )
]
s= S()

#initialize
struct.pack_into( '7s', s.array, 0, 'abc\x00def' )

#prototype and call PyString_FromStringAndSize
prototype= PYFUNCTYPE( py_object, POINTER( c_byte ), c_size_t )
PyString_FromStringAndSize= prototype( ( "PyString_FromStringAndSize",
pythonapi ) )
x= PyString_FromStringAndSize( s.array, 12 )
print repr( x )

#prototype and call PyString_FromString for contrast
prototype= PYFUNCTYPE( py_object, POINTER( c_byte ) )
PyString_FromString= prototype( ( "PyString_FromString", pythonapi ) )
x= PyString_FromString( s.array )
print repr( x )

/Output:

'abc\x00def\x00\x00\x00\x00\x00'
'abc'
--
http://mail.python.org/mailman/listinfo/python-list


Re: lacking follow-through

2008-09-12 Thread Carl Banks
On Sep 12, 8:16 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> castironpi wrote:
> > On Sep 7, 5:03 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> >> On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote:
> >>> This is the strangest post I've seen
> >>> since I've joined this list (only
> >>> recently). What the ?
> >> Yeah, castironpi sometimes doesn't make much sense.  Maybe because it's a
> >> bot!?  :-)
>
> >> Ciao,
> >>         Marc 'BlackJack' Rintsch
>
> > No, I'm legit, and I believe my complaint is.  That's all I can
> > guarantee anyway.  While I'm still not a vet on Usenet, I'm still
> > disappointed so far.  Though I should be flattered for my logic to be
> > ever compared to an A.I.'s.
>
> Your various outpourings appear so rambling and ill-conceived that
> silence is often the only polite response.
>
> If you are flattered to be compared to an AI you must come from the same
> race as Mr. Spock in Star Trek.

I'm surprised there is anyone who still gives castironpi credit for
being fully human.


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


Re: lacking follow-through

2008-09-12 Thread Carl Banks
On Sep 12, 12:35 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Steve Holden wrote:
> > The defence rests.
>
> can you please stop quoting that guy, so we don't have to killfile you
> as well...


Guy?


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


Re: n00b question: Better Syntax for Coroutines?

2008-09-12 Thread Carl Banks
On Sep 12, 9:08 pm, [EMAIL PROTECTED] wrote:
> First off, I'm a python n00b, so feel free to comment on anything if
> I'm doing it "the wrong way." I'm building a discrete event simulation
> tool. I wanted to use coroutines. However, I want to know if there's
> any way to hide a yield statement.
>
> I have a class that I'd like to look like this:
>
> class Pinger(Actor):
>     def go(self):
>         success = True
>         while success:
>             result = self.ping("128.111.41.38")
>             if result != "success":
>                 success = False
>         print "Pinger done"
>
> But because I can't hide yield inside ping, and because I can't find a
> convenient way to get a self reference to the coroutine (which is used
> by the event queue to pass back results), my code looks like this:
>
> class Pinger(Actor):
>     def go(self):
>         # I dislike this next line
>         self.this_pointer = (yield None)
>         success = True
>         while success:
>             # I want to get rid of the yield in the next line
>             result = (yield self.ping("128.111.41.38"))
>             if result != "success":
>                 success = False
>         print "Pinger done"
>
> I'd like to know, is there a way to get the syntax I want?

I think you're stuck with using threads in a standard Python release.
Generators can't serve as coroutines when you're yielding from a
nested call (they only go one level deep).

You can get coroutines with Stackless Python, a non-standard version
of Python.  But even with Stackless I got the impression that you'd be
building coroutines atop something that was fairly thread-like.  There
is no coroutine syntax.


Carl Banks


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


Wrong application name in menubar of OS X

2008-09-12 Thread erikcw
Hi,

The menubar of OS X is showing the application name as Python instead
of the name of my wxpython gui app.  How do I make my application name
show-up in the menu bar?

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


Re: universal unicode font for reportlab

2008-09-12 Thread Tim Roberts
Duncan Booth <[EMAIL PROTECTED]> wrote:
>
>The not too scientific test I did was to copy the font embedding example 
>from the Reportlab documentation, modify it enough to make it actually 
>run, and then change the output to have only one glyph. The resulting 
>PDF is virtually identical. I'm not a reportlab expert though so I may 
>have made some blindingly obvious beginners mistake (or maybe it only 
>subsets fonts over a certain size or glyphs outside the ascii range?).
>
>-- rlab.py 
>import os, sys
>import reportlab
>folder = os.path.dirname(reportlab.__file__) + os.sep + 'fonts'
>afmFile = os.path.join(folder, 'LeERC___.AFM')
>pfbFile = os.path.join(folder, 'LeERC___.PFB')
>from reportlab.pdfbase import pdfmetrics
>justFace = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile)
>faceName = 'LettErrorRobot-Chrome' # pulled from AFM file
>pdfmetrics.registerTypeFace(justFace)
>justFont = pdfmetrics.Font('LettErrorRobot-Chrome',faceName,'WinAnsiEncoding')

OK, look the other way while I backpedal furiously.  The conversation on
the mailing last year was focused on TrueType fonts.  Those are subsetted.

EmbeddedType1Face, used for Type 1 fonts, does appear to embed the entire
font.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: n00b question: Better Syntax for Coroutines?

2008-09-12 Thread Aaron "Castironpi" Brady
On Sep 12, 8:08 pm, [EMAIL PROTECTED] wrote:
> First off, I'm a python n00b, so feel free to comment on anything if
> I'm doing it "the wrong way." I'm building a discrete event simulation
> tool. I wanted to use coroutines. However, I want to know if there's
> any way to hide a yield statement.
>
> I have a class that I'd like to look like this:
>
> class Pinger(Actor):
>     def go(self):
>         success = True
>         while success:
>             result = self.ping("128.111.41.38")
>             if result != "success":
>                 success = False
>         print "Pinger done"
>
> But because I can't hide yield inside ping, and because I can't find a
> convenient way to get a self reference to the coroutine (which is used
> by the event queue to pass back results), my code looks like this:
>
> class Pinger(Actor):
>     def go(self):
>         # I dislike this next line
>         self.this_pointer = (yield None)
>         success = True
>         while success:
>             # I want to get rid of the yield in the next line
>             result = (yield self.ping("128.111.41.38"))
>             if result != "success":
>                 success = False
>         print "Pinger done"
>
> I posted a more detailed version of this as a rant 
> here:http://illusorygoals.com/post/49926627/
>
> I'd like to know, is there a way to get the syntax I want? After
> staying up late last night to get a proof-of-concept working with
> coroutines, my boss expressed disappointment in the ugliness of the
> Pinger code (we agreed on the desired syntax above). I spent almost 2
> hours today to migrate the system over to threads. That made my boss
> happy, but I'm still curious if I can do something to salvage the
> coroutine version.
>
> Regards,
> IG

I did not read you whole post though I did skim your link.  I don't
know your whole problem but it seems you are trying to inform a
generator of its own identity.  Here's a solution to that problem;
perhaps it relates to yours.  (The shorter retort is, "Just use
closures.")

def gen( ):
def _gen( ):
while 1:
yield 1, 'i am %r'% ob
yield 2, 'i am %r'% ob
yield 3, 'i am %r'% ob
ob= _gen( )
return ob

gens= [ gen( ) for _ in range( 4 ) ]
for i in range( 6 ):
print i
for g in gens:
print g.next( )

/Output (lengthy):

0
(1, 'i am ')
(1, 'i am ')
(1, 'i am ')
(1, 'i am ')
1
(2, 'i am ')
(2, 'i am ')
(2, 'i am ')
(2, 'i am ')
2
(3, 'i am ')
(3, 'i am ')
(3, 'i am ')
(3, 'i am ')
3
(1, 'i am ')
(1, 'i am ')
(1, 'i am ')
(1, 'i am ')
4
(2, 'i am ')
(2, 'i am ')
(2, 'i am ')
(2, 'i am ')
5
(3, 'i am ')
(3, 'i am ')
(3, 'i am ')
(3, 'i am ')
--
http://mail.python.org/mailman/listinfo/python-list


Insider information, fackbook labs open today, we the first to register!

2008-09-12 Thread [EMAIL PROTECTED]
Insider information, fackbook labs open today, we the first to
register!
www.fackbooklabs.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Good python web programming books

2008-09-12 Thread Sean DiZazzo
On Sep 12, 6:08 pm, "Chris Rebert" <[EMAIL PROTECTED]> wrote:
> I've heard good things about The Django Book:http://www.djangobook.com/
> - Chris
>
>
>
> On Fri, Sep 12, 2008 at 5:57 PM, bhaarat Sharma <[EMAIL PROTECTED]> wrote:
> > Hi Guys,
>
> > I am very new to python.  I am looking for a good book about python web
> > programming.
>
> > I looked at a few online like Web Programming In Python but most are quite
> > old.
>
> > If you've read a good book on python web programming can you please suggest
> > some?
>
> > Thanks
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> --
> Follow the path of the Iguana...http://rebertia.com

Im exploring TurboGears and loving it.  However I don't know how well
you will do learning a web framework at the same time as the
language.  Spend a few weeks (at least) learning the language basics
from the tutorials, then maybe try Django or TurboGears.  You could do
some neat stuff with mod_python as a beginner, so maybe start there.

http://docs.python.org/tut/
http://diveintopython.org/
http://www.modpython.org/
http://www.turbogearsbook.com/

Good luck!

m2c,

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


Re: GUI programming with python

2008-09-12 Thread David Boddie
On Saturday 13 September 2008 01:04, sturlamolden wrote:

> On Sep 12, 8:33 pm, [EMAIL PROTECTED] (Al Dykes) wrote:
> 
>> OK, what are my choices for an IDE/GUI development tool that runs on XP?

[...]

> Cpython with PyQt: BlackAdder

People using this combination apparently prefer Eric, these days:

  http://www.die-offenbachs.de/eric/index.html

More suggestions can be found on this page:

  http://wiki.python.org/moin/IntegratedDevelopmentEnvironments

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


RELEASED Python 2.6rc1

2008-09-12 Thread Barry Warsaw

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On behalf of the Python development team and the Python community, I  
am happy to announce the first release candidate for Python 2.6.


This is a release candidate, so while it is not suitable for  
production environments, we strongly encourage you to download the  
release and test it on your software.  We expect only critical bugs to  
be fixed between now and the final 2.6 release, still scheduled for  
October 1st, 2008.  There is one more release candidate planned for  
September 17th.


You might notice that unlike earlier releases, we are /not/ releasing  
Python 3.0rc1 at this time.  It was decided that 3.0 still needs time  
to resolve open issues and that we would not hold up the 2.6 release  
for this.  We feel that Python 2.6 is nearly ready for its final  
release.


If you find things broken or incorrect, please submit bug reports at

http://bugs.python.org

For more information and downloadable distributions, see the Python  
2.6 website:


   http://www.python.org/download/releases/2.6/

(Note that the Windows installers will be uploaded shortly.)

See PEP 361 for release schedule details:

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

Enjoy,
- -Barry

Barry Warsaw
[EMAIL PROTECTED]
Python 2.6/3.0 Release Manager
(on behalf of the entire python-dev team)

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.9 (Darwin)

iQCVAwUBSMsXV3EjvBPtnXfVAQJFsgP9GxZYQocbDTd0Z/0yEjpHfZ/FTd8y83jV
5JouO07lB8XtLawnWB9hF8sUrCuBVog5He3mLVUPDmlyn30qvjYWMG2J6zW0yYMX
yZdjUyUmta0IMCsXe7YXj369xebh4nWuwG4tDygly4donA7GYPXAlxI48MmyDJxw
1v07LM4Dttw=
=Nd3s
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: Good python web programming books

2008-09-12 Thread bhaarat Sharma
That will be concentrating more on the Django framework

On Fri, Sep 12, 2008 at 6:08 PM, Chris Rebert <[EMAIL PROTECTED]> wrote:

> I've heard good things about The Django Book: http://www.djangobook.com/
> - Chris
>
> On Fri, Sep 12, 2008 at 5:57 PM, bhaarat Sharma <[EMAIL PROTECTED]>
> wrote:
> > Hi Guys,
> >
> > I am very new to python.  I am looking for a good book about python web
> > programming.
> >
> > I looked at a few online like Web Programming In Python but most are
> quite
> > old.
> >
> > If you've read a good book on python web programming can you please
> suggest
> > some?
> >
> > Thanks
> >
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
>
>
> --
> Follow the path of the Iguana...
> http://rebertia.com
>
--
http://mail.python.org/mailman/listinfo/python-list

n00b question: Better Syntax for Coroutines?

2008-09-12 Thread ig
First off, I'm a python n00b, so feel free to comment on anything if
I'm doing it "the wrong way." I'm building a discrete event simulation
tool. I wanted to use coroutines. However, I want to know if there's
any way to hide a yield statement.

I have a class that I'd like to look like this:

class Pinger(Actor):
def go(self):
success = True
while success:
result = self.ping("128.111.41.38")
if result != "success":
success = False
print "Pinger done"

But because I can't hide yield inside ping, and because I can't find a
convenient way to get a self reference to the coroutine (which is used
by the event queue to pass back results), my code looks like this:

class Pinger(Actor):
def go(self):
# I dislike this next line
self.this_pointer = (yield None)
success = True
while success:
# I want to get rid of the yield in the next line
result = (yield self.ping("128.111.41.38"))
if result != "success":
success = False
print "Pinger done"

I posted a more detailed version of this as a rant here:
http://illusorygoals.com/post/49926627/

I'd like to know, is there a way to get the syntax I want? After
staying up late last night to get a proof-of-concept working with
coroutines, my boss expressed disappointment in the ugliness of the
Pinger code (we agreed on the desired syntax above). I spent almost 2
hours today to migrate the system over to threads. That made my boss
happy, but I'm still curious if I can do something to salvage the
coroutine version.

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


Re: Good python web programming books

2008-09-12 Thread Chris Rebert
I've heard good things about The Django Book: http://www.djangobook.com/
- Chris

On Fri, Sep 12, 2008 at 5:57 PM, bhaarat Sharma <[EMAIL PROTECTED]> wrote:
> Hi Guys,
>
> I am very new to python.  I am looking for a good book about python web
> programming.
>
> I looked at a few online like Web Programming In Python but most are quite
> old.
>
> If you've read a good book on python web programming can you please suggest
> some?
>
> Thanks
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Good python web programming books

2008-09-12 Thread bhaarat Sharma
Hi Guys,

I am very new to python.  I am looking for a good book about python web
programming.

I looked at a few online like Web Programming In Python but most are quite
old.

If you've read a good book on python web programming can you please suggest
some?

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

Re: Gateway to python-list is generating bounce messages.

2008-09-12 Thread MRAB
On Sep 12, 11:15 pm, Matt Nordhoff <[EMAIL PROTECTED]> wrote:
> Steven D'Aprano wrote:
> > On Thu, 11 Sep 2008 17:27:33 +0200, Sjoerd Mullender wrote:
>
> >> When mail messages bounce, the MTA (Message Transfer Agent--the program
> >> that handles mail) *should* send the bounce message to whatever is in
> >> the Sender header, and only if that header does not exist, should it use
> >> the From header.
>
> > Who makes up these rules, and why should we pay the least bit of
> > attention to them?
>
> > It's one thing to say "right or wrong, that's what list admins do and you
> > have to deal with their behaviour whatever way you can". It's another
> > thing altogether to take the legalistic attitude of "never mind the
> > consequences, the standard is the standard and must be unthinkingly
> > obeyed". If the standard does more harm than good, then ignoring the
> > standard is the right thing to do. (Better would be to change the
> > standard, but that probably won't happen until there's a critical mass of
> > people who ignore the existing broken standard and form their own de
> > facto standard.)
>
> > A standard isn't "correct" just because it's a standard, it's merely
> > something that a committee has agreed to do. In other words, it's a
> > compromise. Now, such compromises might be good and useful, or they might
> > combine the worst of all opinions. Just because something is standardized
> > doesn't make it the right thing to do. If you want proof of this, I give
> > you the recently approved ISO standard for Microsoft's so-called "Office
> > Open XML" OOXML file format.
>
> > The standard behaviour of sending bounce and out-of-office messages to
> > the sender works well when sending email to individuals, but for mailing
> > lists it is pointless and counter-productive. Pointless, because the
> > sender can't do anything to fix the problem he's being notified about.
> > And counter-productive, because it is an anti-feature, something that
> > makes the mailing list more unpleasant and less useful. Anyone who has
> > regularly emailed to a large mailing list has surely experienced the
> > frustration of receiving bounce messages from perfect strangers.
>
> > To anyone who wishes to defend the process of sending mailing list
> > bounces back the sender, ask yourself this: what do YOU do with such
> > bounces when you receive them? If you ignore them or delete them (whether
> > manually or via a procmail recipe or some other automatic system) then
> > what benefit does the standard behaviour offer?
>
> I think you misunderstand. He's referring to the Sender header, not the>From 
> header. The messages the listbot sends out have a Sender header of
>
> "[EMAIL PROTECTED]" (supposing the
> subscriber's email address is [EMAIL PROTECTED]). Bounces should be
> directed to the bitbucket or list admin or whatever, not the user in 
> the>>From header. kring.com just has a broken mail server.
>
Ah, kring.com. I've been receiving bounces from there as well since
Wednesday. I just added it to my spam blacklist and forgot about it.

I'm just wondering what would happen if someone posted from
there... :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Gateway to python-list is generating bounce messages.

2008-09-12 Thread Matt Nordhoff
Grant Edwards wrote:
> On 2008-09-12, Matt Nordhoff <[EMAIL PROTECTED]> wrote:
> 
>> I think you misunderstand. He's referring to the Sender
>> header, not the From header. The messages the listbot sends
>> out have a Sender header of
>> "[EMAIL PROTECTED]" (supposing
>> the subscriber's email address is [EMAIL PROTECTED]). Bounces
>> should be directed to the bitbucket or list admin or whatever,
>> not the user in the From header. kring.com just has a broken
>> mail server.
> 
> So the statement below by Dennis Lee Bieber in message
> [EMAIL PROTECTED] isn't actually
> correct?
> 
>   >>Three: The bounce/ooo-reply is sent to the message author, not
>   >>to any intermediate host(s). After all, on that end, it's
>   >>normal email failure response -- notify the author of the
>   >>message. It doesn't matter that the original message was posted
>   >>on a Usenet newsgroup if that group is automatically relayed to
>   >>members of a mailing list.

I have no idea. My post was assuming that Sjoerd Mullender was correct.

With headers like "Return-Path", "Errors-To" and "Sender", ISTM the
mailing list software is doing everything it can to avoid bounces
getting sent to the user in the From header. If it's completely wrong,
then, well, it would be silly to have gone to the effort.
-- 
--
http://mail.python.org/mailman/listinfo/python-list


ctypes: Get full contents of character array

2008-09-12 Thread overdrigzed
Hello!

I wanted to get the full contents of a character array stored in a
struct, i.e.
_fields_ = [...("array", c_char * 12)...]
however, ctypes seems to try to return struct.array as a Python string
rather than a character array, and stops as soon as it encounters a
null within the character array.

I ended up having to define a dummy struct
class dummystruct(Structure):
_fields_ = []

and declare array as:
("array", dummystruct)

then use string_at(byref(struct.array), 12).

Is this really the best way of doing it? Is there no better way to
work around ctypes 'guess what you want' behaviour?

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


Re: Gateway to python-list is generating bounce messages.

2008-09-12 Thread Grant Edwards
On 2008-09-12, Matt Nordhoff <[EMAIL PROTECTED]> wrote:

> I think you misunderstand. He's referring to the Sender
> header, not the From header. The messages the listbot sends
> out have a Sender header of
> "[EMAIL PROTECTED]" (supposing
> the subscriber's email address is [EMAIL PROTECTED]). Bounces
> should be directed to the bitbucket or list admin or whatever,
> not the user in the From header. kring.com just has a broken
> mail server.

So the statement below by Dennis Lee Bieber in message
[EMAIL PROTECTED] isn't actually
correct?

  >>Three: The bounce/ooo-reply is sent to the message author, not
  >>to any intermediate host(s). After all, on that end, it's
  >>normal email failure response -- notify the author of the
  >>message. It doesn't matter that the original message was posted
  >>on a Usenet newsgroup if that group is automatically relayed to
  >>members of a mailing list.

-- 
Grant

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


Re: conditional install/distribution

2008-09-12 Thread i3dmaster
On Sep 11, 11:07 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> i3dmasterschrieb:
>
> > Is there a feature in distutils or easy_install to specify what
> > version of python that the target package can be installed? For
> > example, if a package has a module that only needed if the python
> > version < 2.6, is there a way to specifiy that in setup.py or
> > easy_install cfg file so that when installing to python >= 2.6, this
> > module wouldn't be installed??
>
> you can simply import sys and check sys.version in the setup-script, and
> abort with an error-message if the expectations aren't matched.
>
> Diez
I know I can precheck the version, but the real issue is how I can
prevent from installing a specific module? Actually, the rest of the
package should still be installed but just not a particular module
because the feature is built in after 2.6.
--
http://mail.python.org/mailman/listinfo/python-list


Re: GUI programming with python

2008-09-12 Thread sturlamolden
On Sep 12, 8:33 pm, [EMAIL PROTECTED] (Al Dykes) wrote:

> OK, what are my choices for an IDE/GUI development tool that runs on XP?

That depends on the GUI toolkit you are using. My suggestion:

CPython with wxPython: wxFormBuilder

Cpython with PyQt: BlackAdder

CPython with PyGTK: GLADE 3

Jython: whatever there is for Swing or SWT.

IronPython: MS VisualStudio

Cpython + PyWin32: GUI with VB/Delphi/C#. Python ActiveX server (can
use MFC).










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


Re: setattr in class

2008-09-12 Thread Michael Palmer
On Sep 12, 11:08 am, Bojan Mihelac <[EMAIL PROTECTED]> wrote:
> Hi all - when trying to set some dynamic attributes in class, for
> example:
>
> class A:
> for lang in ['1', '2']:
> exec('title_%s = lang' % lang) #this work but is ugly
> # setattr(A, "title_%s" % lang, lang) # this wont work
>
> setattr(A, "title_1", "x") # this work when outside class
>
> print A.title_1
> print A.title_2
>
> I guess A class not yet exists in line 4. Is it possible to achive
> adding dynamic attributes without using exec?
>
> thanks,
> Bojan

Is it really worth it? If the names of the attributes are only known
at runtime, why not just use a dict - that's what they are for. If you
want a dict plus some special behaviour, just write a class that
inherits from dict, or use UserDict.DictMixin.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python a good choice for experimenting with Win32 API?

2008-09-12 Thread sturlamolden


> (1) Would CPython be a good choice for this? How about iron python? How
> about Jython (probably not).

You can use CPython without any problems. Alternatives are pywin32,
ctypes, cython, pyrex, Python C API.

You can use .NET platform invoke from IronPython.

You can use JNI from Jython, or any Win32 API wrapper that may exist
for Java.


> (2) What about callbacks? Which pythons can handle callbacks?

Yes you can use Python functions or bound methods as callbacks.


> (3) How easy it it define the C structs, enums and integer constants
> necessary to call the windows API functions?

It is easy if you can read C header files.


> (4) Here is the code I'm struggling with presently (it is just not
> cooperating: no errors just wrong results!

Here is what it will look like with the pywin32 package:


import win32api
import win32con

def compute(sLangId_, uCode_, uMapType_):
hkl = win32api.LoadKeyboardLayout(sLangId_, win32con.KLF_ACTIVATE
|win32con.KLF_SUBSTITUTE_OK|win32con.KLF_REPLACELANG)
uResult_ = win32api.MapVirtualKeyEx(uCode_, uMapType_, hkl)
return uResult_



With ctypes there is a little more work to do:


import ctypes

MAPVK_VK_TO_VSC = 0
MAPVK_VSC_TO_VK = 1
MAPVK_VK_TO_CHAR = 2
MAPVK_VSC_TO_VK_EX = 3
MAPVK_VK_TO_VSC_EX = 4
KLF_ACTIVATE = 1,
KLF_SUBSTITUTE_OK = 2
KLF_REORDER = 8
KLF_REPLACELANG = 0x10
KLF_NOTELLSHELL = 0x80
KLF_SETFORPROCESS = 0x00100
KLF_SHIFTLOCK = 0x1
KLF_RESET = 0x4000

LoadKeyboardLayout = ctypes.windll.user32.LoadKeyboardLayout
LoadKeyboardLayout.argtypes = (ctypes.c_wchar_p, ctypes.c_uint)
LoadKeyboardLayout.restype = ctypes.c_void_p

UnloadKeyboardLayout = ctypes.windll.user32.UnloadKeyboardLayout
UnloadKeyboardLayout.argtypes = (ctypes.c_void_p,)
UnloadKeyboardLayout.restype = ctypes.c_int

MapVirtualKeyEx = ctypes.windll.user32.UnloadKeyboardLayout
MapVirtualKeyEx.argtypes = (ctypes.c_uint, ctypes.c_uint,
ctypes.c_void_p)
MapVirtualKeyEx.restype = ctypes.c_uint

def compute(sLangId_, uCode_, uMapType_):
hkl = LoadKeyboardLayout(sLangId_, KLF_ACTIVATE|KLF_SUBSTITUTE_OK|
KLF_REPLACELANG)
uResult_ = MapVirtualKeyEx(uCode_, uMapType_, hkl)
return uResult_

This is similar to your code, so it will have the same bugs.




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


Re: Gateway to python-list is generating bounce messages.

2008-09-12 Thread Matt Nordhoff
Steven D'Aprano wrote:
> On Thu, 11 Sep 2008 17:27:33 +0200, Sjoerd Mullender wrote:
> 
>> When mail messages bounce, the MTA (Message Transfer Agent--the program
>> that handles mail) *should* send the bounce message to whatever is in
>> the Sender header, and only if that header does not exist, should it use
>> the From header.
> 
> Who makes up these rules, and why should we pay the least bit of 
> attention to them?
> 
> It's one thing to say "right or wrong, that's what list admins do and you 
> have to deal with their behaviour whatever way you can". It's another 
> thing altogether to take the legalistic attitude of "never mind the 
> consequences, the standard is the standard and must be unthinkingly 
> obeyed". If the standard does more harm than good, then ignoring the 
> standard is the right thing to do. (Better would be to change the 
> standard, but that probably won't happen until there's a critical mass of 
> people who ignore the existing broken standard and form their own de 
> facto standard.)
> 
> A standard isn't "correct" just because it's a standard, it's merely 
> something that a committee has agreed to do. In other words, it's a 
> compromise. Now, such compromises might be good and useful, or they might 
> combine the worst of all opinions. Just because something is standardized 
> doesn't make it the right thing to do. If you want proof of this, I give 
> you the recently approved ISO standard for Microsoft's so-called "Office 
> Open XML" OOXML file format.
> 
> The standard behaviour of sending bounce and out-of-office messages to 
> the sender works well when sending email to individuals, but for mailing 
> lists it is pointless and counter-productive. Pointless, because the 
> sender can't do anything to fix the problem he's being notified about. 
> And counter-productive, because it is an anti-feature, something that 
> makes the mailing list more unpleasant and less useful. Anyone who has 
> regularly emailed to a large mailing list has surely experienced the 
> frustration of receiving bounce messages from perfect strangers.
> 
> To anyone who wishes to defend the process of sending mailing list 
> bounces back the sender, ask yourself this: what do YOU do with such 
> bounces when you receive them? If you ignore them or delete them (whether 
> manually or via a procmail recipe or some other automatic system) then 
> what benefit does the standard behaviour offer?

I think you misunderstand. He's referring to the Sender header, not the
>From header. The messages the listbot sends out have a Sender header of
"[EMAIL PROTECTED]" (supposing the
subscriber's email address is [EMAIL PROTECTED]). Bounces should be
directed to the bitbucket or list admin or whatever, not the user in the
>From header. kring.com just has a broken mail server.
-- 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing __slots__ from C

2008-09-12 Thread Carl Banks
On Sep 12, 10:01 am, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Chris <[EMAIL PROTECTED]> writes:
> >> descr = GetAttrString(cls,"varname");
> >> offset = descr->d_member->offset;
> >> slotvar = (PyObject*)(((char*)obj)+offset)
>
> > Unfortunately, I am inexperienced at this kind of thing, so I wasn't
> > able to get something working. Maybe someone could tell me what's
> > wrong with the code below (it gives the error "'struct _object' has no
> > member named 'd_member'")?
>
> You are getting that error because Carl forgot to cast the descriptor
> to the appropriate C type, in this case PyMemberDescrObject.  The last
> line is also incorrect, I think.

Yep, was in too much of a hurry to waste too much time showing how to
do something slightly dubious.

The offsetof() macro would help for the third line (in fact, it's the
recommended standard way since there are some C implmentions,
somewhere, that the pointer artithmetic method fails).


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


Re: Python and Open Office

2008-09-12 Thread Gary Herron

Greg Lindstrom wrote:

Hello,

I would like to create and manipulate Open Office documents using 
Python.  I have found then UNO Python page and odfpy modules which 
seem to be exactly what I need.  The odfpy manual is, to me, a 
confusing list of objects and methods (it's an impressive list!), but 
does not have much in the way of how to use them.  For example, I can 
open a spreadsheet and create new pages (there's a nice example near 
the back of the manual) but I can't figure out how to open an existing 
spreadsheet and list the names of the individual sheets ("tabs").


I have written an application that access Microsoft Excel and creates 
reports for work, but would like to create an Open Source version 
using Open Office and release it to the community (and maybe get a 
talk at PyCon :-).


Is there someone here who can help me out, or is there an appropriate 
mailing list for me to join? 


Thanks

--greg


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


Here's a snippet of code I use to open a spreadsheet (given as a file 
path name), and compute and return the list of sheets it contains.  It 
connects to an existing OpenOffice if possible, otherwise it starts 
OpenOffice and waits for it to accept a connection.




def OpenSS(path):
   localContext = uno.getComponentContext()
   resolver = localContext.ServiceManager.createInstanceWithContext(
   'com.sun.star.bridge.UnoUrlResolver', localContext )

   
resolveArg='uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext'


   # Conect to running OO;  First, starting OO if necessary;
   try:
   ctx = resolver.resolve(resolveArg)
   except NoConnectException:
   os.system("ooffice '-accept=socket,host=localhost,port=2002;urp;'&")
   while 1:
   print '  waiting for OpenOffice'
   time.sleep(1)
   try:
   ctx = resolver.resolve(resolveArg)
   break
   except NoConnectException:
   pass
   smgr = ctx.ServiceManager
   desktop = smgr.createInstanceWithContext( 
'com.sun.star.frame.Desktop', ctx)


   url = 'file://' + path
   component = desktop.loadComponentFromURL(url, '_default', 0, ())
   sheets = [component.getSheets().getByIndex(i)
 for i in range(component.getSheets().getCount())]
   return sheets


Hope this helps,

Gary Herro


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


Re: Which version

2008-09-12 Thread Don
Eric,Fredrik,

Many thanks for your prompt advice, it was a 'better safe than sorry' type
of question.

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


Re: setattr in class

2008-09-12 Thread Arnaud Delobelle
On Sep 12, 4:30 pm, Bojan Mihelac <[EMAIL PROTECTED]> wrote:
> On Sep 12, 5:21 pm, Christian Heimes <[EMAIL PROTECTED]> wrote:
>
> > Bojan Mihelac wrote:
> > > I guess A class not yet exists in line 4. Is it possible to achive
> > > adding dynamic attributes without using exec?
>
> > Correct, the class doesn't exist until the end of the class body. You
> > can either do it outside the class definition or you can use a metaclass.
>
> > Christian
>
> thanks, can you give example on using a metaclass?

class MoreMeta(type):
def __init__(self, name, bases, attrs):
more = attrs.get('moreattrs')
if more:
for attr, val in more.iteritems():
setattr(self, attr, val)

class MoreObject(object):
__metaclass__ = MoreMeta

class A(MoreObject):
moreattrs = {}
for i in '12':
moreattrs['title_' + i] = int(i)

>>> A.title_1
1
>>> A.title_2
2
>>>

--
Arnaud

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


Re: String to hexadecimal conversion

2008-09-12 Thread imageguy
On Sep 8, 5:05 am, Praveena P <[EMAIL PROTECTED]> wrote:
> Hi folks,
>
> I am new to Python... so am not too sure about how the type conversion
> works.
>
> I have to read a file that contains hexadecimal data and use the data
> further to do some arithmetic calculations.
> A sample of the input is : 20E032F8400022005E
> The problem I am facing is this:
> I am using f.read(2) to read a byte at a time, but the data that is
> read is a string rather than a number. So it kind of hampers any
> arithmetic operations I perform on this data...
>
> Could you please suggest some method I could use for this?
>
> Thanks guys!
> Praveena

check out the "struct" module in the standard python library.
It's title says it all "Interpreting strings as packed binary data".
I used this extensively to reverse engineer a couple proprietary file
structures.

You can read large chucks of the file - perhaps a record ? - and then
based on the format provided, convert it to a tuple.

Good luck.

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


lxml build error in sun

2008-09-12 Thread Owen Zhang
I am trying to build lxml package in SunOS 5.10. I got the following
errors. Does anybody know why?

$ python setup.py build
Building lxml version 2.1.
NOTE: Trying to build without Cython, pre-generated 'src/lxml/
lxml.etree.c' needs to be available.
Using build configuration of libxslt 1.1.7
Building against libxml2/libxslt in the following directory: /usr/lib
running build
running build_py
running build_ext
building 'lxml.etree' extension
gcc -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -
fPIC -I/opt/swt/install/libxml2-2.6.27/include/libxml2 -I/opt/swt/
install/Python-2.5/include/python2.5 -c src/lxml/lxml.etree.c -o build/
temp.solaris-2.10-sun4u-2.5/src/lxml/lxml.etree.o -w
In file included from /usr/include/sys/wait.h:24,
 from /usr/include/stdlib.h:22,
 from /opt/swt/install/Python-2.5/include/python2.5/
Python.h:41,
 from src/lxml/lxml.etree.c:4:
/usr/include/sys/siginfo.h:259: error: syntax error before "ctid_t"
/usr/include/sys/siginfo.h:292: error: syntax error before '}' token
/usr/include/sys/siginfo.h:294: error: syntax error before '}' token
/usr/include/sys/siginfo.h:390: error: syntax error before "ctid_t"
/usr/include/sys/siginfo.h:398: error: conflicting types for '__fault'
/usr/include/sys/siginfo.h:267: error: previous declaration of
'__fault' was here
--
http://mail.python.org/mailman/listinfo/python-list


Re: manipulating files within 'for'

2008-09-12 Thread bearophileHUGS
Matt Nordhoff:
> BTW, I could easily be wrong, but I think C behaves the same way as Python.

C syntax has many traps that are much better out of modern languages
like Python/D/etc.

I think C has that feature because it lacks an operator for string
concatenation, while both Python and D have one (+ and ~. D uses the ~
to avoid any programmer confusion with the mathematical summing
operator), so the situation of Python/D is different.

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


Re: manipulating files within 'for'

2008-09-12 Thread bearophileHUGS
Matt Nordhoff:

> It's useful when wrapping a line. For lack of better lorem ipsum:
>
> whatever = some_function("Your mistake is caused by Python not "
>  "following one of its general rules:\n\n"
>  "Explicit is better than implicit.")
>
> You can also use backslashes, and probably even + if you want to, but
> the implicit concatenation is prettier (IMO, at least ;-).

Adding a + at the end of lines isn't much extra work:

whatever = some_function("Your mistake is caused by Python not " +
 "following one of its general rules:\n\n" +
 "Explicit is better than implicit.")

Or even:

whatever = "Your mistake is caused by Python not " + \
   "following one of its general rules:\n\n" + \
   "Explicit is better than implicit."


> But you do have a point. I have never thought about the problems it
> could cause.

Probably such problems aren't much common, because common bugs are
already prevented by Python designers :-) But I think once I have
written a bug like this:

parts = ["foo", "bar" "baz", "spam"]

Where I meant a list of 4 strings.

> BTW, I could easily be wrong, but I think C behaves the same way as Python.

I know, but here changing the behavior respect to C doesn't cause bugs
to C programmers, because in that situation their Python program just
doesn't run. So it's not a Python syntax that looks like a C syntax
that behaves in a different way (this rule is used by the D designer
too: when something behaves differently from C (often to avoid a
common C pitfall), it has a different syntax. Where the D syntax is
the same of C syntax, then the D behavior is generally the same. This
avoids several problems to programmers coming from C/C++).

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


Re: GUI programming with python

2008-09-12 Thread Mike Driscoll
On Sep 12, 1:33 pm, [EMAIL PROTECTED] (Al Dykes) wrote:
> In article <[EMAIL PROTECTED]>,
> Alan Franzoni  <[EMAIL PROTECTED]> wrote:
>
> >zamil was kind enough to say:
>
> >[cut]
>
> >If your needs are very basic, you can stick with the tk module that comes
> >with python. It's not really feature-packed, but it's maintained and pretty
> >cross-platform.
>
> OK, what are my choices for an IDE/GUI development tool that runs on XP?
>
> Thanks
>
> --
> Al Dykes
>  News is something someone wants to suppress, everything else is advertising.
>     - Lord Northcliffe, publisher of the Daily Mail

Here's a few:

WingWare: http://www.wingware.com/
SPE: http://pythonide.blogspot.com/
Eclipse + Python plugin = EasyEclipse (PyDev):
http://easyeclipse.org/site/distributions/python.html
Or you could use Google and you would have found this:

http://wiki.python.org/moin/IntegratedDevelopmentEnvironments

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


Re: book example confusion

2008-09-12 Thread byron
On Sep 12, 3:51 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On Sep 13, 5:36 am, byron <[EMAIL PROTECTED]> wrote:
>
>
>
> > I am reading o'reilly's learning python (great book), but i came
> > across an example (pg 291, pdf) that I am not quite understanding the
> > reasoning for the author's explanation:
>
> > if f1() or f2():
>
> > The author states that do to the nature of that expression, if f1()
> > returns True, f2() will not be evaluated.. which makes sense. His
> > quote:
>
> >         "Here, if f1 returns a true (or nonempty) value, Python will
> > never run f2."
>
> > He then states:
>
> >         "To guarantee that both functions will be run, call them
> > before the 'or':"
>
> > tmp1, tmp2 = f1(), f2()
> > if tmp1 or tmp2:
>
> > Being that each function is an object, a name assignment to
> > (tmp1,tmp2) doesn't actually evaluate or run the function itself until
> > the name is called.. so why would the latter example "run" both
> > functions as the author suggests?
>
> It's not a "name assignment".
> In effect it's doing this:
>    tmp1 = f1() # get the RESULT of calling f1()
>    tmp2 = f2() # likewise f2
>    if tmp1 or tmp2: # if result1 or result2
> A (pointless) "name assignment") with the nil effect that you fear
> would look like this:
>     tmp1, tmp2 = f1, f2 # Look, no parentheses after function names
>     if tmp1() or tmp2():
>
> HTH,
> John

That makes sense. Thank you for the clarification.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Matching horizontal white space

2008-09-12 Thread John Machin
On Sep 13, 12:52 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > multipleSpaces = re.compile(u'\\h+')
>
> > importantTextString = '\n  \n  \n \t\t  '
> > importantTextString = multipleSpaces.sub("M", importantTextString)
>
> what's "\\h" supposed to mean?

Match *h*orizontal whitespace, I guess ... looks like the maintainer
of the re equivalent in some other language has far too much spare
time :-)



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


Re: GUI programming with python

2008-09-12 Thread Stef Mientki

Al Dykes wrote:

In article <[EMAIL PROTECTED]>,
Alan Franzoni  <[EMAIL PROTECTED]> wrote:
  

zamil was kind enough to say:

[cut]

If your needs are very basic, you can stick with the tk module that comes
with python. It's not really feature-packed, but it's maintained and pretty
cross-platform.




OK, what are my choices for an IDE/GUI development tool that runs on XP? 


Thanks

 

  

From Linux guys, I hear that PyScripter is the best,
they also want to have it, but unfortunately it only runs under windows ;-)

cheers,
Stef
  

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


Re: manipulating files within 'for'

2008-09-12 Thread Matt Nordhoff
[EMAIL PROTECTED] wrote:
> Ben Keshet:
>> ...wrong.  I thought I should omit the comma and didn't put it.  I guess
>> that stating the obvious should be the first attempt with beginners like
>> me.  Thanks for thinking about it (it's running perfect now).
> 
> In CLisp, Scheme etc, lists such commas aren't necessary, but in
> Python if you don't separate strings with a comma they become merged
> into a single string:
> 
 'foo', 'bar'
> ('foo', 'bar')
 'foo' 'bar'
> 'foobar'
> 
> Your mistake is caused by Python not following one of its general
> rules:
> 
> Explicit is better than implicit.
> 
> In such case the string concatenation (+) is done implicitly. It's a
> little handy feature once in a while (but not for me so far), while it
> may cause bugs, so I don't like this little feature of Python and I
> may like to see it removed, because it may bite you in similar
> situations, where you forgot a comma for mistake:
> 
> parts = ["foo", "bar" "baz"]
> 
> Bye,
> bearophile

It's useful when wrapping a line. For lack of better lorem ipsum:

whatever = some_function("Your mistake is caused by Python not "
 "following one of its general rules:\n\n"
 "Explicit is better than implicit.")

You can also use backslashes, and probably even + if you want to, but
the implicit concatenation is prettier (IMO, at least ;-).

But you do have a point. I have never thought about the problems it
could cause.

BTW, I could easily be wrong, but I think C behaves the same way as Python.
-- 
--
http://mail.python.org/mailman/listinfo/python-list


Re: book example confusion

2008-09-12 Thread John Machin
On Sep 13, 5:36 am, byron <[EMAIL PROTECTED]> wrote:
> I am reading o'reilly's learning python (great book), but i came
> across an example (pg 291, pdf) that I am not quite understanding the
> reasoning for the author's explanation:
>
> if f1() or f2():
>
> The author states that do to the nature of that expression, if f1()
> returns True, f2() will not be evaluated.. which makes sense. His
> quote:
>
>         "Here, if f1 returns a true (or nonempty) value, Python will
> never run f2."
>
> He then states:
>
>         "To guarantee that both functions will be run, call them
> before the 'or':"
>
> tmp1, tmp2 = f1(), f2()
> if tmp1 or tmp2:
>
> Being that each function is an object, a name assignment to
> (tmp1,tmp2) doesn't actually evaluate or run the function itself until
> the name is called.. so why would the latter example "run" both
> functions as the author suggests?

It's not a "name assignment".
In effect it's doing this:
   tmp1 = f1() # get the RESULT of calling f1()
   tmp2 = f2() # likewise f2
   if tmp1 or tmp2: # if result1 or result2
A (pointless) "name assignment") with the nil effect that you fear
would look like this:
tmp1, tmp2 = f1, f2 # Look, no parentheses after function names
if tmp1() or tmp2():

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


Re: book example confusion

2008-09-12 Thread Chris Rebert
Note the parentheses after f1 and f2 in the second example. That's  
what calls the functions and causes them to be evaluated and run.


- Chris

Sent from my iPod

On Sep 12, 2008, at 12:36 PM, byron <[EMAIL PROTECTED]> wrote:


I am reading o'reilly's learning python (great book), but i came
across an example (pg 291, pdf) that I am not quite understanding the
reasoning for the author's explanation:

if f1() or f2():

The author states that do to the nature of that expression, if f1()
returns True, f2() will not be evaluated.. which makes sense. His
quote:

   "Here, if f1 returns a true (or nonempty) value, Python will
never run f2."

He then states:

   "To guarantee that both functions will be run, call them
before the 'or':"

tmp1, tmp2 = f1(), f2()
if tmp1 or tmp2:

Being that each function is an object, a name assignment to
(tmp1,tmp2) doesn't actually evaluate or run the function itself until
the name is called.. so why would the latter example "run" both
functions as the author suggests?
--
http://mail.python.org/mailman/listinfo/python-list

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


Re: book example confusion

2008-09-12 Thread Bruno Desthuilliers

byron a écrit :

I am reading o'reilly's learning python (great book), but i came
across an example (pg 291, pdf) that I am not quite understanding the
reasoning for the author's explanation:

if f1() or f2():

The author states that do to the nature of that expression, if f1()
returns True, f2() will not be evaluated.. which makes sense. His
quote:

"Here, if f1 returns a true (or nonempty) value, Python will
never run f2."

He then states:

"To guarantee that both functions will be run, call them
before the 'or':"

tmp1, tmp2 = f1(), f2()
if tmp1 or tmp2:

Being that each function is an object, a name assignment to
(tmp1,tmp2) doesn't actually evaluate or run the function itself until
the name is called..


It (well... they) is (are) actually called. The parens are the call 
operator.


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


book example confusion

2008-09-12 Thread byron
I am reading o'reilly's learning python (great book), but i came
across an example (pg 291, pdf) that I am not quite understanding the
reasoning for the author's explanation:

if f1() or f2():

The author states that do to the nature of that expression, if f1()
returns True, f2() will not be evaluated.. which makes sense. His
quote:

"Here, if f1 returns a true (or nonempty) value, Python will
never run f2."

He then states:

"To guarantee that both functions will be run, call them
before the 'or':"

tmp1, tmp2 = f1(), f2()
if tmp1 or tmp2:

Being that each function is an object, a name assignment to
(tmp1,tmp2) doesn't actually evaluate or run the function itself until
the name is called.. so why would the latter example "run" both
functions as the author suggests?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python on Windows XP 64-bit: python not found in registry

2008-09-12 Thread Martin v. Löwis
> Anybody here that had the same problem and solved it?

Did you install the 32-bit or the 64-bit installer?

If the 64-bit installer, did you also install 32-bit or 64-bit
installers for iPython, PIL, and easy_install?

If you try to use 32-bit extensions or installers to locate a 64-bit
Python, that will fail: even if installation would succeed, you still
couldn't use the resulting installations, since you just can't mix
the two architectures in a single process.

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


Re: manipulating files within 'for'

2008-09-12 Thread bearophileHUGS
Ben Keshet:
> ...wrong.  I thought I should omit the comma and didn't put it.  I guess
> that stating the obvious should be the first attempt with beginners like
> me.  Thanks for thinking about it (it's running perfect now).

In CLisp, Scheme etc, lists such commas aren't necessary, but in
Python if you don't separate strings with a comma they become merged
into a single string:

>>> 'foo', 'bar'
('foo', 'bar')
>>> 'foo' 'bar'
'foobar'

Your mistake is caused by Python not following one of its general
rules:

Explicit is better than implicit.

In such case the string concatenation (+) is done implicitly. It's a
little handy feature once in a while (but not for me so far), while it
may cause bugs, so I don't like this little feature of Python and I
may like to see it removed, because it may bite you in similar
situations, where you forgot a comma for mistake:

parts = ["foo", "bar" "baz"]

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


Need help with the 'transport' for setting the header while calling a function at server side

2008-09-12 Thread Usman Ajmal
I am getting an Internal Server Error  500 when i run my client code. I am
trying to call a function at the server side which for now only returns a
string. Meanwhile this calling i also set the header of HTTP request.
Following are my client and server code. Am i doing something wrong?

#---Server code-

import SimpleXMLRPCServer
class AuthenticationFunctions:
def system_auth(self):
# No need to print here if you are going to print it at the client
side. Return it instead.
return "something..."
server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000))
server.register_instance(AuthenticationFunctions())
server.serve_forever()


#---Client code-
import sha,random, os, time, sha, quopri, xmlrpclib

class SecureTransport(xmlrpclib.Transport):
   def set_authorization(self, ustring, text_ucert):
   self.authorization = quopri.encodestring("%s:%s" %
(ustring,text_ucert))
   def send_request(self, connection, handler, request_body):
   connection.putrequest("POST", handler)
   connection.putheader("Authorization","Basic %s" %
self.authorization)

def caller():
#Opening file named newcert.pem in which certificate generated via
openssl command is placed
infile = open('newcert.pem', "r+")
if infile:
text_ucert = infile.read()
infile.close()

#Generating a random string
random.seed();
ustring_raw="%s_%f_%f"%(os.getpid(),time.time(),random.random())

#For calculating the hash of some arbitrary message
hashValue = sha.new()
hashValue.update("(.2).ch^kjdw*()[EMAIL PROTECTED]
@!jssljdu2837.kd'[EMAIL PROTECTED]&")

#Updating the hash with the previously generated random string
hashValue.update(ustring_raw)
ustring  =  quopri.encodestring(hashValue.digest())

#Instantiating the transport
t = SecureTransport()
   t.set_authorization(ustring, text_ucert)
   server = xmlrpclib.Server('http://localhost:8000',transport=t)

#Calling some arbitrary function at server side
print server.system_auth()

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

Re: Getting Linux partition info programmatically

2008-09-12 Thread Christian Heimes

python dev wrote:

Hello everyone,

I am trying to get a list of all the partitions (along with their respective
file system types) listed in the /media directory.  Does anybody know if
there is a way to do this using Python, or do I have to get this information
by parsing the output of a Linux command?


The /sys and /proc file system provide all the information you need:

for line in open("/proc/mounts"):
...

Christian

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


Re: GUI programming with python

2008-09-12 Thread Al Dykes
In article <[EMAIL PROTECTED]>,
Alan Franzoni  <[EMAIL PROTECTED]> wrote:
>zamil was kind enough to say:
>
>[cut]
>
>If your needs are very basic, you can stick with the tk module that comes
>with python. It's not really feature-packed, but it's maintained and pretty
>cross-platform.


OK, what are my choices for an IDE/GUI development tool that runs on XP? 

Thanks

 

-- 
Al Dykes
 News is something someone wants to suppress, everything else is advertising.
- Lord Northcliffe, publisher of the Daily Mail

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


Getting Linux partition info programmatically

2008-09-12 Thread python dev
Hello everyone,

I am trying to get a list of all the partitions (along with their respective
file system types) listed in the /media directory.  Does anybody know if
there is a way to do this using Python, or do I have to get this information
by parsing the output of a Linux command?

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

Re: manipulating files within 'for'

2008-09-12 Thread Ben Keshet

Emile van Sebille wrote:

Ben Keshet wrote:

Hi Pythoneers,

I have a question about a code I wrote with the help of someone. The 
code below copy a few lines from different files into one file. It 
works fine as it is given here and generates the new file 
'pockets.out' correctly, but says:"py returned exit code 0". 
However, if I add more values to 'receptor' (say, receptor = ['1AZM' 
'1ADS']) 



At risk of stating the obvious, you _did_ put this in properly as

receptors = ['1AZM', '1ADS']

...right?

Emile
...wrong.  I thought I should omit the comma and didn't put it.  I guess 
that stating the obvious should be the first attempt with beginners like 
me.  Thanks for thinking about it (it's running perfect now). 


BK





it gives an

error: "Exception raised while running script".

Can anyone please advice me? Why is it giving an error on multiple x 
but runs well with one (I made sure that all files and folders exist, 
etc.). What does exit code 0 mean?


No error


what does "exception raised" mean?


Error

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



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


Re: manipulating files within 'for'

2008-09-12 Thread Arnaud Delobelle
On Sep 12, 6:11 pm, Ben Keshet <[EMAIL PROTECTED]> wrote:
> Hi Pythoneers,
>
> I have a question about a code I wrote with the help of someone. The
> code below copy a few lines from different files into one file. It works
> fine as it is given here and generates the new file 'pockets.out'
> correctly, but says:"py returned exit code 0". However, if I add
> more values to 'receptor' (say, receptor = ['1AZM' '1ADS']) it gives an
> error: "Exception raised while running script".

You should post the full error if you want some help which is more
than speculation

>
> Can anyone please advice me? Why is it giving an error on multiple x but
> runs well with one (I made sure that all files and folders exist, etc.).
> What does exit code 0 mean? what does "exception raised" mean?

I guess you are on Windows, but how do you run your script?  Do you do
it from the command line or do you use some IDE?

--
Arnaud

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


Re: manipulating files within 'for'

2008-09-12 Thread Emile van Sebille

Ben Keshet wrote:

Hi Pythoneers,

I have a question about a code I wrote with the help of someone. The 
code below copy a few lines from different files into one file. It works 
fine as it is given here and generates the new file 'pockets.out' 
correctly, but says:"py returned exit code 0". However, if I add 
more values to 'receptor' (say, receptor = ['1AZM' '1ADS']) 



At risk of stating the obvious, you _did_ put this in properly as

receptors = ['1AZM', '1ADS']

...right?

Emile



it gives an

error: "Exception raised while running script".

Can anyone please advice me? Why is it giving an error on multiple x but 
runs well with one (I made sure that all files and folders exist, etc.). 
What does exit code 0 mean?


No error


what does "exception raised" mean?


Error

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


Re: Which version

2008-09-12 Thread Fredrik Lundh

Eric Wertman wrote:


The subprocess module is one though


footnote: subprocess works on older versions too, and can be trivially 
installed along with your application under Python 2.2 and 2.3.


binary builds for Windows are available here:

  http://effbot.org/downloads/#subprocess



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


Re: Which version

2008-09-12 Thread Fredrik Lundh

Don wrote:


I'm a reasonably experienced in other languages and have just decided to
get my feet wet with Python. But I'm using FC6 which has v2.4.4 installed,
is this good enough to start out with or am I likely to encounter bugs that
have been fixed in later versions.


Python 2.4 is definitely good enough to start with.

The bugs you'll find in released versions are usually pretty obscure; 
I've been using Python since release 1.1 or so, and I cannot remember 
ever having to upgrade due to a critical bug in the version I was using.




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


Re: Which version

2008-09-12 Thread Eric Wertman
> I'm a reasonably experienced in other languages and have just decided to
> get my feet wet with Python. But I'm using FC6 which has v2.4.4 installed,
> is this good enough to start out with or am I likely to encounter bugs that
> have been fixed in later versions.

I'm sure there will be other opinions.  I try to use the stock distro
version whenever possible, just because it makes administration easier
and you have some reasonable guess as to where your code will work if
you move it.  I use 2.4 regularly, and haven't come across many things
that the 2.5 series would make behave differently.  The subprocess
module is one though, and I recall a few datetime routines that were
2.5 only that I wished I could use.

If you aren't married to you linux distro, you might switch to
ubuntu... I believe they package the 2.5 series.  IMO it's not wrong
to compile a new one alongside the stock installation, but you could
run into potentially confusing issues later about which one exactly
you are using, installing modules for, etc.  Easy to avoid if you know
what you are doing, but a potential pitfall for a beginner.

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


Which version

2008-09-12 Thread Don
Hi,

I'm a reasonably experienced in other languages and have just decided to
get my feet wet with Python. But I'm using FC6 which has v2.4.4 installed,
is this good enough to start out with or am I likely to encounter bugs that
have been fixed in later versions.

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


Re: lacking follow-through

2008-09-12 Thread Aahz
In article <[EMAIL PROTECTED]>,
Fredrik Lundh  <[EMAIL PROTECTED]> wrote:
>Steve Holden wrote:
>>
>> The defence rests.
>
>can you please stop quoting that guy, so we don't have to killfile you 
>as well...

+1
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Argue for your limitations, and sure enough they're yours."  --Richard Bach
--
http://mail.python.org/mailman/listinfo/python-list


manipulating files within 'for'

2008-09-12 Thread Ben Keshet

Hi Pythoneers,

I have a question about a code I wrote with the help of someone. The 
code below copy a few lines from different files into one file. It works 
fine as it is given here and generates the new file 'pockets.out' 
correctly, but says:"py returned exit code 0". However, if I add 
more values to 'receptor' (say, receptor = ['1AZM' '1ADS']) it gives an 
error: "Exception raised while running script".


Can anyone please advice me? Why is it giving an error on multiple x but 
runs well with one (I made sure that all files and folders exist, etc.). 
What does exit code 0 mean? what does "exception raised" mean?


Thanks a lot,
BK

CODE:

|receptors = ['1AZM']
for x in receptors:
   print x
   # open out_file for appending for each 'x' in receptors, close at 
same level
   out_file = 
open('c:/Linux/Dock_method_validation/%s/validation/pockets.out' %(x),'a')

   for i in range(10):
   for r in (7, 9, 11, 13, 15, 17):
   f = open('%s/validation/ligand_ran_line_%s_%s.mol2' 
%(x,i,r), 'r')

   out_file.write('%s ' %i)
   out_file.write('%s ' %r)
   # assume 'PRIMARY' should be found first
   # set flag for string 'PRIMARY'
   primary = False
   # iterate on file object, empty files will be skipped
   for line in f:
   if 'PRIMARY' in line:
   primary = True
   out_file.write(line.strip()) # write line to out_file
   out_file.write(' ')   # add a space
   # write all line after 'PRIMARY' was found until 
'TRIPOS' is found

   elif 'TRIPOS' not in line and primary:
   out_file.write(line.strip()) 
   out_file.write(' ')# add a space

   elif 'TRIPOS' in line and primary:
   break# stop when 
'TRIPOS' is found

   print
   out_file.write('\n')   # move to a new line
   f.close()  # close file. for loop moves to next 'r' 
value, and then to next 'i'

   out_file.close()# close out_file|
--
http://mail.python.org/mailman/listinfo/python-list


Re: dict slice in python (translating perl to python)

2008-09-12 Thread Nick Craig-Wood
Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>  On Thu, 11 Sep 2008 03:36:35 -0500, Nick Craig-Wood wrote:
> 
> > As an ex-perl programmer and having used python for some years now, I'd
> > type the explicit
> > 
> >   v1,v2,v3 = mydict['one'], mydict['two'], mydict['two'] # 54 chars
> > 
> > Or maybe even
> > 
> >   v1 = mydict['one'] # 54 chars
> >   v2 = mydict['two']
> >   v3 = mydict['two']
> > 
> > Either is only a couple more characters to type.
> 
>  But that's an accident of the name you have used. Consider:
> 
>  v1,v2,v3 = section_heading_to_table_index['one'], \
>   section_heading_to_table_index['two'], \
>   section_heading_to_table_index['two']  # 133 characters
> 
>  versus:
> 
>  v1,v2,v3 = [section_heading_to_table_index[k] for k in
>   ['one','two','two']]  # 75 characters
> 
>  It also fails the "Don't Repeat Yourself" principle, and it completely 
>  fails to scale beyond a handful of keys.

If you have more than a handful of keys then you have a different
problem (far too many local variables) with your code I think!

DRY is a good principle.  I still prefer the 3 explicit assignments
though ;-)

>  Out of interest, on my PC at least the list comp version is significantly 
>  slower than the explicit assignments. So it is a micro-optimization that 
>  may be worth considering if needed -- but at the cost of harder to 
>  maintain code.
> 
> > It is completely
> > explicit and comprehensible to everyone, in comparison to
> > 
> >   v1,v2,v3 = [ mydict[k] for k in ['one','two','two']] # 52 chars
> >   v1,v2,v3 = [ mydict[k] for k in 'one two two'.split()] # 54 chars
> 
>  That's a matter for argument. I find the list comprehension perfectly 
>  readable and comprehensible, and in fact I had to read your explicit 
>  assignments twice to be sure I hadn't missed something. But I accept that 
>  if you aren't used to list comps, they might look a little odd.

A matter of taste certainly!

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: lacking follow-through

2008-09-12 Thread Fredrik Lundh

Steve Holden wrote:


The defence rests.


can you please stop quoting that guy, so we don't have to killfile you 
as well...




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


Re: Newbie Question:Please help

2008-09-12 Thread Steve Holden
Karthik Krishnan wrote:
> Hi,
> 
> I am a newbie to python and I hope this is not a stupid question. I am
> trying to run a main method from a Python command line using the command
> shell using the command.
> 
> python main_test.py
> 
> I get the following error.
> 
> 
> File "", line 1
>   python main_test.py
> 
> Syntax Error: invalid syntax
> 
> My main file main_test.py is given below.
> 
> #!/usr/bin/env python
> 
> """ Test method to run the main method.
> 
> """
> 
> def main():
>   print "Main method called.";
> 
> 
> if __name__ = "__main__":
>   main()
> 
Apart from the syntax error Rob pointed out (use of "=" instead of "=="
as a comparison operator) the output you show makes it seem possible you
are entering the command "python main_test.py" at the Python interpreter
interactive prompt ">>>". That won't work, as you are supposed to enter
Python statements and expressions there.

"python" is an operating system command, so you want to enter "python
main_test.py" in a command window (terminal window, shell window, call
it what you will). I'm guessing (possibly incorrectly) that you are a
Windows user, and got your interactive Python window by choosing "Python
(command line)" from the Start | Programs menu.

See the FAQ for further information, possibly

  http://www.python.org/doc/faq/windows/

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

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


Re: lacking follow-through

2008-09-12 Thread Steve Holden
Aaron "Castironpi" Brady wrote:
> On Sep 12, 7:23 am, Steve Holden <[EMAIL PROTECTED]> wrote:
>> castironpi wrote:
>>
>> If you are flattered to be compared to an AI you must come from the same
>> race as Mr. Spock in Star Trek.
> 
> No, I said 'for my logic to compared'.  Speaking of which, I think you
> excluded the possibility of diligent and ethical human, which meets
> the criteria (of being flattered to be compared to an AI)... unless
> Vulcan is just a synonym for it.  If you want a discussion of why a
> diligent and ethical human takes pride in / devotes effort to logic,
> that's another topic that I'm happy to engage on.
> 
>> You aren't entitled to require discussion of your ideas and proposals.
> 
> No, but you are entitled to human interaction.  If your case is that I
> should seek mine face-to-face instead of keyboard-to-screen, you
> probably have a point.
> 
> ...
> 
>> [...]
>>
>>> For example, I sometimes hear people talk about salary as though it
>>> were social approval, and vice versa.  Even though the analogy doesn't
>>> hold in every case generally, it is still a good way to express
>>> yourself in many contexts, and especially when the more precise word
>>> isn't on the tip of your tongue.
>> Perhaps under those circumstances the better choice is to hold off
>> posting and do some research until you come up with the proper word.
> 
> Yes I know.  Good thing everyone at Mozilla agrees with you, and
> Thesaurus.Com is included in Firefox's quicksearch engines.
> 
>> Precision in the expression of ideas encourages debate, whereas sloppy
>> "just write what you feel" is likely to result in hostile responses, as
>> it causes the perception that you value your own time more than that of
>> the people you attempt to engage.
> 
> But the value of expression and self-expression can outweigh the value
> of debate, even in so stuffy a setting as a Usenet group.  Make time
> for both or stifle your emotions.  Do you hold I should be speaking
> from the heart more or less?
> 
> Regardless, you've contradicted yourself:
> 
> 1) "just write what you feel" is likely to result in hostile responses
> 2) If you are flattered to be compared to an AI you must [not be
> human]
> 
> Assume you, Steve, do as you say (practice what you preach).  You do
> not write either "just what you feel", nor anything that can be
> compared to an A.I.  Define the goal of A.I. to be logic and reasoned
> "post-impulsive" deliberation (my title to define as I voiced the
> flattery).  Then conclude you don't post to the newsgroup.  Observe
> you do, and reach an absurdity.  What premise do you retract?
> 
> Knowing nothing of your background in philosophy or otherwise, it may
> be a little unfair to put words in your mouth like that.  It's a deep
> problem (that yes, does have implications on the "diligent and
> ethical" issue above) of human nature and the human condition: If
> you're not rational, then you're a man.
> 
> Besides, it is better to complain to the group that it is dropping my
> posts than to anyone else.
> 
The defence rests.

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

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


Re: Python a good choice for experimenting with Win32 API?

2008-09-12 Thread Mike Driscoll
On Sep 12, 10:36 am, "Siegfried Heintze" <[EMAIL PROTECTED]>
wrote:
> I need to understand some User32.dll functions and I'm making an elaborate
> GUI so I can easily experiment with different parameters. This is taking a
> long time. I'm new to python and I'm thinking it would sure be nice to have
> an interpreter I can type a few lines of code into and test things.
>
> (1) Would CPython be a good choice for this? How about iron python? How
> about Jython (probably not).
> (2) What about callbacks? Which pythons can handle callbacks? I read on msdn
> that you cannot use managed code to call SetWindowsHook and supply a call
> back (with two exceptions). I guess that means I cannot use iron python.
> What about C-Python for playing with hooks?
> (3) How easy it it define the C structs, enums and integer constants
> necessary to call the windows API functions?
> (4) Here is the code I'm struggling with presently (it is just not
> cooperating: no errors just wrong results! I expect to be able give it a
> scan code, get a virtual key code, change the arguments, give it the virtual
> key code and get the original scan code back again).
>
>         public const UInt32 MAPVK_VK_TO_VSC = 0, MAPVK_VSC_TO_VK = 1,
> MAPVK_VK_TO_CHAR = 2, MAPVK_VSC_TO_VK_EX = 3, MAPVK_VK_TO_VSC_EX = 4;
>         public const UInt32 KLF_ACTIVATE = 1, KLF_SUBSTITUTE_OK = 2,
> KLF_REORDER = 8, KLF_REPLACELANG = 0x10, KLF_NOTELLSHELL = 0x80,
> KLF_SETFORPROCESS = 0x00100, KLF_SHIFTLOCK = 0x1, KLF_RESET =
> 0x4000;
>         [DllImport("user32.dll")]  static extern IntPtr
> LoadKeyboardLayout(string pwszKLID, uint Flags);
>         [DllImport("user32.dll")] static extern bool
> UnloadKeyboardLayout(IntPtr hkl);
>         [DllImport("user32.dll")]   static extern uint MapVirtualKeyEx(uint
> uCode, uint uMapType, IntPtr dwhkl);
>         private void Compute()
>         {
>             IntPtr hkl = LoadKeyboardLayout(sLangId_, KLF_ACTIVATE |
> KLF_SUBSTITUTE_OK | KLF_REPLACELANG);
>             uResult_ = MapVirtualKeyEx(uCode_, uMapType_, hkl);
>             UpdateOutput();
>         }
> Would it be easy to execute this in the CPython interpreter or am I better
> off sticking with C#?
>
> Thanks!
> Siegfried

I use the Python interpreter all the time for heavy experimentation.
While I use PyWin32, I haven't done what you are attempting. I would
recommend re-posting to the PyWin32 group as the PyWin32 creators use
that list much more:

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

And there's lots of other knowledgeable users there too. Good luck!

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


Re: Checking the boolean value of a collection

2008-09-12 Thread bearophileHUGS
Marco Bizzarri:
> >>> any([x for x in [1, 2, 3]])
>
> I mean, I'm afraid I can't use an expression like that without
> building a list... not at least in python2.3

Note that you don't need a list comp there:

>>> any([x for x in [1, 2, 3]])
True
>>> any([1, 2, 3])
True

so this may suffice:

any(self.findActiveOutgoingRegistrationInstancesPlusSomeOtherThings())

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


Re: Checking the boolean value of a collection

2008-09-12 Thread Bruno Desthuilliers

Marco Bizzarri a écrit :
(snip)

I'm afraid this have another problem for me...


[EMAIL PROTECTED]:/var/local/zope28/porting/Products/PAFlow$ python2.3
Python 2.3.5 (#2, Oct 18 2006, 23:04:45)
[GCC 4.1.2 20061015 (prerelease) (Debian 4.1.1-16.1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

def any(iterable): pass

...

any(x for x in [1, 2, 3])

  File "", line 1
any(x for x in [1, 2, 3])
^
SyntaxError: invalid syntax


any([x for x in [1, 2, 3]])



I mean, I'm afraid I can't use an expression like that without
building a list... not at least in python2.3


Err... a list being an iterable, you just need any([1, 2, 3]).

But this wont be enough to solve your real use case, indeed.

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


Re: Checking the boolean value of a collection

2008-09-12 Thread Fredrik Lundh

D'Arcy J.M. Cain wrote:


Is there ever any advantage to having something as a builtin rather
than as a regular user method?  What difference does it make to the
running script?  I can see that adding "bar" from module "foo" to
"__builtins__" means that you can use "bar()" instead of "foo.bar()".
Is that the only benefit?


basically, yes.  in this case, it does make some sense to patch any/all 
into __builtin__, since they are builtins in a later version.




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


Re: setattr in class

2008-09-12 Thread Bojan Mihelac
On Sep 12, 5:35 pm, Wojtek Walczak <[EMAIL PROTECTED]> wrote:
> On Fri, 12 Sep 2008 08:08:18 -0700 (PDT), Bojan Mihelac wrote:
> > Hi all - when trying to set some dynamic attributes in class, for
> > example:
>
> > class A:
> >     for lang in ['1', '2']:
> >         exec('title_%s = lang' % lang) #this work but is ugly
> >         # setattr(A, "title_%s" % lang, lang) # this wont work
> > I guess A class not yet exists in line 4. Is it possible to achive
> > adding dynamic attributes without using exec?
>
> Yes, it is:
>
> -
> class A:
>    for i in (1, 2):
>       locals()['xxx%d' % (i)] = i
>
> print A.xxx1
> print A.xxx2
> a = A()
> print a.xxx1
> print a.xxx2
> -
>
> And the output is:
>
> -
> 1
> 2
> 1
> 2
> -
>
> But I definitely don't consider this one as a good programming
> practice.
>
> --
> Regards,
> Wojtek Walczak,http://tosh.pl/gminick/

thnx Wojtek, this works!
--
http://mail.python.org/mailman/listinfo/python-list


Python a good choice for experimenting with Win32 API?

2008-09-12 Thread Siegfried Heintze
I need to understand some User32.dll functions and I'm making an elaborate 
GUI so I can easily experiment with different parameters. This is taking a 
long time. I'm new to python and I'm thinking it would sure be nice to have 
an interpreter I can type a few lines of code into and test things.

(1) Would CPython be a good choice for this? How about iron python? How 
about Jython (probably not).
(2) What about callbacks? Which pythons can handle callbacks? I read on msdn 
that you cannot use managed code to call SetWindowsHook and supply a call 
back (with two exceptions). I guess that means I cannot use iron python. 
What about C-Python for playing with hooks?
(3) How easy it it define the C structs, enums and integer constants 
necessary to call the windows API functions?
(4) Here is the code I'm struggling with presently (it is just not 
cooperating: no errors just wrong results! I expect to be able give it a 
scan code, get a virtual key code, change the arguments, give it the virtual 
key code and get the original scan code back again).

public const UInt32 MAPVK_VK_TO_VSC = 0, MAPVK_VSC_TO_VK = 1, 
MAPVK_VK_TO_CHAR = 2, MAPVK_VSC_TO_VK_EX = 3, MAPVK_VK_TO_VSC_EX = 4;
public const UInt32 KLF_ACTIVATE = 1, KLF_SUBSTITUTE_OK = 2, 
KLF_REORDER = 8, KLF_REPLACELANG = 0x10, KLF_NOTELLSHELL = 0x80, 
KLF_SETFORPROCESS = 0x00100, KLF_SHIFTLOCK = 0x1, KLF_RESET = 
0x4000;
[DllImport("user32.dll")]  static extern IntPtr 
LoadKeyboardLayout(string pwszKLID, uint Flags);
[DllImport("user32.dll")] static extern bool 
UnloadKeyboardLayout(IntPtr hkl);
[DllImport("user32.dll")]   static extern uint MapVirtualKeyEx(uint 
uCode, uint uMapType, IntPtr dwhkl);
private void Compute()
{
IntPtr hkl = LoadKeyboardLayout(sLangId_, KLF_ACTIVATE | 
KLF_SUBSTITUTE_OK | KLF_REPLACELANG);
uResult_ = MapVirtualKeyEx(uCode_, uMapType_, hkl);
UpdateOutput();
}
Would it be easy to execute this in the CPython interpreter or am I better 
off sticking with C#?

Thanks!
Siegfried 


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


Re: setattr in class

2008-09-12 Thread Wojtek Walczak
On Fri, 12 Sep 2008 08:08:18 -0700 (PDT), Bojan Mihelac wrote:
> Hi all - when trying to set some dynamic attributes in class, for
> example:
>
> class A:
> for lang in ['1', '2']:
> exec('title_%s = lang' % lang) #this work but is ugly
> # setattr(A, "title_%s" % lang, lang) # this wont work

> I guess A class not yet exists in line 4. Is it possible to achive
> adding dynamic attributes without using exec?

Yes, it is:

-
class A:
   for i in (1, 2):
  locals()['xxx%d' % (i)] = i

print A.xxx1
print A.xxx2
a = A()
print a.xxx1
print a.xxx2
-

And the output is:

-
1
2
1
2
-

But I definitely don't consider this one as a good programming
practice.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: setattr in class

2008-09-12 Thread Bojan Mihelac
On Sep 12, 5:21 pm, Christian Heimes <[EMAIL PROTECTED]> wrote:
> Bojan Mihelac wrote:
> > I guess A class not yet exists in line 4. Is it possible to achive
> > adding dynamic attributes without using exec?
>
> Correct, the class doesn't exist until the end of the class body. You
> can either do it outside the class definition or you can use a metaclass.
>
> Christian

thanks, can you give example on using a metaclass?
--
http://mail.python.org/mailman/listinfo/python-list


Re: setattr in class

2008-09-12 Thread Christian Heimes

Bojan Mihelac wrote:

I guess A class not yet exists in line 4. Is it possible to achive
adding dynamic attributes without using exec?


Correct, the class doesn't exist until the end of the class body. You 
can either do it outside the class definition or you can use a metaclass.


Christian

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


Re: Checking the boolean value of a collection

2008-09-12 Thread D'Arcy J.M. Cain
On Fri, 12 Sep 2008 17:11:47 +0200
Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> The "__builtins__" object is an implementation detail, and shouldn't be 
> accessed directly.  And I hope I don't need to point out that adding 
> custom builtins nillywilly is a bad idea...

Is there ever any advantage to having something as a builtin rather
than as a regular user method?  What difference does it make to the
running script?  I can see that adding "bar" from module "foo" to
"__builtins__" means that you can use "bar()" instead of "foo.bar()".
Is that the only benefit?

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


Re: setattr in class

2008-09-12 Thread Fredrik Lundh

Bojan Mihelac wrote:


Hi all - when trying to set some dynamic attributes in class, for
example:

class A:
for lang in ['1', '2']:
exec('title_%s = lang' % lang) #this work but is ugly
# setattr(A, "title_%s" % lang, lang) # this wont work

setattr(A, "title_1", "x") # this work when outside class

print A.title_1
print A.title_2

I guess A class not yet exists in line 4. Is it possible to achive
adding dynamic attributes without using exec?


Move the for-in loop out of the class definition:

>>> class A:
... pass
...
>>> for lang in ['1', '2']:
... setattr(A, "title_%s" % lang, lang)
>>> a = A()
>>> a.title_1
'1'

A truly dynamic solution (using __getattr__ and modification on access) 
would probably give you a more "pythonic" solution.




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


Re: Checking the boolean value of a collection

2008-09-12 Thread Fredrik Lundh

Marco Bizzarri wrote:


I would like to make  this available to the whole project. I suspect I
could put it in the package __init__.py... in that way, the
__builtins__ namespace should have it... am I right?


the __init__ module for package "foo" defines the contents of the "foo" 
module; it doesn't add anything to the builtin namespace.


Diez made a typo in his post, btw.  To add your own builtins, you should 
add them to the "__builtin__" module (no plural s):


 import __builtin__

 try:
 any
 except NameError:
 def any(iterable):
 for element in iterable:
 if element:
 return True
 return False
 __builtin__.any = any

 try:
 all
 except NameError:
 def all(iterable):
 for element in iterable:
 if not element:
 return False
 return True
 __builtin__.all = all

The "__builtins__" object is an implementation detail, and shouldn't be 
accessed directly.  And I hope I don't need to point out that adding 
custom builtins nillywilly is a bad idea...




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


setattr in class

2008-09-12 Thread Bojan Mihelac
Hi all - when trying to set some dynamic attributes in class, for
example:

class A:
for lang in ['1', '2']:
exec('title_%s = lang' % lang) #this work but is ugly
# setattr(A, "title_%s" % lang, lang) # this wont work

setattr(A, "title_1", "x") # this work when outside class

print A.title_1
print A.title_2

I guess A class not yet exists in line 4. Is it possible to achive
adding dynamic attributes without using exec?

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


Re: Checking the boolean value of a collection

2008-09-12 Thread Marco Bizzarri
On Fri, Sep 12, 2008 at 4:44 PM, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
>>> if any(instance.forbitToClose(archivefolder) for instance in
>>> self.findActiveOutgoingRegistrationInstances())
>>
>> Can you clarify where I can find "any"? It seems to me I'm unable to find
>> it...
>
> It's part of python2.5.
>
> If you don't have that, you can write it your own and stuff it into
> __builtins__:
>
 def any(iterable):
> ... for item in iterable:
> ... if item:
> ...  return True
> ... return False
> ...
> ... __builtins__.any = any
>
>
> You might also want to add all, the companion of any:
>
>
 def all(iterable):
> ... for item in iterable:
> ... if not item:
> ...  return False
> ... return True
> ...
>
> Diez
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I'm afraid this have another problem for me...


[EMAIL PROTECTED]:/var/local/zope28/porting/Products/PAFlow$ python2.3
Python 2.3.5 (#2, Oct 18 2006, 23:04:45)
[GCC 4.1.2 20061015 (prerelease) (Debian 4.1.1-16.1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def any(iterable): pass
...
>>> any(x for x in [1, 2, 3])
  File "", line 1
any(x for x in [1, 2, 3])
^
SyntaxError: invalid syntax
>>>

>>> any([x for x in [1, 2, 3]])
>>>

I mean, I'm afraid I can't use an expression like that without
building a list... not at least in python2.3

Regards
Marco

-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Checking the boolean value of a collection

2008-09-12 Thread Marco Bizzarri
On Fri, Sep 12, 2008 at 4:44 PM, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
>>> if any(instance.forbitToClose(archivefolder) for instance in
>>> self.findActiveOutgoingRegistrationInstances())
>>
>> Can you clarify where I can find "any"? It seems to me I'm unable to find
>> it...
>
> It's part of python2.5.
>
> If you don't have that, you can write it your own and stuff it into
> __builtins__:
>
 def any(iterable):
> ... for item in iterable:
> ... if item:
> ...  return True
> ... return False
> ...
> ... __builtins__.any = any
>
>
> You might also want to add all, the companion of any:
>
>
 def all(iterable):
> ... for item in iterable:
> ... if not item:
> ...  return False
> ... return True
> ...
>
> Diez
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Thanks for the clarification, Diez! Indeed, I tried python2.3 and
python2.4, and of course not python2.5 ;)

I would like to make  this available to the whole project. I suspect I
could put it in the package __init__.py... in that way, the
__builtins__ namespace should have it... am I right?

-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Matching horizontal white space

2008-09-12 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


multipleSpaces = re.compile(u'\\h+')

importantTextString = '\n  \n  \n \t\t  '
importantTextString = multipleSpaces.sub("M", importantTextString)


what's "\\h" supposed to mean?


I would have expected consecutive spaces and tabs to be replaced by M
but nothing is being replaced.


if you know what you want to replace, be explicit:

>>> importantTextString = '\n  \n  \n \t\t  '
>>> re.compile("[\t ]+").sub("M", importantTextString)
'\nM\nM\nM'



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


Re: Checking the boolean value of a collection

2008-09-12 Thread Fredrik Lundh

Marco Bizzarri wrote:


Can you clarify where I can find "any"? It seems to me I'm

> unable to find it...

it's a 2.5 addition.  to use this in a "future-compatible" way in 2.3, 
you can add


 try:
 any
 except NameError:
 def any(iterable):
 for element in iterable:
 if element:
 return True
 return False

to the top of the file (or to some suitable support library).

2.5 also provides an "all" function, which can be emulated as:

 try:
 all
 except NameError:
 def all(iterable):
 for element in iterable:
 if not element:
 return False
 return True



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


Re: Checking the boolean value of a collection

2008-09-12 Thread Diez B. Roggisch

if any(instance.forbitToClose(archivefolder) for instance in
self.findActiveOutgoingRegistrationInstances())


Can you clarify where I can find "any"? It seems to me I'm unable to find it...


It's part of python2.5.

If you don't have that, you can write it your own and stuff it into 
__builtins__:


>>> def any(iterable):
... for item in iterable:
... if item:
...  return True
... return False
...
... __builtins__.any = any


You might also want to add all, the companion of any:


>>> def all(iterable):
... for item in iterable:
... if not item:
...  return False
... return True
...

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


Re: Accessing __slots__ from C

2008-09-12 Thread Hrvoje Niksic
Hrvoje Niksic <[EMAIL PROTECTED]> writes:

> Chris <[EMAIL PROTECTED]> writes:
>
>>> descr = GetAttrString(cls,"varname");
>>> offset = descr->d_member->offset;
>>> slotvar = (PyObject*)(((char*)obj)+offset)
>>
>> Unfortunately, I am inexperienced at this kind of thing, so I wasn't
>> able to get something working. Maybe someone could tell me what's
>> wrong with the code below (it gives the error "'struct _object' has no
>> member named 'd_member'")?
>
> You are getting that error because Carl forgot to cast the descriptor
> to the appropriate C type, in this case PyMemberDescrObject.  The last
> line is also incorrect, I think.  Try something like this:
>
>   PyObject *descr = PyObject_GetAttrString(x,"attr_one");

Also note that x should be your object's type, i.e. o->ob_type cast to
PyObject *.  The complete incantation would be:

// outside the loop
PyObject *descr = PyObject_GetAttrString((PyObject *) obj->ob_type,
 "attr_one");
if (!descr)
  return NULL;
int offset = ((PyMemberDescrObject *) descr)->d_member->offset;
Py_DECREF(descr);

// inside the loop
PyObject *value = *(PyObject **)((char *)obj + offset);
if (!value) {
  PyErr_SetString(PyExc_AttributeError, "attribute missing");
  return NULL;
}
// Remember to Py_INCREF(value) before using it and Py_DECREF it after
// using it.  Otherwise if the object changes its slot to something
// else, you might be using a dead object.

With this code, accessing the value is practically free once the
offset is calculated.  Here is a bench3 function updated to use this
strategy:

static PyObject *
bench3(PyObject *ignored, PyObject *obj)
{
  PyObject *descr = PyObject_GetAttrString((PyObject *) obj->ob_type,
   "abcdef");
  if (!descr)
return NULL;

  // Here you should also assert that PyObject_TypeCheck(descr,
  // PyMemberDescr_Type) holds true.  Since PyMemberDescr_Type is static,
  // you'll have to get it by stashing away ob_type of a value known to be
  // the descriptor.  This is left as excercise to the reader.

  int offset = ((PyMemberDescrObject *) descr)->d_member->offset;
  Py_DECREF(descr);

  int i;
  PyObject *volatile attr;   // 'volatile' for benchmarking, prevents gcc
 // from optimizing away the loop
  for (i = 0; i < 100; i++) {
attr = *(PyObject **)((char *)obj + offset);
  }
  Py_INCREF(attr);
  return attr;// to prove that we retrieved the correct value
}

>>> t0 = time.time(); attr.bench3(o); t1 = time.time()
1
>>> t1-t0
0.00071597099304199219   # for 1,000,000 iterations, as cheap as it gets
--
http://mail.python.org/mailman/listinfo/python-list


Re: Checking the boolean value of a collection

2008-09-12 Thread Marco Bizzarri
On Fri, Sep 12, 2008 at 4:09 PM, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> Marco Bizzarri schrieb:
>>
>> Hi all.
>>
>> In many parts of my code I've the following schema of code:
>>
>>def isInUseByOutgoingRegistrations(self, archivefolder):
>>for instance in self.findActiveOutgoingRegistrationInstances():
>>if instance.forbidToClose(archivefolder):
>>return True
>>return False
>>
>> Before devising my own solution for this kind of problem, I wonder if
>> there is a common solution for the problem. I'm looking for a
>> python2.3 solution.
>
> if any(instance.forbitToClose(archivefolder) for instance in
> self.findActiveOutgoingRegistrationInstances())

Can you clarify where I can find "any"? It seems to me I'm unable to find it...


> You should also consider using PEP8 style naming.
>

I knew that someone would have said that to me :-).

I'm doing that... slowly. I'm trying to fix naming conventions as I
had to work on my code...

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



-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Checking the boolean value of a collection

2008-09-12 Thread Diez B. Roggisch

Marco Bizzarri schrieb:

Hi all.

In many parts of my code I've the following schema of code:

def isInUseByOutgoingRegistrations(self, archivefolder):
for instance in self.findActiveOutgoingRegistrationInstances():
if instance.forbidToClose(archivefolder):
return True
return False

Before devising my own solution for this kind of problem, I wonder if
there is a common solution for the problem. I'm looking for a
python2.3 solution.


if any(instance.forbitToClose(archivefolder) for instance in 
self.findActiveOutgoingRegistrationInstances())


You should also consider using PEP8 style naming.


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


Re: Accessing __slots__ from C

2008-09-12 Thread Hrvoje Niksic
Chris <[EMAIL PROTECTED]> writes:

>> descr = GetAttrString(cls,"varname");
>> offset = descr->d_member->offset;
>> slotvar = (PyObject*)(((char*)obj)+offset)
>
> Unfortunately, I am inexperienced at this kind of thing, so I wasn't
> able to get something working. Maybe someone could tell me what's
> wrong with the code below (it gives the error "'struct _object' has no
> member named 'd_member'")?

You are getting that error because Carl forgot to cast the descriptor
to the appropriate C type, in this case PyMemberDescrObject.  The last
line is also incorrect, I think.  Try something like this:

  PyObject *descr = PyObject_GetAttrString(x,"attr_one");
  int offset = ((PyMemberDescrObject *) descr)->d_member->offset;
  PyObject *slotvar = *(PyObject **)(((char *) obj) + offset);
--
http://mail.python.org/mailman/listinfo/python-list


Re: lacking follow-through

2008-09-12 Thread Aaron "Castironpi" Brady
On Sep 12, 7:23 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> castironpi wrote:
>
> If you are flattered to be compared to an AI you must come from the same
> race as Mr. Spock in Star Trek.

No, I said 'for my logic to compared'.  Speaking of which, I think you
excluded the possibility of diligent and ethical human, which meets
the criteria (of being flattered to be compared to an AI)... unless
Vulcan is just a synonym for it.  If you want a discussion of why a
diligent and ethical human takes pride in / devotes effort to logic,
that's another topic that I'm happy to engage on.

> You aren't entitled to require discussion of your ideas and proposals.

No, but you are entitled to human interaction.  If your case is that I
should seek mine face-to-face instead of keyboard-to-screen, you
probably have a point.

...

> [...]
>
> > For example, I sometimes hear people talk about salary as though it
> > were social approval, and vice versa.  Even though the analogy doesn't
> > hold in every case generally, it is still a good way to express
> > yourself in many contexts, and especially when the more precise word
> > isn't on the tip of your tongue.
>
> Perhaps under those circumstances the better choice is to hold off
> posting and do some research until you come up with the proper word.

Yes I know.  Good thing everyone at Mozilla agrees with you, and
Thesaurus.Com is included in Firefox's quicksearch engines.

> Precision in the expression of ideas encourages debate, whereas sloppy
> "just write what you feel" is likely to result in hostile responses, as
> it causes the perception that you value your own time more than that of
> the people you attempt to engage.

But the value of expression and self-expression can outweigh the value
of debate, even in so stuffy a setting as a Usenet group.  Make time
for both or stifle your emotions.  Do you hold I should be speaking
from the heart more or less?

Regardless, you've contradicted yourself:

1) "just write what you feel" is likely to result in hostile responses
2) If you are flattered to be compared to an AI you must [not be
human]

Assume you, Steve, do as you say (practice what you preach).  You do
not write either "just what you feel", nor anything that can be
compared to an A.I.  Define the goal of A.I. to be logic and reasoned
"post-impulsive" deliberation (my title to define as I voiced the
flattery).  Then conclude you don't post to the newsgroup.  Observe
you do, and reach an absurdity.  What premise do you retract?

Knowing nothing of your background in philosophy or otherwise, it may
be a little unfair to put words in your mouth like that.  It's a deep
problem (that yes, does have implications on the "diligent and
ethical" issue above) of human nature and the human condition: If
you're not rational, then you're a man.

Besides, it is better to complain to the group that it is dropping my
posts than to anyone else.

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

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


Re: Accessing __slots__ from C

2008-09-12 Thread Hrvoje Niksic
Chris <[EMAIL PROTECTED]> writes:

>> In my experience, as long as you're
>> accessing simple slots, you should notice a difference.
>
> (I'm not sure what you mean by a 'simple slot'.

I mean a slot defined by __slots__ = slot1, slot2, slot3, ..., without
descriptors or specific __getattribute__ code on top of that.

> - GetAttr: 46 seconds (46 seconds)
> outside the loop:
> PyObject *name = PyString_FromString("attr_one"); 

I think you should be using PyString_InternFromString, but it will
probably still be slower than PyList_GET_ITEM, which is still much
simpler.  The next optimization is the one proposed by Carl, which
should yield speed comparable to PyList_GET_ITEM.  See my response in
that subthread for details.
--
http://mail.python.org/mailman/listinfo/python-list


Checking the boolean value of a collection

2008-09-12 Thread Marco Bizzarri
Hi all.

In many parts of my code I've the following schema of code:

def isInUseByOutgoingRegistrations(self, archivefolder):
for instance in self.findActiveOutgoingRegistrationInstances():
if instance.forbidToClose(archivefolder):
return True
return False

Before devising my own solution for this kind of problem, I wonder if
there is a common solution for the problem. I'm looking for a
python2.3 solution.

Regards
Marco

-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Injecting new names into the above frame

2008-09-12 Thread Carsten Haese
Peter Waller wrote:
> Dear Pythoners,
> 
> I know this will probably be perceived as 'evil voodoo', and fair
> enough: it probably is. I guess it is unpythonic.
> 
> .. but I want to know how to do it anyway - mostly for my own
> interest.

Well, if you're really just asking out of curiosity, it should be
sufficient to tell you that this is not possible.

> [...] we have to add this
> snippet before the Get() function returns:
> 
> from ctypes import pythonapi, py_object, c_int
> pythonapi.PyFrame_LocalsToFast( py_object( frame ), 1 )
> 
> This copies back the names into the code object, and works fine.. that
> is, if the names already exist within the code object.
> 
> def MyFunction():
> a = None
> Get("a")
> print a # Works
> Get("b")
> print b # Name error, b is undefined

The answer to why this doesn't work lies in the disassembly of that
function:
  0 LOAD_CONST  0 (0)
  3 STORE_FAST  0 (0)
  6 LOAD_GLOBAL 1 (1)
  9 LOAD_CONST  1 (1)
 12 CALL_FUNCTION   1
 15 POP_TOP
 16 LOAD_FAST   0 (0) <- This is a
 19 PRINT_ITEM
 20 PRINT_NEWLINE
 21 LOAD_GLOBAL 1 (1)
 24 LOAD_CONST  2 (2)
 27 CALL_FUNCTION   1
 30 POP_TOP
 31 LOAD_GLOBAL 2 (2) <- This is b
 34 PRINT_ITEM
 35 PRINT_NEWLINE
 36 LOAD_CONST  0 (0)
 39 RETURN_VALUE

Since you have an assignment to the name a, a is recognized as a local
name at compile time. b is not recognized as a local name at compile
time, so even if you inject a value for b into the locals dictionary,
the byte code still looks up the value as a global name.

> Is there any way for Get() to define a new variable within
> MyFunction's code object? Or is there any programmatic way to, at
> runtime, insert new names into functions?

Not without making fundamental changes to Python itself. The fact that
this isn't possible is a feature, in my opinion. I like the fact that I
can call a function and be *absolutely certain* that it's not going to
pollute my local namespace.

Hope this helps,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing __slots__ from C

2008-09-12 Thread Chris
Hrvoje Niksic  xemacs.org> writes:
...
> Chris  users.sourceforge.net> writes:
> 
> >> PyObject_GetAttrString is convenient, but it creates a Python string
> >> only so it can intern it (and in most cases throw away the freshly
> >> created version).  For maximum efficiency, pre-create the string
> >> object using PyString_InternFromString, and use that with
> >> PyObject_GetAttr.
> >
> > Yes, we'd thought of that too, but it doesn't seem to be an
> > important factor compared to the actual attribute lookup.
> 
> I'd like to see your test code.  

Thanks for your interest in this. My test code is a whole function
that's part of a big simulator, unfortunately! I need to use the data
structures created by the simulator as part of the testing.  While the
source is freely available*, that doesn't make it easy for others to
run the tests...


> In my experience, as long as you're
> accessing simple slots, you should notice a difference.

(I'm not sure what you mean by a 'simple slot'. The slot we're
accessing is a numpy array.)

Sorry I wasn't clear before - we do notice a difference, but not as
big a difference as when we access the attributes (arrays) from a
pre-built list. Below are timings from running the simulator
(i.e. calling the function in question many times) using the three
approaches (GetAttrString, GetAttr, and instead using a list and
GetItem; times outside parentheses are from a stopwatch; times in
parentheses are from Python's cProfile module):


- GetAttrString: 55 seconds (58 seconds)
inside the loop:
PyObject *weights_obj = PyObject_GetAttrString(obj,"attr_one");


- GetAttr: 46 seconds (46 seconds)
outside the loop:
PyObject *name = PyString_FromString("attr_one"); 

inside the loop: 
PyObject *obj = PyObject_GetAttr(obj,name);


- PyList_GetItem: 35 seconds (37 seconds)


So, of course, you are right to say that we should notice a
difference!  But speed is critical for us here. 

Incidentally, what we have is a simulator written entirely in Python,
but we also provide optimized C versions of some parts of it.  These C
parts must be entirely optional.


> Here is a test program that shows a 4.6 time speedup simply by
> switching from PyObject_GetAttrString to PyObject_GetAttr:

Thanks for the illustration. While I didn't run your code myself,
I did try to study it. Illustrations like that are very helpful.


Chris


* from http://topographica.org/



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


Injecting new names into the above frame

2008-09-12 Thread Peter Waller
Dear Pythoners,

I know this will probably be perceived as 'evil voodoo', and fair
enough: it probably is. I guess it is unpythonic.

.. but I want to know how to do it anyway - mostly for my own
interest.

Consider the following snippet of code:

---
def Get( *names ):
if not names: return None

frame = sys._getframe(1)
prevFrameLocals = frame.f_locals

for name in names:
prevFrameLocals[ name ] = FetchObjectNamed( name )

Get("a", "b", "c")

print a, b, c
---

FetchObjectNamed() is an arbitrary function which takes a string and
returns an object it got from some store somewhere.

This works fine at the module level, because names in the locals/
globals dictionary can be played with in this way. The idea is to save
lots of typing, i.e.

a, b, c = Get("a","b","c")

..gets frustrating after much typing for many objects with long names.
This is just an example, there are other instances I have where it
would be nice to inject names into the frame above.

Of course, we hit a road block when we call 'Get' from a function
rather than a module, because the locals dictionary does not get
copied back into the code object automatically, so we have to add this
snippet before the Get() function returns:

from ctypes import pythonapi, py_object, c_int
pythonapi.PyFrame_LocalsToFast( py_object( frame ), 1 )

This copies back the names into the code object, and works fine.. that
is, if the names already exist within the code object.

def MyFunction():
a = None
Get("a")
print a # Works
Get("b")
print b # Name error, b is undefined

Is there any way for Get() to define a new variable within
MyFunction's code object? Or is there any programmatic way to, at
runtime, insert new names into functions?

I don't care how hacky it is and whether it requires making calls to
python's internals with ctypes - maybe the whole code object needs to
be replaced? is it even possible to do that when the Get() function is
about to return to this new code object?

Cheers,

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


Re: dynamic allocation file buffer

2008-09-12 Thread Aaron "Castironpi" Brady
On Sep 12, 4:34 am, Paul Boddie <[EMAIL PROTECTED]> wrote:
> On 12 Sep, 08:30, Steven D'Aprano
>
> <[EMAIL PROTECTED]> wrote:
>
> > Which is why I previously said that XML was not well suited for random
> > access.
>
> Maybe not.

No, it's not.  Element trees are, which if I just would have said
originally...

> A consideration of other storage formats such as HDF5 might
> be appropriate:
>
> http://hdf.ncsa.uiuc.edu/HDF5/whatishdf5.html
>
> There are, of course, HDF5 tools available for Python.

PyTables came up within the past few weeks on the list.

"When the file is created, the metadata in the object tree is updated
in memory while the actual data is saved to disk. When you close the
file the object tree is no longer available. However, when you reopen
this file the object tree will be reconstructed in memory from the
metadata on disk"

This is different from what I had in mind, but the extremity depends
on how slow the 'reconstructed in memory' step is.  (From
http://www.pytables.org/docs/manual/ch01.html#id2506782 ).  The
counterexample would be needing random access into multiple data
files, which don't all fit in memory at once, but the maturity of the
package might outweigh that.  Reconstruction will form a bottleneck
anyway.

> > I think we're starting to be sucked into a vortex of obtuse and opaque
> > communication.
>
> I don't know about that. I'm managing to keep up with the discussion.
>
> > We agree that XML can store hierarchical data, and that it
> > has to be read and written sequentially, and that whatever the merits of
> > castironpi's software, his original use-case of random access to a 4GB
> > XML file isn't workable. Yes?

I could renege that bid and talk about a 4MB file, where recopying is
prohibitively expensive and so random access is needed, thereby
requiring an alternative to XML.

> Again, XML specifically might not be workable for random access in a
> serialised form, despite people's best efforts at processing it in
> various unconventional ways, but that doesn't mean that random access
> to a 4GB file containing hierarchical data isn't possible, so I
> suppose it depends on whether he is wedded to the idea of using
> vanilla XML or not.

No.  It is always nice to be able to scroll through your data, but
it's much less common to be able to scroll though a data -structure-.
(Which is part of the reason data structures are hard to design.)

> It's always worth exploring the available
> alternatives before embarking on a challenging project, unless one
> wants to pursue the exercise as a learning experience, and I therefore
> suggest investigating whether HDF5 doesn't already solve at least some
> of the problems or use-cases stated in this discussion.

The potential for concurrency is definitely one benefit of raw alloc/
free management, and a requirement I was setting out to program
directly for.  There is a multi-threaded version of HDF5 but
interprocess communication is unsupported.

"This version serializes the API suitable for use in a multi-threaded
application but does not provide any level of concurrency."

From: http://www.hdfgroup.uiuc.edu/papers/features/mthdf/

(It is always appreciated to find a statement of what a product does
not do.)

> Paul

There is an updated statement of the problem on the project website:

http://code.google.com/p/pymmapstruct/source/browse/trunk/pymmapstruct.txt

I don't have numbers for my claim that the abstraction layers in SQL,
including string construction and parsing, are ever a bottleneck or
limiting factor, despite that it's sort of intuitive.  Until I get
those, maybe I should leave that allegation out.

Compared to the complexity of all these other packages (ZOPE,
memcached, HDF5/PyTables), alloc and free are almost looking like they
should become methods on a subclass of the builtin buffer type.  Ha!
(Ducks.)  They're beyond dangerous compared to the snuggly feeling of
Python though, so maybe they could belong in ctypes.

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


Re: Please help me finding a way to implement os.path.issubpath(a, b)

2008-09-12 Thread Giampaolo Rodola'
On Sep 11, 8:04 pm, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> On Sep 11, 5:40 pm, "Giampaolo Rodola'" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi,
> > I'm trying to implement a function which returns whether a path is a
> > subpath of another one (e.g. /a/b/c is a subpath of /a/b).
> > I wrote this function which apparently seems to work fine:
>
> > import os
>
> > def issubpath(path1, path2):
> >     """Return True if path1 is a sub path of path2."""
> >     if path1 == path2:
> >         return False
> >     x1 = path1.split(os.sep)
> >     x2 = path2.split(os.sep)
> >     return x1[:len(x2)] == x2
>
> > ...but if I use "issubpath('C:\\dir', 'C:\\')" it returns False.
> > A little help would be appreciated.
>
> > Thanks in advance.
>
> That's because:
>
> >>> 'C:\\dir'.split('\\')
> ['C:', 'dir']
> >>> 'C:\\'.split('\\')
>
> ['C:', '']
>
> So you could write instead something like
>
>     x1 = path1.rstrip(os.sep).split(os.sep)
>     x2 = path2.rstrip(os.sep).split(os.sep)
>
> in your function
>
> HTH
>
> --
> Arnaud

Thanks, it seems to work just fine.


--- Giampaolo
http://code.google.com/p/pyftpdlib/
--
http://mail.python.org/mailman/listinfo/python-list


Re: testing if another instance of a script is already running

2008-09-12 Thread Tim Golden

Tim Golden wrote:

Strato wrote:

Hi folks,

I want to write some kind of test to check at startup if another 
instance of my script is already running.


I don't want to handle writing of a PID file because it is too 
Unix/Linux specific way to do this, and I need to keep the code to be 
cross-platform.


I think the better way to achieve this is to use some process control, 
but I'm a neebie and I don't see how to do this in a safe and clean way.


There's nothing built in to Python to do this, so you'll
probably have to roll your own cross-platformness. Of
course, there's nothing to stop you from writing pid
files under Windows even if it's not the usual way.
Or you could just put some conditional code, and use
the kernel mutex under Windows, which is the generally
recommended technique. Have a look at this thread,
for example (among several others):

http://mail.python.org/pipermail/python-list/2005-June/327063.html


Sorry, not the best of links to point to. Basically, search
mail.python.org for things like "CreateMutex" and 
"single application instance".


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


Re: String to hexadecimal conversion

2008-09-12 Thread Steve Holden
Praveena P wrote:
> Hi folks,
> 
> I am new to Python... so am not too sure about how the type conversion
> works.
> 
> I have to read a file that contains hexadecimal data and use the data
> further to do some arithmetic calculations.
> A sample of the input is : 20E032F8400022005E
> The problem I am facing is this:
> I am using f.read(2) to read a byte at a time, but the data that is
> read is a string rather than a number. So it kind of hampers any
> arithmetic operations I perform on this data...
> 
> Could you please suggest some method I could use for this?

Generally speaking, reading a file 2 bytes at a time i going to be
inefficient and untidy.

Does this help?

>>> int("20E032F8400022005E", 16)
170696759285949896156423472451551326L
>>>

Or have I misunderstood your intention?

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

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


Re: testing if another instance of a script is already running

2008-09-12 Thread Tim Golden

Strato wrote:

Hi folks,

I want to write some kind of test to check at startup if another 
instance of my script is already running.


I don't want to handle writing of a PID file because it is too 
Unix/Linux specific way to do this, and I need to keep the code to be 
cross-platform.


I think the better way to achieve this is to use some process control, 
but I'm a neebie and I don't see how to do this in a safe and clean way.


There's nothing built in to Python to do this, so you'll
probably have to roll your own cross-platformness. Of
course, there's nothing to stop you from writing pid
files under Windows even if it's not the usual way.
Or you could just put some conditional code, and use
the kernel mutex under Windows, which is the generally
recommended technique. Have a look at this thread,
for example (among several others):

http://mail.python.org/pipermail/python-list/2005-June/327063.html


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


Re: Gateway to python-list is generating bounce messages.

2008-09-12 Thread Steven D'Aprano
On Thu, 11 Sep 2008 17:27:33 +0200, Sjoerd Mullender wrote:

> When mail messages bounce, the MTA (Message Transfer Agent--the program
> that handles mail) *should* send the bounce message to whatever is in
> the Sender header, and only if that header does not exist, should it use
> the From header.

Who makes up these rules, and why should we pay the least bit of 
attention to them?

It's one thing to say "right or wrong, that's what list admins do and you 
have to deal with their behaviour whatever way you can". It's another 
thing altogether to take the legalistic attitude of "never mind the 
consequences, the standard is the standard and must be unthinkingly 
obeyed". If the standard does more harm than good, then ignoring the 
standard is the right thing to do. (Better would be to change the 
standard, but that probably won't happen until there's a critical mass of 
people who ignore the existing broken standard and form their own de 
facto standard.)

A standard isn't "correct" just because it's a standard, it's merely 
something that a committee has agreed to do. In other words, it's a 
compromise. Now, such compromises might be good and useful, or they might 
combine the worst of all opinions. Just because something is standardized 
doesn't make it the right thing to do. If you want proof of this, I give 
you the recently approved ISO standard for Microsoft's so-called "Office 
Open XML" OOXML file format.

The standard behaviour of sending bounce and out-of-office messages to 
the sender works well when sending email to individuals, but for mailing 
lists it is pointless and counter-productive. Pointless, because the 
sender can't do anything to fix the problem he's being notified about. 
And counter-productive, because it is an anti-feature, something that 
makes the mailing list more unpleasant and less useful. Anyone who has 
regularly emailed to a large mailing list has surely experienced the 
frustration of receiving bounce messages from perfect strangers.

To anyone who wishes to defend the process of sending mailing list 
bounces back the sender, ask yourself this: what do YOU do with such 
bounces when you receive them? If you ignore them or delete them (whether 
manually or via a procmail recipe or some other automatic system) then 
what benefit does the standard behaviour offer?



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


Re: Accessing __slots__ from C

2008-09-12 Thread Chris
Carl Banks  gmail.com> writes:
...
> You can determine the offset the of the slot in the object structure
> by
> querying the member descriptor of the type object.

That sounds like just the kind of thing we were looking for - thanks!

> descr = GetAttrString(cls,"varname");
> offset = descr->d_member->offset;
> slotvar = (PyObject*)(((char*)obj)+offset)

Unfortunately, I am inexperienced at this kind of thing, so I wasn't
able to get something working. Maybe someone could tell me what's
wrong with the code below (it gives the error "'struct _object' has no
member named 'd_member'")?

  PyObject *descr = PyObject_GetAttrString(x,"attr_one");
  int offset = descr->d_member->offset;
  PyObject* slotvar = (PyObject*)(((char*)obj)+offset);

where x is the class and attr_one is a slot (the full example is
appended to this message).  I guessed the type of offset; I'm not sure
what it should be.

I couldn't find any information about d_member on the web.


> There might be some macros to simplify this.

Sorry to say that I also have no idea about where to find such macros!
Maybe I should continue this thread on capi-sig?


Thanks for your help,
Chris


class MyObject(object):

  __slots__ = ['attr_one']

  def __init__(self,attr_one=1.0):
  self.attr_one = attr_one

import weave
def test():

  x = MyObject

  code = """
  PyObject *descr = PyObject_GetAttrString(x,"attr_one");
  int offset = descr->d_member->offset;
  //PyObject* slotvar = (PyObject*)(((char*)obj)+offset);
  """
  weave.inline(code,['x'],local_dict=locals(),verbose=1)

test()


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


Re: lacking follow-through

2008-09-12 Thread Steve Holden
castironpi wrote:
[...]
> For example, I sometimes hear people talk about salary as though it
> were social approval, and vice versa.  Even though the analogy doesn't
> hold in every case generally, it is still a good way to express
> yourself in many contexts, and especially when the more precise word
> isn't on the tip of your tongue.

Perhaps under those circumstances the better choice is to hold off
posting and do some research until you come up with the proper word.

Precision in the expression of ideas encourages debate, whereas sloppy
"just write what you feel" is likely to result in hostile responses, as
it causes the perception that you value your own time more than that of
the people you attempt to engage.

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

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


Re: lacking follow-through

2008-09-12 Thread Steve Holden
castironpi wrote:
> On Sep 7, 5:03 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote:
>>> This is the strangest post I've seen
>>> since I've joined this list (only
>>> recently). What the ?
>> Yeah, castironpi sometimes doesn't make much sense.  Maybe because it's a
>> bot!?  :-)
>>
>> Ciao,
>> Marc 'BlackJack' Rintsch
> 
> No, I'm legit, and I believe my complaint is.  That's all I can
> guarantee anyway.  While I'm still not a vet on Usenet, I'm still
> disappointed so far.  Though I should be flattered for my logic to be
> ever compared to an A.I.'s.
> 
Your various outpourings appear so rambling and ill-conceived that
silence is often the only polite response.

If you are flattered to be compared to an AI you must come from the same
race as Mr. Spock in Star Trek.

> Maybe the ideas are not that groundbreaking, but they still have been
> dropped instead of critiqued.  Problem.

You aren't entitled to require discussion of your ideas and proposals.
The usual way of obtaining responses is to engage in a dialog,
responding intelligently and directly to any criticism or discussion.
But it's often difficult to discern what point you are trying to make.

This may be a linguistic issue, or it may be because you are running
some bizarre experiment. The jury appears to still be out on that question.

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

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


testing if another instance of a script is already running

2008-09-12 Thread Strato

Hi folks,

I want to write some kind of test to check at startup if another 
instance of my script is already running.


I don't want to handle writing of a PID file because it is too 
Unix/Linux specific way to do this, and I need to keep the code to be 
cross-platform.


I think the better way to achieve this is to use some process control, 
but I'm a neebie and I don't see how to do this in a safe and clean way.


Any idea ?

Best regards,
Strato
--
http://mail.python.org/mailman/listinfo/python-list


Matching horizontal white space

2008-09-12 Thread Magnus . Moraberg
multipleSpaces = re.compile(u'\\h+')

importantTextString = '\n  \n  \n \t\t  '
importantTextString = multipleSpaces.sub("M", importantTextString)

I would have expected consecutive spaces and tabs to be replaced by M
but nothing is being replaced. If I try the following, then I'm left
only with M, as expected -

multipleSpaces = re.compile(u'\\s+') # both vertical and horizontal

importantTextString = '\n  \n  \n \t\t  '
importantTextString = multipleSpaces.sub("M", importantTextString)


What I eventually wish to do is have only single spaces in my text and
to only have single carriage returns -

"one   two three  four

five


six

"

becoming -

"one two three four
five
six
"

Thanks,

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


  1   2   >