Re: Data Model:

2009-04-13 Thread Anthony
On Apr 12, 9:36 pm, Aaron Brady  wrote:
> On Apr 12, 10:33 pm, Anthony  wrote:
>
>
>
> > On Apr 12, 8:10 pm, Aaron Brady  wrote:
>
> > > On Apr 12, 9:14 pm, Anthony  wrote:
>
> > > > I'm struggling on whether or not to implement GroupItem (below) with
> > > > two separate models, or with one model that has a distinguishing key:
>
> > > > Given:
> > > > class ParentGroup:
> > > >     a group of values represented by class GroupItem
>
> > > > class ChildGroup:
> > > >     a group of values represented by class GroupItem
> > > >     foreign-key to ParentGroup (many Children sum to one Parent)
>
> > > > Option A:
> > > > class GroupItem:
> > > >     foreign-key to ParentGroup
> > > >     foreign-key to ChildGroup
> > > >     GroupItemType in (ParentItem, ChildItem)
> > > >     value
> > > >     value-type
>
> > > > Option B:
> > > > class ParentGroupItem
> > > >     foreign-key to ParentGroup
> > > >     value
> > > >     value-type
>
> > > > class ChildGroupItem
> > > >     foreign-key to ChildGroup
> > > >     value
> > > >     value-type
>
> > > > What are my considerations when making this decision?
>
> > > > Thanks!
>
> > > You want a ChildItem to have membership in two collections:
> > > ParentGroup and ChildGroup.  You also want a ParentItem to have
> > > membership in one collection.  For example:
>
> > > parentA: itemPA1, itemPA2, childA, childB
> > > childA: itemCA1, itemCA2
> > > childB: itemCB1, itemCB2
>
> > > Or, listing by child,
>
> > > itemPA1: parentA
> > > itemPA2: parentA
> > > itemCA1: childA
> > > itemCA2: childA
> > > itemCB1: childB
> > > itemCB2: childB
> > > childA: parentA
> > > childB: parentA
>
> > > Correct so far?
>
> > Thanks for the insightful response.
>
> > Yes, everything you say is correct, with one clarification:  The
> > ChildItem can be a member of ParentGroup OR ChildGroup, but never both
> > at the same time.
>
> I see.  You described a collection class.  Its members are items or
> other collections.  They are never nested more than two levels deep.
>
> However, in your example, you implied a collection class whose
> attributes are aggregates of its members'.  For simplicity, you can
> use methods to compute the aggregate attributes.
>
> class Group:
>   def calculate_total_produced( self ):
>     total= sum( x.total_produced for x in self.members )
>
> If you want to cache them for performance, the children will have to
> notify the parent when one of their attributes changes, which is at
> least a little more complicated.  The class in the simpler structure
> could even derive from 'set' or other built-in collection if you
> want.  Are you interested in the more complicated faster technique?

Yes, in my example, the top level collection class is implicitly the
aggregate of the lower level class.  However, data entry will take
place at the top level, not necessarily at the lower level.  This
means that the lower level values will never drive the top level
value.  Instead, the aggregate of the lower levels will be validated
against the top level.  If there is a discrepancy, then the remainder
will be applied to an additional "Unregistered" instance of the lower
level.

e.g.

Group: Johnson - Total Units Produced 25;  Units Consumed 18;
  Chris Johnson - Units Produced 18; Units Consumed 10;
  Jim Johnson   - Units Produced 3;  Units Consumed 5;

The group totals are the basis for any validations.  In this example,
another entry will be created to account for the discrepancy:

  Unregistered -  Units Produced 4;  Units Consumed 3

As far as child notification of the parent, I plan to only allow data
entry on a form that includes both parent and child level values.
Validation of top level to child level aggregates can happen at this
time.  This should remove the need for notification, right?

Am I looking at 6 of one and half dozen of the other between options A
and B at this point?  I'm currently leaning towards option B.  Is
there anything I will be losing performance-wise by not choosing
option A?

Thanks again for conversing with me on this.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: PyGUI 2.0.1

2009-04-13 Thread roee shlomo
I can't run any of the tests on windows (pywin32-213, XP SP3, Python 2.6.1).

1. Had to change the first line in Applications.py to :

> import win32con as wc, win32ui as ui, win32clipboard as wcb, win32api as
> api

Otherwise it gives me a DLL Import error. I have no idea why.
2. Import fails in Components.py because

> from Win32 import win_none

tries to import win_none from the Win32 package, not the module, so I got

> ImportError: This should not be imported.


Thanks,
Roee.

On Mon, Apr 13, 2009 at 4:26 AM, Greg Ewing wrote:

> PyGUI 2.0.1 is available:
>
>  http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/
>
> Fixes some problems in setup.py affecting installation
> on Linux and Windows.
>
>
> What is PyGUI?
> --
>
> PyGUI is a cross-platform GUI toolkit designed to be lightweight
> and have a highly Pythonic API.
>
> --
> Gregory Ewing
> greg.ew...@canterbury.ac.nz
> http://www.cosc.canterbury.ac.nz/greg.ewing/
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


how to fit a gamma distribution

2009-04-13 Thread ning luwen
hi,
  i need to fit a gamma distribution, is there any module can do the job?



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


Re: Data Model:

2009-04-13 Thread Aaron Brady
On Apr 13, 2:29 am, Anthony  wrote:
> On Apr 12, 9:36 pm, Aaron Brady  wrote:
>
>
>
> > On Apr 12, 10:33 pm, Anthony  wrote:
>
> > > On Apr 12, 8:10 pm, Aaron Brady  wrote:
>
> > > > On Apr 12, 9:14 pm, Anthony  wrote:
>
> > > > > I'm struggling on whether or not to implement GroupItem (below) with
> > > > > two separate models, or with one model that has a distinguishing key:
>
> > > > > Given:
> > > > > class ParentGroup:
> > > > >     a group of values represented by class GroupItem
>
> > > > > class ChildGroup:
> > > > >     a group of values represented by class GroupItem
> > > > >     foreign-key to ParentGroup (many Children sum to one Parent)
>
> > > > > Option A:
> > > > > class GroupItem:
> > > > >     foreign-key to ParentGroup
> > > > >     foreign-key to ChildGroup
> > > > >     GroupItemType in (ParentItem, ChildItem)
> > > > >     value
> > > > >     value-type
>
> > > > > Option B:
> > > > > class ParentGroupItem
> > > > >     foreign-key to ParentGroup
> > > > >     value
> > > > >     value-type
>
> > > > > class ChildGroupItem
> > > > >     foreign-key to ChildGroup
> > > > >     value
> > > > >     value-type
>
> > > > > What are my considerations when making this decision?
>
> > > > > Thanks!
>
> > > > You want a ChildItem to have membership in two collections:
> > > > ParentGroup and ChildGroup.  You also want a ParentItem to have
> > > > membership in one collection.  For example:
>
> > > > parentA: itemPA1, itemPA2, childA, childB
> > > > childA: itemCA1, itemCA2
> > > > childB: itemCB1, itemCB2
>
> > > > Or, listing by child,
>
> > > > itemPA1: parentA
> > > > itemPA2: parentA
> > > > itemCA1: childA
> > > > itemCA2: childA
> > > > itemCB1: childB
> > > > itemCB2: childB
> > > > childA: parentA
> > > > childB: parentA
>
> > > > Correct so far?
>
> > > Thanks for the insightful response.
>
> > > Yes, everything you say is correct, with one clarification:  The
> > > ChildItem can be a member of ParentGroup OR ChildGroup, but never both
> > > at the same time.
>
> > I see.  You described a collection class.  Its members are items or
> > other collections.  They are never nested more than two levels deep.
>
> > However, in your example, you implied a collection class whose
> > attributes are aggregates of its members'.  For simplicity, you can
> > use methods to compute the aggregate attributes.
>
> > class Group:
> >   def calculate_total_produced( self ):
> >     total= sum( x.total_produced for x in self.members )
>
> > If you want to cache them for performance, the children will have to
> > notify the parent when one of their attributes changes, which is at
> > least a little more complicated.  The class in the simpler structure
> > could even derive from 'set' or other built-in collection if you
> > want.  Are you interested in the more complicated faster technique?
>
> Yes, in my example, the top level collection class is implicitly the
> aggregate of the lower level class.  However, data entry will take
> place at the top level, not necessarily at the lower level.  This
> means that the lower level values will never drive the top level
> value.  Instead, the aggregate of the lower levels will be validated
> against the top level.  If there is a discrepancy, then the remainder
> will be applied to an additional "Unregistered" instance of the lower
> level.
>
> e.g.
>
> Group: Johnson - Total Units Produced 25;  Units Consumed 18;
>   Chris Johnson - Units Produced 18; Units Consumed 10;
>   Jim Johnson   - Units Produced 3;  Units Consumed 5;
>
> The group totals are the basis for any validations.  In this example,
> another entry will be created to account for the discrepancy:
>
>   Unregistered -  Units Produced 4;  Units Consumed 3
>
> As far as child notification of the parent, I plan to only allow data
> entry on a form that includes both parent and child level values.
> Validation of top level to child level aggregates can happen at this
> time.  This should remove the need for notification, right?
>
> Am I looking at 6 of one and half dozen of the other between options A
> and B at this point?  I'm currently leaning towards option B.  Is
> there anything I will be losing performance-wise by not choosing
> option A?
>
> Thanks again for conversing with me on this.

It sounds like you want your total to also be degenerate instance of
the Item class.  It has a name and two numeric attributes.  I once
learned that it "meant the right thing" to merely derive the Total
class from the Item class, and raise an exception when and if non-
aggregate values are attempted to access.

There is a little wasted space on A, which you probably needn't worry
about.  In C, you can create a 'union' type, that holds the parent
foreign-key -or- the child foreign-key, and use the "GroupItemType in"
flag to signal which, but not both.  The space required is whichever
is larger.   In Python, you can just use one object, and
treat it differently depending on the 'itemtype in' flag.

>From what I und

Re: Data Model:

2009-04-13 Thread Peter Otten
Anthony wrote:

> On Apr 12, 7:46 pm, Aaron Watters  wrote:
>> On Apr 12, 10:14 pm, Anthony  wrote:
>>
>>
>>
>> > I'm struggling on whether or not to implement GroupItem (below) with
>> > two separate models, or with one model that has a distinguishing key:
>>
>> > Given:
>> > class ParentGroup:
>> > a group of values represented by class GroupItem
>>
>> > class ChildGroup:
>> > a group of values represented by class GroupItem
>> > foreign-key to ParentGroup (many Children sum to one Parent)
>>
>> > Option A:
>> > class GroupItem:
>> > foreign-key to ParentGroup
>> > foreign-key to ChildGroup
>> > GroupItemType in (ParentItem, ChildItem)
>> > value
>> > value-type
>>
>> > Option B:
>> > class ParentGroupItem
>> > foreign-key to ParentGroup
>> > value
>> > value-type
>>
>> > class ChildGroupItem
>> > foreign-key to ChildGroup
>> > value
>> > value-type
>>
>> > What are my considerations when making this decision?
>>
>> > Thanks!
>>
>> It looks to me that the two designs
>> might be useful for different
>> purposes.  What are you trying to do?
>>
>> -- Aaron Watters
>>
>> 
>>
whiff.sourceforge.nethttp://aaron.oirt.rutgers.edu/myapp/root/misc/erdTest
> 
> The group values represent statistics that I'm tracking, based on
> activity groups.  Some samples:
> 
> Group: Johnson, Total Units Produced = 10, Total Units Consumed = 5
> Chris Johnson, Units Produced = 6, Units Consumed = 3
> Jim Johnson, Units Produced = 4, Units Consumed = 2
> 
> Group: Smith, Total Units Produced = 15, Total Units Consumed = 8
> Mark Smith, Units Produced = 7, Units Consumed = 5
> Bob Smith, Units Produced = 8, Units Consumed = 3
> 
> The groups will be responsible for entering their own statistics, so I
> will have to do some validation at data entry.  The ability to create
> new statistic types (e.g. Units Broken) for new groups in the future
> is important.
> 
> What would be the advantages of using option A versus option B?

I may be missing something, but your example looks more like option C:

class Group:
name

class Member:
group # foreign key to Group
name

class Item:
member # foreign key to Member
type
value

You can calculate the totals for members or groups on the fly; the classical
tool would be a relational database.

Peter

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


Re: GUI Programming

2009-04-13 Thread Gabriel

Gabriel wrote:

Hello,

I'm python newbie and i need to write gui for my school work in python.
I need to write it really quick, because i haven't much time .)
So question is, which of gui toolkits should i pick and learn? I heard 
PyGTK and Glade are best for quick gui programming? Is it good for 
beginner? Or is there something better?

I have some experience with java swing, btw..
--
http://mail.python.org/mailman/listinfo/python-list

I'm going to try wxPython because i found some stuff i need on web and 
it seems easy to me .)
But I checked everything you mentioned and i discovered that python is 
really great to write gui (not only of course ,))

Thank you all
--
http://mail.python.org/mailman/listinfo/python-list


Re: Definition of Pythonic?

2009-04-13 Thread Francesco Bochicchio

John Yeung ha scritto:

On Apr 11, 10:08 am, Emmanuel Surleau 
wrote:

Having written a few trivial scripts in Python, I'm curious as
to how you would sum up the Pythonic philosophy of development.


A couple of others have already mentioned the Zen of Python, available
at the Python command prompt.  I would agree with that, but also add
the caveat that none of the principles expressed there are hard-and-
fast rules.  Hopefully that is clear from the quasi-contradictory
nature of the principles, but inevitably there will be some people who
complain that Python breaks this or that "rule" from the Zen.



I believe the almost-contraddictory nature of the various listed 
principles is on-purpose. My anecdotal knowledge of the Zen tells me
that is based on the balance of two 'opposing forces', the Yin and the 
Yang. So the 'zen of python' attempts to enunciate the various yins and
yangs of software development, leaving to the developers the task of 
finding the right equilibrium among them.


Which is pretty sensible, since good engineering is often based more on 
choosing the right trade-off rather than choosing the One Right Thing to do.


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


Using a decorator to *remove* parameters from a call

2009-04-13 Thread Michel Albert
A small foreword: This might look like a cherrypy-oriented post, and
should therefore go to the cherrypy group, but if you read to the end,
you'll see it's a more basic python problem, with cherrypy only as an
example. ;)

>From the decorator PEP (318) I get it that you can /add/ parameters to
a call. Say you do something like this:

@mydeco( foo="bar" )
def myfunc( hello ):
   print foo, foo

However, this is not what I would like to do. I would like to take
away one or more attributes using a decorator. My goal is to
centralize the logic associated with that parameter. In my particular
example, I am writing a cherrypy application (more specifically,
turbogears1) and I would like all controller method to accept a "lang"
and a "skin" attribute. As a simple, but hands-on example, imagine
code like this (http://python.pastebin.com/f25f2429b):

class MyController(Controller):

@expose()
def index(self, skin="default", lang="en"):
set_skin( skin )
set_language( lang )
return "Hello skinned world"

@expose()
def foo(self, skin="default", lang="en"):
set_skin( skin )
set_language( lang )
return "bar"

This becomes cumbersome however for a large application with many
controllers and methods. Always adding the parameters to the methods
and function calls into the method bodies looks way to repetitive for
my taste.

Currently I solve this by using a cherrypy filter which removes those
parameters from the HTTP-Request and puts them into the session
object. This looked wrong to me though right from the start. Also, the
cherrypy docs advise against the use of "filters" for application
logic. But this looks pretty much like that to me somewhat. Worse
yet, filters are not supported in Turbogears2 any longer. Which makes
porting my app not straight-forward, as I have to port my filters and
write WSGI middleware instead.

I would prefer a syntax like this (http://python.pastebin.com/
f462bc29c)

class MyController(Controller):

@expose()
@skinnable
@translatable
def index(self):
return "Hello skinned world"

@expose()
@skinnable
@translatable
def foo(self):
return "bar"

This, to me has several advantages: The logic is "encapsulated" in the
application code itself. I do not need to rely on framework specific
features (be it cherrypy or wsgi). This would make the application
more self-contained and hence more future proof.

But right here lies my problem. If you are not familiar with CherryPy,
let me digress for a tiny bit to give you the necessary backgroud:

Inside a controller, an "exposed" method is reachable via HTTP
requests. It's possible to force request parameters. If that is the
case (as in my case it is), then the call will only be successful, if
all parameters received a vaule and no unknown parameters have been
passed. Assume the following signature:

def index(self)

This will successfully return an HTTP Response when the client
requested the resource on the URL "/index". If the client adds a query
string, say "/index?lang=en" the call will *fail* as this parameter is
unkown. For this to work the signature must read:

def index(self, lang)

or

def index(self, lang="en")

Right end of digression, back to topic:

My ultimate question is: Is it possible to write a decorator that
removes a parameter from a call and return a function without that
parameter? Something along the lines (http://python.pastebin.com/
f257877cd):

def translatable(f):
"Note that this code is only an example and will not work!"
lang = f.__get_parameter_value__("lang")
f.__remove_parameter__("lang")
do_something_with_lang(lang)
return f

I am aware, that this depends on *when* the decorator call is
executed. If its called whenever the decorated function is called,
then there should be some way to handle this. If it's called at
"compile-time", then I suppose it's not going to be possible.

A usage scenario would be this:

# --- definition ---
@translatable
def index(self):
   return _("Hello", lang)

# --- call --
obj.index( lang="de")
obj.index()

As you can see, the method definition does not contain the "lang"
parameter in the signature, but I want to be able to (optionally) set
it during a call.

I hope I made my ideas clear enough. I would be very positively
surprised if this worked. It would make my application code much
easier to read, understand and follow. The filters currently do a lot
of magic "behind-the-scenes" and if somebody else needs to jump in and
code on that application they will surely ask themselves "where the
** is that * lang variable set?" :) And I'd like to make it as
easy as possible for everyone :)

Or, maybe you even have a better solution in mind? I'm open for
suggestions.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Falcon - powering innovation

2009-04-13 Thread Gerhard Häring
Kless wrote:
> If anybody is interesed in new technologies, you'll love this new
> language called Falcon [1], which has been open sourced ago little
> time.
> 
> Falcon is a scripting engine ready to empower mission-critical
> multithreaded applications. 

"Mission-critical" and "empower" sound like a good start for bullshit
bingo :-P

> It provides six integrated programming
> paradigms: procedural, object oriented, prototype oriented,
> functional, tabular and message oriented. You use what you prefer.

I've never heard of tabular programming before.

> To know more about its design, read the interview to the Falcon author
> that has published ComputerWorld Australia [2].

-- Gerhard

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


Re: video capture in Python ?

2009-04-13 Thread Stef Mientki

Tim Roberts wrote:

Stef Mientki  wrote:
  

has anyone got video capturing (from a webcam)  successful  running
in a wxPython application under winXP ?

I got some links, but it seems quit complicated to get everything 
installed,
and all the packages you need don't describe which versions of the other 
parts you need,

so a lot trial and error I expect.



What packages have you tried?
  

videocapture
webcamwatcher
opencv
libvidcap
hdpvrassistent

they didn't run at all or they crashed within 10 seconds :-(
The most promissing looks videocapture, but that also crashes within 10 
seconds.

Video capture is not a trivial task.

to be more exactly, I think you mean  "it's not a trival task in Python"

I just created a Delphi project to select a video device, show the cam 
image on the screen and store the movie in a file:

- less than 10 lines of code,
- less than 10 minutes of work
and the program looks rock stable !

So for this project I'll probably go back to Delphi ;-)

thanks,
Stef Mientki


  There is a lot to do, although most
of it is boilerplate that you will reuse from app to app.
  


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


Re: Using a decorator to *remove* parameters from a call

2009-04-13 Thread Aaron Brady
On Apr 13, 5:11 am, Michel Albert  wrote:
> A small foreword: This might look like a cherrypy-oriented post, and
> should therefore go to the cherrypy group, but if you read to the end,
> you'll see it's a more basic python problem, with cherrypy only as an
> example. ;)
>
> From the decorator PEP (318) I get it that you can /add/ parameters to
> a call. Say you do something like this:
>
> @mydeco( foo="bar" )
> def myfunc( hello ):
>    print foo, foo
snip
> I would prefer a syntax like this (http://python.pastebin.com/
> f462bc29c)
>
> class MyController(Controller):
>
>     @expose()
>     @skinnable
>     @translatable
>     def index(self):
>         return "Hello skinned world"
>
>     @expose()
>     @skinnable
>     @translatable
>     def foo(self):
>         return "bar"
>
snip
> more future proof.
snip

Sure.  Just pop the keywords you want from the dictionary, if they
exist.

def take_ab( fun ):
def newfun( *ar, **kw ):
aval= kw.pop( 'a', None )
bval= kw.pop( 'b', None )
print( 'aval %r and bval %r popped'% ( aval, bval ) )
res= fun( *ar, **kw )
return res
return newfun

@take_ab
def f( c= 42, d= 'some' ):
print( 'in f, c= %r, d= %r'% ( c, d ) )

f( a= 'paramA', b= 'paramB', c= 'other number' )

/Output:

aval 'paramA' and bval 'paramB' popped
in f, c= 'other number', d= 'some'

As you can see, 'a', 'b', and 'c' were passed to 'f', but 'f' only
received 'c', as well as its default value for 'd'.  So long as you
only need to pass by keyword, not position, it's pretty easy.  It's
harder if the parameter you want might have been passed by either, and
you need to remove it from whichever one it was passed by.
--
http://mail.python.org/mailman/listinfo/python-list


Re: numpy permutations with replacement

2009-04-13 Thread Chris Rebert
On Mon, Apr 13, 2009 at 4:05 AM, skorpi...@gmail.com
 wrote:
> I am trying to generate all possible permutations of length three from
> elements of [0,1]. i.e in this scenario there are a total of 8
> distinct permutations:
>
> [0,0,0]
> [0,0,1]
> [0,1,0]
>    .
>    .
>    .
> [1,1,1]
>
>
> Does numpy define a function to achieve this ?

No idea, but the Python standard library already has this covered with
itertools.permutations()
[http://docs.python.org/library/itertools.html].

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: regex for multiple whitespace-only lines

2009-04-13 Thread MRAB

Phil Mayes wrote:

I am trying to search for 1 or more empty or white-space-only lines.
Empty lines work:
 >>> re.compile('(?m)(^$){1,2}')
<_sre.SRE_Pattern object at 0x010F9218>

One line with possible whitespace works:
 >>> re.compile('(?m)(^\s*$)')
<_sre.SRE_Pattern object at 0x010F7860>

Multiple lines with possible whitespace don't:
 >>> re.compile('(?m)(^\s*$)+')
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\lib\re.py", line 180, in compile
return _compile(pattern, flags)
  File "C:\Python25\lib\re.py", line 233, in _compile
raise error, v # invalid expression
error: nothing to repeat

Does anyone know a work-round?


(?m)^(?:[ \t]*\n)+
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Falcon - powering innovation

2009-04-13 Thread Tim Chase

Gerhard Häring wrote:

Kless wrote:

If anybody is interesed in new technologies, you'll love this new
language called Falcon [1], which has been open sourced ago little
time.

Falcon is a scripting engine ready to empower mission-critical
multithreaded applications. 


"Mission-critical" and "empower" sound like a good start for bullshit
bingo :-P


All I need is "synergy", "paradigm", or "please advise" and I've won!


It provides six integrated programming paradigms:


Oh, wait...BINGO!


procedural, object oriented, prototype oriented,
functional, tabular and message oriented. You use what you prefer.


I've never heard of tabular programming before.


I think that's a violation of PEP-8...doesn't that suggest using 
spaces instead of tabs?  Or maybe your code goes in a table, so 
it's "programming with Excel"?


And only six programming paradigms?  What about "buzzword 
oriented"?  And how about "declarative oriented" for the Prolog 
refugees?  Pshaw...and you (OP) suggest it's multiparadigmatic?


-tkc



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


Re: numpy permutations with replacement

2009-04-13 Thread skorpi...@gmail.com
On Apr 13, 7:13 am, Chris Rebert  wrote:
> On Mon, Apr 13, 2009 at 4:05 AM, skorpi...@gmail.com
>
>  wrote:
> > I am trying to generate all possible permutations of length three from
> > elements of [0,1]. i.e in this scenario there are a total of 8
> > distinct permutations:
>
> > [0,0,0]
> > [0,0,1]
> > [0,1,0]
> >    .
> >    .
> >    .
> > [1,1,1]
>
> > Does numpy define a function to achieve this ?
>
> No idea, but the Python standard library already has this covered with
> itertools.permutations()
> [http://docs.python.org/library/itertools.html].
>
> Cheers,
> Chris
>
> --
> I have a blog:http://blog.rebertia.com

Thanks Chris,

That looks promising, however I am still stuck at python 2.5 (I need
numpy). And the 2.5 version does not look as nice as the 2.6 itertool.
So, if there is a numpy method ... please let me know ..
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using a decorator to *remove* parameters from a call

2009-04-13 Thread Jon Clements
On 13 Apr, 11:11, Michel Albert  wrote:
> A small foreword: This might look like a cherrypy-oriented post, and
> should therefore go to the cherrypy group, but if you read to the end,
> you'll see it's a more basic python problem, with cherrypy only as an
> example. ;)
>
> From the decorator PEP (318) I get it that you can /add/ parameters to
> a call. Say you do something like this:
>
> @mydeco( foo="bar" )
> def myfunc( hello ):
>    print foo, foo
>
> However, this is not what I would like to do. I would like to take
> away one or more attributes using a decorator. My goal is to
> centralize the logic associated with that parameter. In my particular
> example, I am writing a cherrypy application (more specifically,
> turbogears1) and I would like all controller method to accept a "lang"
> and a "skin" attribute. As a simple, but hands-on example, imagine
> code like this (http://python.pastebin.com/f25f2429b):
>
> class MyController(Controller):
>
>     @expose()
>     def index(self, skin="default", lang="en"):
>         set_skin( skin )
>         set_language( lang )
>         return "Hello skinned world"
>
>     @expose()
>     def foo(self, skin="default", lang="en"):
>         set_skin( skin )
>         set_language( lang )
>         return "bar"
>
> This becomes cumbersome however for a large application with many
> controllers and methods. Always adding the parameters to the methods
> and function calls into the method bodies looks way to repetitive for
> my taste.
>
> Currently I solve this by using a cherrypy filter which removes those
> parameters from the HTTP-Request and puts them into the session
> object. This looked wrong to me though right from the start. Also, the
> cherrypy docs advise against the use of "filters" for application
> logic. But this looks pretty much like that to me somewhat. Worse
> yet, filters are not supported in Turbogears2 any longer. Which makes
> porting my app not straight-forward, as I have to port my filters and
> write WSGI middleware instead.
>
> I would prefer a syntax like this (http://python.pastebin.com/
> f462bc29c)
>
> class MyController(Controller):
>
>     @expose()
>     @skinnable
>     @translatable
>     def index(self):
>         return "Hello skinned world"
>
>     @expose()
>     @skinnable
>     @translatable
>     def foo(self):
>         return "bar"
>
> This, to me has several advantages: The logic is "encapsulated" in the
> application code itself. I do not need to rely on framework specific
> features (be it cherrypy or wsgi). This would make the application
> more self-contained and hence more future proof.
>
> But right here lies my problem. If you are not familiar with CherryPy,
> let me digress for a tiny bit to give you the necessary backgroud:
>
> Inside a controller, an "exposed" method is reachable via HTTP
> requests. It's possible to force request parameters. If that is the
> case (as in my case it is), then the call will only be successful, if
> all parameters received a vaule and no unknown parameters have been
> passed. Assume the following signature:
>
> def index(self)
>
> This will successfully return an HTTP Response when the client
> requested the resource on the URL "/index". If the client adds a query
> string, say "/index?lang=en" the call will *fail* as this parameter is
> unkown. For this to work the signature must read:
>
> def index(self, lang)
>
> or
>
> def index(self, lang="en")
>
> Right end of digression, back to topic:

Haven't finished coffee yet, plus it's a bank holiday! [/excuse]

Can't that be changed to def index(self, **kwdargs) -- then your
decorators can operate something like set_language(kwdargs.get('lang',
'en')) and then delete the key

Anyway, back to more coffee!

>
> My ultimate question is: Is it possible to write a decorator that
> removes a parameter from a call and return a function without that
> parameter? Something along the lines (http://python.pastebin.com/
> f257877cd):
>
> def translatable(f):
>     "Note that this code is only an example and will not work!"
>     lang = f.__get_parameter_value__("lang")
>     f.__remove_parameter__("lang")
>     do_something_with_lang(lang)
>     return f
>
> I am aware, that this depends on *when* the decorator call is
> executed. If its called whenever the decorated function is called,
> then there should be some way to handle this. If it's called at
> "compile-time", then I suppose it's not going to be possible.
>
> A usage scenario would be this:
>
> # --- definition ---
> @translatable
> def index(self):
>    return _("Hello", lang)
>
> # --- call --
> obj.index( lang="de")
> obj.index()
>
> As you can see, the method definition does not contain the "lang"
> parameter in the signature, but I want to be able to (optionally) set
> it during a call.
>
> I hope I made my ideas clear enough. I would be very positively
> surprised if this worked. It would make my application code much
> easier to read, u

numpy permutations with replacement

2009-04-13 Thread skorpi...@gmail.com
I am trying to generate all possible permutations of length three from
elements of [0,1]. i.e in this scenario there are a total of 8
distinct permutations:

[0,0,0]
[0,0,1]
[0,1,0]
.
.
.
[1,1,1]


Does numpy define a function to achieve this ?

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


Re: Generators/iterators, Pythonicity, and primes

2009-04-13 Thread Aaron Brady
On Apr 13, 1:39 am, Arnaud Delobelle  wrote:
> Duncan Booth  writes:
> > Duncan Booth  wrote:
>
> >> John Posner  wrote:
>
> >>> Do know what in the itertools implementation causes adding a 'if p <=
> >>> sqrt(n)' clause to *decrease* performance, while adding a
> >>> 'takewhile()' clause *increases* performance?
>
> >> I haven't timed it, but I would guess that the takewhile was faster
> >> only because the sqrt(n) had been factored out of the loop. Try the
> >> original loop again precalculating the sqrt(n) and see how that compares.
>
> > Which of course is rubbish, extracting the sdqrt will have an effect but
> > the main factor is that takewhile exits the loop as soon as the condition
> > is false whereas a conditional in a generator comprehension doesn't stop
> > the loop continuing to the end.
>
> Absolutely!  Since you hadn't quoted the original code, I'd forgotten
> that it wasn't stopping after n**0.5.
>
> --
> Arnaud

-1 entertaining, list.  Come on, people, the show must go on.  Take
five.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Falcon - powering innovation

2009-04-13 Thread Andrii V. Mishkovskyi
On Sat, Apr 11, 2009 at 4:11 PM, Kless  wrote:
[skipped buzzwords]
>
>
> [1] http://www.falconpl.org/
> [2] 
> http://www.computerworld.com.au/article/298655/-z_programming_languages_falcon?fp=2&fpid=

And this table should make you even more interested in Falcon (also
called THE BEST PROGRAMMING LANGUAGE EVAR):

http://www.falconpl.org/index.ftd?page_id=facts

Yes, it's a proven fact that Falcon is better than Python, Ruby, Perl,
Lua, PHP, C or Lisp. This is a table of truth!
But I have one important question about Falcon:
Does it have ponies?


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



-- 
Wbr, Andrii V. Mishkovskyi.

He's got a heart of a little child, and he keeps it in a jar on his desk.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using a decorator to *remove* parameters from a call

2009-04-13 Thread Michel Albert
On Apr 13, 12:52 pm, Jon Clements  wrote:
> On 13 Apr, 11:11, Michel Albert  wrote:
>
>
>
> > A small foreword: This might look like a cherrypy-oriented post, and
> > should therefore go to the cherrypy group, but if you read to the end,
> > you'll see it's a more basic python problem, with cherrypy only as an
> > example. ;)
>
> > From the decorator PEP (318) I get it that you can /add/ parameters to
> > a call. Say you do something like this:
>
> > @mydeco( foo="bar" )
> > def myfunc( hello ):
> >    print foo, foo
>
> > However, this is not what I would like to do. I would like to take
> > away one or more attributes using a decorator. My goal is to
> > centralize the logic associated with that parameter. In my particular
> > example, I am writing a cherrypy application (more specifically,
> > turbogears1) and I would like all controller method to accept a "lang"
> > and a "skin" attribute. As a simple, but hands-on example, imagine
> > code like this (http://python.pastebin.com/f25f2429b):
>
> > class MyController(Controller):
>
> >     @expose()
> >     def index(self, skin="default", lang="en"):
> >         set_skin( skin )
> >         set_language( lang )
> >         return "Hello skinned world"
>
> >     @expose()
> >     def foo(self, skin="default", lang="en"):
> >         set_skin( skin )
> >         set_language( lang )
> >         return "bar"
>
> > This becomes cumbersome however for a large application with many
> > controllers and methods. Always adding the parameters to the methods
> > and function calls into the method bodies looks way to repetitive for
> > my taste.
>
> > Currently I solve this by using a cherrypy filter which removes those
> > parameters from the HTTP-Request and puts them into the session
> > object. This looked wrong to me though right from the start. Also, the
> > cherrypy docs advise against the use of "filters" for application
> > logic. But this looks pretty much like that to me somewhat. Worse
> > yet, filters are not supported in Turbogears2 any longer. Which makes
> > porting my app not straight-forward, as I have to port my filters and
> > write WSGI middleware instead.
>
> > I would prefer a syntax like this (http://python.pastebin.com/
> > f462bc29c)
>
> > class MyController(Controller):
>
> >     @expose()
> >     @skinnable
> >     @translatable
> >     def index(self):
> >         return "Hello skinned world"
>
> >     @expose()
> >     @skinnable
> >     @translatable
> >     def foo(self):
> >         return "bar"
>
> > This, to me has several advantages: The logic is "encapsulated" in the
> > application code itself. I do not need to rely on framework specific
> > features (be it cherrypy or wsgi). This would make the application
> > more self-contained and hence more future proof.
>
> > But right here lies my problem. If you are not familiar with CherryPy,
> > let me digress for a tiny bit to give you the necessary backgroud:
>
> > Inside a controller, an "exposed" method is reachable via HTTP
> > requests. It's possible to force request parameters. If that is the
> > case (as in my case it is), then the call will only be successful, if
> > all parameters received a vaule and no unknown parameters have been
> > passed. Assume the following signature:
>
> > def index(self)
>
> > This will successfully return an HTTP Response when the client
> > requested the resource on the URL "/index". If the client adds a query
> > string, say "/index?lang=en" the call will *fail* as this parameter is
> > unkown. For this to work the signature must read:
>
> > def index(self, lang)
>
> > or
>
> > def index(self, lang="en")
>
> > Right end of digression, back to topic:
>
> Haven't finished coffee yet, plus it's a bank holiday! [/excuse]
>
> Can't that be changed to def index(self, **kwdargs) -- then your
> decorators can operate something like set_language(kwdargs.get('lang',
> 'en')) and then delete the key

Sure. It could work like that. But that, in my case, would mean that
anyone could pass any parameters into that method. That should not
make any problems, but I prefer enforcing only the parameters I expect
(and /only/ those) to be passed into the method. If only for my own
sanity ;)

> Anyway, back to more coffee!

enjoy!

> > My ultimate question is: Is it possible to write a decorator that
> > removes a parameter from a call and return a function without that
> > parameter? Something along the lines (http://python.pastebin.com/
> > f257877cd):
>
> > def translatable(f):
> >     "Note that this code is only an example and will not work!"
> >     lang = f.__get_parameter_value__("lang")
> >     f.__remove_parameter__("lang")
> >     do_something_with_lang(lang)
> >     return f
>
> > I am aware, that this depends on *when* the decorator call is
> > executed. If its called whenever the decorated function is called,
> > then there should be some way to handle this. If it's called at
> > "compile-time", then I suppose it's not going to be possible.
>
>

Re: Using a decorator to *remove* parameters from a call

2009-04-13 Thread Michel Albert
On Apr 13, 12:45 pm, Aaron Brady  wrote:
> On Apr 13, 5:11 am, Michel Albert  wrote:
>
> > A small foreword: This might look like a cherrypy-oriented post, and
> > should therefore go to the cherrypy group, but if you read to the end,
> > you'll see it's a more basic python problem, with cherrypy only as an
> > example. ;)
>
> > From the decorator PEP (318) I get it that you can /add/ parameters to
> > a call. Say you do something like this:
>
> > @mydeco( foo="bar" )
> > def myfunc( hello ):
> >    print foo, foo
> snip
> > I would prefer a syntax like this (http://python.pastebin.com/
> > f462bc29c)
>
> > class MyController(Controller):
>
> >     @expose()
> >     @skinnable
> >     @translatable
> >     def index(self):
> >         return "Hello skinned world"
>
> >     @expose()
> >     @skinnable
> >     @translatable
> >     def foo(self):
> >         return "bar"
>
> snip
> > more future proof.
>
> snip
>
> Sure.  Just pop the keywords you want from the dictionary, if they
> exist.
>
> def take_ab( fun ):
>     def newfun( *ar, **kw ):
>         aval= kw.pop( 'a', None )
>         bval= kw.pop( 'b', None )
>         print( 'aval %r and bval %r popped'% ( aval, bval ) )
>         res= fun( *ar, **kw )
>         return res
>     return newfun
>
> @take_ab
> def f( c= 42, d= 'some' ):
>     print( 'in f, c= %r, d= %r'% ( c, d ) )
>
> f( a= 'paramA', b= 'paramB', c= 'other number' )
>
> /Output:
>
> aval 'paramA' and bval 'paramB' popped
> in f, c= 'other number', d= 'some'
>
> As you can see, 'a', 'b', and 'c' were passed to 'f', but 'f' only
> received 'c', as well as its default value for 'd'.  So long as you
> only need to pass by keyword, not position, it's pretty easy.  It's
> harder if the parameter you want might have been passed by either, and
> you need to remove it from whichever one it was passed by.

Thanks. That works like a charm. I tried that last night and it gave
me an error. So I must have had a typo in there somewhere. Not enough
sleep I guess ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: download robot

2009-04-13 Thread Kushal Kumaran
On Mon, Apr 13, 2009 at 11:13 AM, larryzhang  wrote:
> Hi,
> Being a newbie for Python, I am trying to write a code that can act as
> a downloading robot.
>

This might be useful: http://wwwsearch.sourceforge.net/mechanize/.
I've only casually gone through the page, not actually used it.  If
you feel like it, you can also use the urllib2 in the library to do
all the work yourself.  Notes if you go this way are below.

> The website provides information for companies. Manually, I can search
> by company name and then click the “download” button to get the data
> in excel or word format, before saving the file in a local directory.
> The program is to do this automatically.
>
> I have met several problems when writing the codes:
> 1. The website needs user ID and password, is there a way that I can
> pass my ID and password to the server in my python code?

See the examples in the urllib2 documentation for how to send a
username and password for Basic authentication.  If the authentication
is done using forms, you'll need to put that data with your request.
The website might then use cookies to track you, so your code will
need to be prepared to handle that.

> 2. Can Python hit the “download” button automatically and choose the
> type of file format as I can do manually?

The download button will probably be just an appropriate GET or POST
request.  You'll need to be familiar with HTML forms to be able to do
this.

> 3. The url of each downloading webpage is not unique (webpages point
> to different data files may share the same url), which prevent me from
> working directly with the url as the address to find a certain file.
> Is there any solution for this? Does this mean I have to work directly
> with the database stored in the server rather than with the webpage
> displayed?

This simply means that the identifiers for the file to download are
being passed in using means other than the URL, most likely as POST
data.  Look at the HTML for the page to see how.

>
> Thank you very much for any comments and suggestions.
>

You'll find tools that let you observe the communication between your
browser and the web server useful.  If you use Mozilla Firefox, the
httpfox extension might help.

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


Re: video capture in Python ?

2009-04-13 Thread Tino Wildenhain

Hi Stef,

Stef Mientki wrote:
...

videocapture
webcamwatcher
opencv
libvidcap
hdpvrassistent

they didn't run at all or they crashed within 10 seconds :-(
The most promissing looks videocapture, but that also crashes within 10 
seconds.

Video capture is not a trivial task.

to be more exactly, I think you mean  "it's not a trival task in Python"

I just created a Delphi project to select a video device, show the cam 
image on the screen and store the movie in a file:

- less than 10 lines of code,
- less than 10 minutes of work
and the program looks rock stable !

So for this project I'll probably go back to Delphi ;-)


Or C. OpenCV has nice examples.

For Video Capture, the external library needs to do most of the work
obviously, since this is the corner case for a scripting language.
(Even Delphi can be suboptimal depending on what you want to do
once you captured a frame)

I can say opencv worked great for me both on linux and windows
and didn't crash. Maybe you have just an unlucky combination
of drivers.

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


Re: HTML Conversion in python

2009-04-13 Thread Aaron Watters
On Apr 13, 1:47 am, "venutaurus...@gmail.com"
 wrote:
> Hello All,
> Is there any library defined in Python which can convert a
> given text file into a html page. Basically, I require functions for
> creating tables or filling background colours for the html pages etc
> instead of writing each and every tag in my script..
>
> Thank you,
> Venu Madhav.

At the risk of being annoying, I just announced
a suite of tools that includes a methodology for
building complex pages by combining simple page fragments.

Please have a look at the tutorial
  http://aaron.oirt.rutgers.edu/myapp/docs/W1100.tutorial

This is the configuration source for the tutorial page

{{use-url "comments"}}
   {{section title}} Tutorial {{/section}}
   {{section summary}}
  Walking through some examples will help you learn
  the organization and capabilities of the whiff
  package.
   {{/section}}
   {{section body}}
  These tutorials hope to introduce WHIFF by discussing a number
  of use cases, beginning with simple ones and progressing to
examples
  with greater complexity.
  
  (UNDER CONSTRUCTION)
   {{/section}}
{{/use-url}}

The page generated from this source is much
more complex than that (take a look).  The
"comments" URL points to another WHIFF template
which defines the scaffolding for all WHIFF
documentation pages.  The "comments" page in turn
uses other fragments and scaffoldings...

There are many other
HTML generation approaches as indicated by the
Wiki link previously.  As far as I
know the WHIFF approach is the most "compositional".
Please correct me if I'm wrong.

Thanks, -- Aaron Watters

===
'To join the Guild I had to kill somebody,
cruelly, with no mercy, and without reason
-- so I killed the dwarf, because she was
really annoying anyway.'
  -- World of Warfare talk, overheard.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to fit a gamma distribution

2009-04-13 Thread Kushal Kumaran
On Mon, Apr 13, 2009 at 1:40 PM, ning luwen  wrote:
> hi,
>  i need to fit a gamma distribution, is there any module can do the job?
>

Did you try google?  Searching for python curve fitting returns some
promising results.

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


Re: Using a decorator to *remove* parameters from a call

2009-04-13 Thread azeem
On Apr 13, 3:45 pm, Aaron Brady  wrote:
> On Apr 13, 5:11 am, Michel Albert  wrote:
>
> > A small foreword: This might look like a cherrypy-oriented post, and
> > should therefore go to the cherrypy group, but if you read to the end,
> > you'll see it's a more basic python problem, with cherrypy only as an
> > example. ;)
>
> > From the decorator PEP (318) I get it that you can /add/ parameters to
> > a call. Say you do something like this:
>
> > @mydeco( foo="bar" )
> > def myfunc( hello ):
> >    print foo, foo
> snip
> > I would prefer a syntax like this (http://python.pastebin.com/
> > f462bc29c)
>
> > class MyController(Controller):
>
> >     @expose()
> >     @skinnable
> >     @translatable
> >     def index(self):
> >         return "Hello skinned world"
>
> >     @expose()
> >     @skinnable
> >     @translatable
> >     def foo(self):
> >         return "bar"
>
> snip
> > more future proof.
>
> snip
>
> Sure.  Just pop the keywords you want from the dictionary, if they
> exist.
>
> def take_ab( fun ):
>     def newfun( *ar, **kw ):
>         aval= kw.pop( 'a', None )
>         bval= kw.pop( 'b', None )
>         print( 'aval %r and bval %r popped'% ( aval, bval ) )
>         res= fun( *ar, **kw )
>         return res
>     return newfun
>
> @take_ab
> def f( c= 42, d= 'some' ):
>     print( 'in f, c= %r, d= %r'% ( c, d ) )
>
> f( a= 'paramA', b= 'paramB', c= 'other number' )
>
> /Output:
>
> aval 'paramA' and bval 'paramB' popped
> in f, c= 'other number', d= 'some'
>
> As you can see, 'a', 'b', and 'c' were passed to 'f', but 'f' only
> received 'c', as well as its default value for 'd'.  So long as you
> only need to pass by keyword, not position, it's pretty easy.  It's
> harder if the parameter you want might have been passed by either, and
> you need to remove it from whichever one it was passed by.


What does the @take_ab do ?
--
http://mail.python.org/mailman/listinfo/python-list


Python inside C++

2009-04-13 Thread AJ Mayorga
Hello all,

 

I am looking for a way  to statically compile pythonxx.dll into my C++
application, so that I can use It as an internal scripting language and
either run the native python code or take an ELF from py2exe/pyinstaller and
run that.

The machines that will have my C++ app running on them do not have python
and I cannot install it as part of my application. Any Ideas?

 

AJ

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


Re: Python inside C++

2009-04-13 Thread Kushal Kumaran
On Wed, Apr 15, 2009 at 8:56 AM, AJ Mayorga  wrote:
> Hello all,
>
>
>
> I am looking for a way  to statically compile pythonxx.dll into my C++
> application, so that I can use It as an internal scripting language and
> either run the native python code or take an ELF from py2exe/pyinstaller and
> run that.
>
> The machines that will have my C++ app running on them do not have python
> and I cannot install it as part of my application. Any Ideas?
>

It's called embedding.  See the documentation on Extending and
Embedding the Python Interpreter.

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


Re: ANN: PyGUI 2.0.1

2009-04-13 Thread user

Greg Ewing wrote:

PyGUI 2.0.1 is available:

  http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/

Fixes some problems in setup.py affecting installation
on Linux and Windows.


What is PyGUI?
--

PyGUI is a cross-platform GUI toolkit designed to be lightweight
and have a highly Pythonic API.



Greg

I installed PyGUI-2.0.1 on Windows (32 bit, non Administrator access).
I got the following error in 2.0.1 when attempting the BlobEdit example:

D:\users\omh\runabq\pyGUI>c:\python26\python
Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> from GUI import Application,  ScrollableView, Document, Window, \
...   FileType, Cursor, rgb
  File "", line 1, in 
  File "c:\python26\Lib\site-packages\GUI\__init__.py", line 78, in __getattr__
traceback.print_stack()
Failed to import 'Application' from Applications
Traceback (most recent call last):
  File "c:\python26\Lib\site-packages\GUI\__init__.py", line 69, in __getattr__
module = __import__(modname, self.__dict__, locals(), [name])
  File "c:\python26\Lib\site-packages\GUI\Win32\Applications.py", line 8, in 

import Components, Windows
  File "c:\python26\Lib\site-packages\GUI\Win32\Components.py", line 12, in 

from Win32 import win_none
  File "c:\python26\lib\site-packages\GUI\Win32\__init__.py", line 2, in 

raise ImportError("This should not be imported.")
ImportError: This should not be imported.

I presume that one should be able to import GUI.Win32 if I need to import 
win_none from it.

If I comment out line 2, I get the following error:
...
  File "c:\python26\Lib\site-packages\GUI\Win32\Components.py", line 12, in 

from Win32 import win_none
ImportError: cannot import name win_none

The directory structure that was installed is as follows:
c:\python26\Lib\site-packages\GUI
c:\python26\Lib\site-packages\GUI\Generic
c:\python26\Lib\site-packages\GUI\Resources
c:\python26\Lib\site-packages\GUI\Resources\cursors
c:\python26\Lib\site-packages\GUI\Win32


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


Re: Using a decorator to *remove* parameters from a call

2009-04-13 Thread Aaron Brady
On Apr 13, 8:25 am, azeem  wrote:
> On Apr 13, 3:45 pm, Aaron Brady  wrote:
snip
> > @take_ab
> > def f( c= 42, d= 'some' ):
> >     print( 'in f, c= %r, d= %r'% ( c, d ) )
>
> > f( a= 'paramA', b= 'paramB', c= 'other number' )
>
> > /Output:
>
> > aval 'paramA' and bval 'paramB' popped
> > in f, c= 'other number', d= 'some'
>
> > As you can see, 'a', 'b', and 'c' were passed to 'f', but 'f' only
> > received 'c', as well as its default value for 'd'.  So long as you
> > only need to pass by keyword, not position, it's pretty easy.  It's
> > harder if the parameter you want might have been passed by either, and
> > you need to remove it from whichever one it was passed by.
>
> What does the @take_ab do ?

Hi.  It's a function decorator.  It replaces 'f' with another
function, which is impersonating it.

In particular, the meaning of this decorator is to remove any and all
occurrences of 'a' or 'b' in the keywords that are passed to 'f'.

So: If you call the impersonated 'f' like this:

f( 1, 2 )

Then the call proceeds as usual.  If you call it like this:

f( 1, 2, a= 'jamqar' ),

Then the real 'f' only receives this:

f( 1, 2 )

Unfortunately, to the world's loss, the original 'f' isn't practically
accessible anymore to anyone but the hijacker.  In fact, if you look
closely, you will find its internal name stamp is not 'f', but
'newfun'!

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


Re: Python inside C++

2009-04-13 Thread Aaron Brady
On Apr 13, 8:41 am, Kushal Kumaran  wrote:
> On Wed, Apr 15, 2009 at 8:56 AM, AJ Mayorga  wrote:
> > Hello all,
>
> > I am looking for a way  to statically compile pythonxx.dll into my C++
> > application, so that I can use It as an internal scripting language and
> > either run the native python code or take an ELF from py2exe/pyinstaller and
> > run that.
>
> > The machines that will have my C++ app running on them do not have python
> > and I cannot install it as part of my application. Any Ideas?
>
> It's called embedding.  See the documentation on Extending and
> Embedding the Python Interpreter.
>
> --
> kushal

But who ever heard of anyone liking Python?
--
http://mail.python.org/mailman/listinfo/python-list


Can I replace this for loop with a join?

2009-04-13 Thread WP

Hello, I have dictionary {1:"astring", 2:"anotherstring", etc}

I now want to print:
"Press 1 for astring"
"Press 2 for anotherstring" etc

I could do it like this:
dict = {1:'astring', 2:'anotherstring'}
for key in dict.keys():
print 'Press %i for %s' % (key, dict[key])

Press 1 for astring
Press 2 for anotherstring

but can I use a join instead?

Thanks for any replies!

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


Re: sharing/swapping items between lists

2009-04-13 Thread Ross
On Apr 11, 1:10 pm, a...@pythoncraft.com (Aahz) wrote:
> In article 
> <4fd78ac3-ba83-456b-b768-3a0043548...@f19g2000vbf.googlegroups.com>,
>
> Ross   wrote:
>
> >I'm trying to design an iterator that produces two lists. The first
> >list will be a list of unique pairings and the second will be a list
> >of items that weren't used in the first list. After each round, the
> >items that weren't used in the round before will get put back in and
> >the second list will be populated with unique items.
>
> How do you specify what goes into the first list?  Based on your
> description, I would have expected that the output from the first
> iteration would be
>
> ( [(1,2),(3,4),(5,6)], [7,8] )
>
> Regardless of the actual algorithm, if you are returning items one at a
> time and maintaining state in a computation, you probably want to use a
> generator.
> --
> Aahz (a...@pythoncraft.com)           <*>        http://www.pythoncraft.com/
>
> Why is this newsgroup different from all other newsgroups?

I'm sorry...my example was probably a bad one. A better example of
output I would like would be something like [[1,2],[3,4],[5,6]] and
then for the leftovers list [7,8,9,10 etc]. What I'm trying to do is
produce some sort of round robin algorithm for tennis that is
constrained by the number of courts available each week. So if there
are only 3 courts available for a singles league and 10 people have
signed up, 4 players will have a bye each week. I want my algorithm to
produce unique matchups each week and also give each player the same
angle?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can I replace this for loop with a join?

2009-04-13 Thread Kushal Kumaran
On Mon, Apr 13, 2009 at 8:33 PM, WP
 wrote:
> Hello, I have dictionary {1:"astring", 2:"anotherstring", etc}
>
> I now want to print:
> "Press 1 for astring"
> "Press 2 for anotherstring" etc
>
> I could do it like this:
> dict = {1:'astring', 2:'anotherstring'}
> for key in dict.keys():
>    print 'Press %i for %s' % (key, dict[key])
>
> Press 1 for astring
> Press 2 for anotherstring
>
> but can I use a join instead?
>

Sure.  Look up list comprehensions and generator expressions in the docs.

'\n'.join('Press %i for %s' % (key, value) for (key, value) in
d.items()) will get you the entire string.  Whether this is better
than what you have done is a consideration I leave to you.

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


Re: Can I replace this for loop with a join?

2009-04-13 Thread Tim Chase

WP wrote:

Hello, I have dictionary {1:"astring", 2:"anotherstring", etc}

I now want to print:
"Press 1 for astring"
"Press 2 for anotherstring" etc

I could do it like this:
dict = {1:'astring', 2:'anotherstring'}
for key in dict.keys():
 print 'Press %i for %s' % (key, dict[key])

Press 1 for astring
Press 2 for anotherstring


Remember that a dict is inherently unordered, and if you get it 
ordered, you're just lucky :)  Also, it's bad style to mask the 
builtin "dict" with your own.



but can I use a join instead?


If you want to lean on this ordered assumption, you can simply do

  d = {1:"astring", 2:"another string"}
  s = '\n'.join(
"Press %i for %s" % pair
for pair in d.iteritems()
)

and you'd have the resulting value in "s".

But remember that if the order appears broken, you get to keep 
both parts :)  Better to do something like


  s = '\n'.join(
"Press %i for %s" % pair
for pair in sorted(d.items())
)

-tkc








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


Re: Can I replace this for loop with a join?

2009-04-13 Thread Nicolas Dandrimont
* WP  [2009-04-13 17:03:17 +0200]:

> Hello, I have dictionary {1:"astring", 2:"anotherstring", etc}
>
> I now want to print:
> "Press 1 for astring"
> "Press 2 for anotherstring" etc
>
> I could do it like this:
> dict = {1:'astring', 2:'anotherstring'}
> for key in dict.keys():
> print 'Press %i for %s' % (key, dict[key])
>
> Press 1 for astring
> Press 2 for anotherstring
>
> but can I use a join instead?
>
> Thanks for any replies!

First off, you shouldn't use 'dict' as a variable name, as it shadows
the built-in 'dict'.

If you really want to obfuscate this, you could use:

my_dict = {1: 'astring', 2: 'anotherstring'}
print "\n".join('Press %i for %s' % (key, value) for key, value in 
my_dict.items())

I find this highly ugly and non readable, though.

HTH,
-- 
Nicolas Dandrimont

"sic transit discus mundi"
(From the System Administrator's Guide, by Lars Wirzenius)


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


wxpython question

2009-04-13 Thread isam uraiqat
hello fellow geeks

i am trying to run the demo for wxpython, and once i click on it i get the
sand clock coming up for a second and then that's it, it is not running no
matter what i do. i tried it on another computer and im getting the same
thing! it used to work earlier i dont know what happened. i am using python
2.5 and the corresponding version of wxpython is installed! please help !
thanks
--
http://mail.python.org/mailman/listinfo/python-list


Imports in python are static, any solution?

2009-04-13 Thread Ravi
foo.py :

i = 10

   def fi():
  global i
  i = 99

bar.py :

import foo
from foo import i

print i, foo.i
foo.fi()
print i, foo.i

This is problematic. Well I want i to change with foo.fi() .
--
http://mail.python.org/mailman/listinfo/python-list


RE:wxpython question

2009-04-13 Thread isam uraiqat
I HATE VISTA!!

it just needed to be installed on the site packages library, because it was
installed by default on program files,

hope this might help another poor vista user

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


Re: sharing/swapping items between lists

2009-04-13 Thread Aahz
In article ,
Ross   wrote:
>
>I'm sorry...my example was probably a bad one. A better example of
>output I would like would be something like [[1,2],[3,4],[5,6]] and
>then for the leftovers list [7,8,9,10 etc]. What I'm trying to do is
>produce some sort of round robin algorithm for tennis that is
>constrained by the number of courts available each week. So if there
>are only 3 courts available for a singles league and 10 people have
>signed up, 4 players will have a bye each week. I want my algorithm to
>produce unique matchups each week and also give each player the same
>angle?

How about Googling for "round robin algorithm python"?  ;-)
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Why is this newsgroup different from all other newsgroups?
--
http://mail.python.org/mailman/listinfo/python-list


Re: possible pairings in a set

2009-04-13 Thread Przemyslaw Kaminski
Ross wrote:

> I'm new to python and I'm trying to come up with a function that takes
> a given number of players in a game and returns all possible unique
> pairings. Here's the code I've come up with so far, but I'm not
> getting the output I'd like to:
> 
> def all_pairings(players):
> cleanlist = []
> for i in range(players):
> cleanlist.append(i)
> return cleanlist
> start = 0
> follow = start +1
> finallist = []
> while follow <= len(cleanlist)-1:
> for player in cleanlist:
> mini = cleanlist[start],cleanlist[follow]
> finallist.append(mini)
> follow +=1
> start+=1
> return finallist
> 
> If I were to execute the function with all_pairings(4), I want to get
> the output [[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]. Instead, I get
> [0,1,2,3] with the code I currently have. Can you guys help me out?
> Also, if my code is considered ugly or redundant by this community,
> can you make suggestions to clean it up?

Try this:
http://www.mini.pw.edu.pl/~pkamins/arch/comb.tar.bz2


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


Re: Imports in python are static, any solution?

2009-04-13 Thread Luis Alberto Zarrabeitia Gomez

Quoting Ravi :

> 
> This is problematic. Well I want i to change with foo.fi() .

You can't. i and foo.i are _different_ variables that just happen to share the
same value initially. What you are observing is no different than

i = 10
j = i
i = 99

print i  # prints 99
print j  # print 10

May I ask, why is it problematic? You should be avoiding the use of global
variables anyway.

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie

-- 
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba 
http://www.universidad2010.cu

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


Re: Imports in python are static, any solution?

2009-04-13 Thread David Stanek
On Mon, Apr 13, 2009 at 11:59 AM, Ravi  wrote:
> foo.py :
>
>    i = 10
>
>   def fi():
>      global i
>      i = 99
>
> bar.py :
>
>    import foo
>    from foo import i
>
>    print i, foo.i
>    foo.fi()
>    print i, foo.i
>
> This is problematic. Well I want i to change with foo.fi() .

Why not only import foo and using foo.i? In fi() when you set i = 99
you are creating a new object called i in foo's namespace.


-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek
--
http://mail.python.org/mailman/listinfo/python-list


RE: Imports in python are static, any solution?

2009-04-13 Thread AJ Mayorga
For something like this I generally create a superclass to hold
configuration variables that will change overtime, doing that will save you
from insanity.

Class configVar:

#set initial values
Def __init__(self):
Self.A = 5
Self.B = 10
Self.C = 20


Class myMath(configVars):
def __init__(self):
pass

def SubAandB(self):
return self.A - self.B

def AddCandB(self):
return self.C + self.B

def MultiplyXbyA(self, x):
return self.A * x


m = myMath()
X = m.SubAandB()
Y = m.AddCandB()
Z = m.MultiplyXbyA(32)

Keeps your vars in a safer easier to handle, debug, and change kinda way
Good luck

AJ

-Original Message-
From: python-list-bounces+aj=xernova@python.org
[mailto:python-list-bounces+aj=xernova@python.org] On Behalf Of David
Stanek
Sent: Monday, April 13, 2009 12:12 PM
To: Ravi
Cc: python-list@python.org
Subject: Re: Imports in python are static, any solution?

On Mon, Apr 13, 2009 at 11:59 AM, Ravi  wrote:
> foo.py :
>
>    i = 10
>
>   def fi():
>      global i
>      i = 99
>
> bar.py :
>
>    import foo
>    from foo import i
>
>    print i, foo.i
>    foo.fi()
>    print i, foo.i
>
> This is problematic. Well I want i to change with foo.fi() .

Why not only import foo and using foo.i? In fi() when you set i = 99
you are creating a new object called i in foo's namespace.


-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek
--
http://mail.python.org/mailman/listinfo/python-list

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


tkFileDialog -> ImportError: No module named shell

2009-04-13 Thread Alan G Isaac

Why do I get the ImportError below?
What is the right way to do this?
Thanks,
Alan Isaac



Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import Tkinter as tk
>>> root=tk.Tk()
>>> import tkFileDialog
>>> fh = tkFileDialog.asksaveasfile()
Traceback (most recent call last):
  File "boot_com_servers.py", line 44, in 
  File "tbzr.pyo", line 125, in 
  File "tbzr.pyo", line 60, in get_all_com_classes
  File "contextmenu.pyo", line 9, in 
ImportError: No module named shell
Redirecting output to win32trace remote collector
--
http://mail.python.org/mailman/listinfo/python-list


sending and receiving ipv6 multicasts

2009-04-13 Thread Kai Timmer
I am trying to send and receive packages via an ipv6 multicast. But I
can't get it working. What I thought was, that on the listener site, I
just need to bind my socket to the interfaces ipv6 local link address
and on the sender site, to the multicast address (in my case ff02::).
That doesn't work :)

I am using this: http://code.activestate.com/recipes/442490/ as an
example code, but I do not understand to which ipv6 address the socket
must be bind, to get this working on my link local network.

To make clear what I want to do: Every node in my ff80:: network
should receive a UDP package and answer with something. The sending
node then receives all the answers and puts them in some kind of data
structure. Can't be to hard to do this, but I am just lost in ipv6 ;)

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


Who is your daddy: Can I find what object instantiates another object?

2009-04-13 Thread hubritic
I want to build a parser object that handles two different log file
formats.  I have an object that handles Connection logs and an object
for Filter logs.  Each will instantiate a Parser object, passing in
the path to individual log files.

There are a number of ways I could figure out whether I am dealing
with connection or filter log.

I could pass it in when creating the Parser, but that doesn't seem
very pythonic.

I could figure out the type of log file a particular instance of the
Parser is working with by looking at the format of the file. This
wouldn't be hard but it seems unnecessary.

It would be jiffy if I could find what kind of object instantiated
that particular parser. So if a FilterLog object instantiated it, the
parser would know to parse a Filter log.

Can the Parser object know who its Daddy is?

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


Re: Who is your daddy: Can I find what object instantiates another object?

2009-04-13 Thread Jean-Paul Calderone

On Mon, 13 Apr 2009 09:53:04 -0700 (PDT), hubritic  
wrote:

I want to build a parser object that handles two different log file
formats.  I have an object that handles Connection logs and an object
for Filter logs.  Each will instantiate a Parser object, passing in
the path to individual log files.


If you have two different things to do, perhaps you should consider providing
two different APIs to do them.



There are a number of ways I could figure out whether I am dealing
with connection or filter log.

I could pass it in when creating the Parser, but that doesn't seem
very pythonic.


Guessing isn't very Pythonic.



I could figure out the type of log file a particular instance of the
Parser is working with by looking at the format of the file. This
wouldn't be hard but it seems unnecessary.

It would be jiffy if I could find what kind of object instantiated
that particular parser. So if a FilterLog object instantiated it, the
parser would know to parse a Filter log.


Make a FilterLogParser and a ConnectionLogParser, or make a Parser which
takes a parameter that tells it if it is parsing filter logs or
connection logs.



Can the Parser object know who its Daddy is?



Inspecting the call stack or the execution context to decide what to do is
a really awful idea.  It's complicated to implement, complicated to maintain,
complicated to read, and there's no reason to do it.  Just do the simple
thing - add a parameter or make two separate APIs.

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


Re: Who is your daddy: Can I find what object instantiates another object?

2009-04-13 Thread Diez B. Roggisch

hubritic schrieb:

I want to build a parser object that handles two different log file
formats.  I have an object that handles Connection logs and an object
for Filter logs.  Each will instantiate a Parser object, passing in
the path to individual log files.

There are a number of ways I could figure out whether I am dealing
with connection or filter log.

I could pass it in when creating the Parser, but that doesn't seem
very pythonic.


What makes you believe that?


I could figure out the type of log file a particular instance of the
Parser is working with by looking at the format of the file. This
wouldn't be hard but it seems unnecessary.

It would be jiffy if I could find what kind of object instantiated
that particular parser. So if a FilterLog object instantiated it, the
parser would know to parse a Filter log.

Can the Parser object know who its Daddy is?


Yes, by Daddy telling him so. That's how nature does it, and how you 
should do it. Or do you think that because DNA-tests are available to us 
we should just put all kids into a big pool and make them find out who 
their parents are themselves, once they grew up?


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


Re: numpy permutations with replacement

2009-04-13 Thread Mensanator
On Apr 13, 6:36 am, "skorpi...@gmail.com"  wrote:
> On Apr 13, 7:13 am, Chris Rebert  wrote:
>
>
>
>
>
> > On Mon, Apr 13, 2009 at 4:05 AM, skorpi...@gmail.com
>
> >  wrote:
> > > I am trying to generate all possible permutations of length three from
> > > elements of [0,1]. i.e in this scenario there are a total of 8
> > > distinct permutations:
>
> > > [0,0,0]
> > > [0,0,1]
> > > [0,1,0]
> > >    .
> > >    .
> > >    .
> > > [1,1,1]
>
> > > Does numpy define a function to achieve this ?
>
> > No idea, but the Python standard library already has this covered with
> > itertools.permutations()
> > [http://docs.python.org/library/itertools.html].
>
> > Cheers,
> > Chris
>
> > --
> > I have a blog:http://blog.rebertia.com
>
> Thanks Chris,
>
> That looks promising, however I am still stuck at python 2.5 (I need
> numpy). And the 2.5 version does not look as nice as the 2.6 itertool.
> So, if there is a numpy method ... please let me know ..

This isn't dependent on numpy or Python version:

>>> e = [0,1]
>>> for i in e:
for j in e:
for k in e:
print [i,j,k]


[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[1, 1, 1]


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


Re: sending and receiving ipv6 multicasts

2009-04-13 Thread Martin v. Löwis
Kai Timmer wrote:
> I am trying to send and receive packages via an ipv6 multicast. But I
> can't get it working. What I thought was, that on the listener site, I
> just need to bind my socket to the interfaces ipv6 local link address
> and on the sender site, to the multicast address (in my case ff02::).
> That doesn't work :)

On the receiving side, you also need to set the IPV6_JOIN_GROUP
socket option - else your kernel doesn't know you are interested in
packets for that address. You need to bind to the multicast port,
and optionally to the multicast address.

On the sending side, you just use sendto, passing the multicast
address as the recipient.

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


Re: Data Model:

2009-04-13 Thread Anthony
On Apr 13, 1:26 am, Peter Otten <__pete...@web.de> wrote:
> Anthony wrote:
> > On Apr 12, 7:46 pm, Aaron Watters  wrote:
> >> On Apr 12, 10:14 pm, Anthony  wrote:
>
> >> > I'm struggling on whether or not to implement GroupItem (below) with
> >> > two separate models, or with one model that has a distinguishing key:
>
> >> > Given:
> >> > class ParentGroup:
> >> > a group of values represented by class GroupItem
>
> >> > class ChildGroup:
> >> > a group of values represented by class GroupItem
> >> > foreign-key to ParentGroup (many Children sum to one Parent)
>
> >> > Option A:
> >> > class GroupItem:
> >> > foreign-key to ParentGroup
> >> > foreign-key to ChildGroup
> >> > GroupItemType in (ParentItem, ChildItem)
> >> > value
> >> > value-type
>
> >> > Option B:
> >> > class ParentGroupItem
> >> > foreign-key to ParentGroup
> >> > value
> >> > value-type
>
> >> > class ChildGroupItem
> >> > foreign-key to ChildGroup
> >> > value
> >> > value-type
>
> >> > What are my considerations when making this decision?
>
> >> > Thanks!
>
> >> It looks to me that the two designs
> >> might be useful for different
> >> purposes.  What are you trying to do?
>
> >> -- Aaron Watters
>
> >> 
>
> whiff.sourceforge.nethttp://aaron.oirt.rutgers.edu/myapp/root/misc/erdTest
>
>
>
>
>
> > The group values represent statistics that I'm tracking, based on
> > activity groups.  Some samples:
>
> > Group: Johnson, Total Units Produced = 10, Total Units Consumed = 5
> > Chris Johnson, Units Produced = 6, Units Consumed = 3
> > Jim Johnson, Units Produced = 4, Units Consumed = 2
>
> > Group: Smith, Total Units Produced = 15, Total Units Consumed = 8
> > Mark Smith, Units Produced = 7, Units Consumed = 5
> > Bob Smith, Units Produced = 8, Units Consumed = 3
>
> > The groups will be responsible for entering their own statistics, so I
> > will have to do some validation at data entry.  The ability to create
> > new statistic types (e.g. Units Broken) for new groups in the future
> > is important.
>
> > What would be the advantages of using option A versus option B?
>
> I may be missing something, but your example looks more like option C:
>
> class Group:
>     name
>
> class Member:
>     group # foreign key to Group
>     name
>
> class Item:
>     member # foreign key to Member
>     type
>     value
>
> You can calculate the totals for members or groups on the fly; the classical
> tool would be a relational database.
>
> Peter

You're absolutely right.  This is also probably why I'm struggling
with my two options, with neither one of them "feeling right."

What got me going down this road is the fact that users will almost
always only have the total level values to work with.  The detail
entries would be almost optional, from their point of view.  This
means that if I were to set it up as option C, then the default data
entry use case would be to set up an "Unregistered" instance of the
child.

Now that you've highlighted that important point though, it seems to
me like the proper course to follow.  It implies a little bit of
redesign on my part, but better now than further down the road.  I
just need to make sure now that there are no exception cases for top
level calculation:

i.e.

Most of the time:

Total Units Consumed = sum of (all Child Units Consumed)


I need to develop a contingency plan for when the top level is not a
straight sum of the child levels.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Who is your daddy: Can I find what object instantiates another object?

2009-04-13 Thread Aahz
In article <74ha3lf10bj9...@mid.uni-berlin.de>,
Diez B. Roggisch  wrote:
>hubritic schrieb:
>> 
>> Can the Parser object know who its Daddy is?
>
>Yes, by Daddy telling him so. That's how nature does it, and how you 
>should do it. Or do you think that because DNA-tests are available to us 
>we should just put all kids into a big pool and make them find out who 
>their parents are themselves, once they grew up?

+1 QOTW
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Why is this newsgroup different from all other newsgroups?
--
http://mail.python.org/mailman/listinfo/python-list


cx_Oracle - DLL load failed

2009-04-13 Thread cwurld
Hi,

I am having some trouble getting cx_Oracle to work. When I try to
import cx_Oracle, I get the following error message:

ImportError: DLL load failed: %1 is not a valid Win32 application.

I am using Python 2.6 on WIndows. Oracle Client 10g.

Any ideas?

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


Re: numpy permutations with replacement

2009-04-13 Thread skorpi...@gmail.com
On Apr 13, 1:17 pm, Mensanator  wrote:
> On Apr 13, 6:36 am, "skorpi...@gmail.com"  wrote:
>
>
>
> > On Apr 13, 7:13 am, Chris Rebert  wrote:
>
> > > On Mon, Apr 13, 2009 at 4:05 AM, skorpi...@gmail.com
>
> > >  wrote:
> > > > I am trying to generate all possible permutations of length three from
> > > > elements of [0,1]. i.e in this scenario there are a total of 8
> > > > distinct permutations:
>
> > > > [0,0,0]
> > > > [0,0,1]
> > > > [0,1,0]
> > > >    .
> > > >    .
> > > >    .
> > > > [1,1,1]
>
> > > > Does numpy define a function to achieve this ?
>
> > > No idea, but the Python standard library already has this covered with
> > > itertools.permutations()
> > > [http://docs.python.org/library/itertools.html].
>
> > > Cheers,
> > > Chris
>
> > > --
> > > I have a blog:http://blog.rebertia.com
>
> > Thanks Chris,
>
> > That looks promising, however I am still stuck at python 2.5 (I need
> > numpy). And the 2.5 version does not look as nice as the 2.6 itertool.
> > So, if there is a numpy method ... please let me know ..
>
> This isn't dependent on numpy or Python version:
>
> >>> e = [0,1]
> >>> for i in e:
>
>         for j in e:
>                 for k in e:
>                         print [i,j,k]
>
> [0, 0, 0]
> [0, 0, 1]
> [0, 1, 0]
> [0, 1, 1]
> [1, 0, 0]
> [1, 0, 1]
> [1, 1, 0]
> [1, 1, 1]

Much appreciated. This is exactly what was needed...
--
http://mail.python.org/mailman/listinfo/python-list


Re: zProblem

2009-04-13 Thread norseman

Gabriel Genellina wrote:
En Fri, 10 Apr 2009 21:14:01 -0300, norseman  
escribió:

norseman wrote:

Gabriel Genellina wrote:
En Fri, 10 Apr 2009 14:50:57 -0300, norseman  
escribió:



...(snip)


I didn't understand what your problem is actually.

 UUHHDid you read the pdf?


Yes (and I guess not many people would do). It wasn't clear *what* you 
were asking until this post.



...(snip)


(are you sure the grammatical issues are relevant at all...?)


...(snip)


Now, if ... summarizes your problem, I think you 
should use the "place" geometry manager, not grid (nor pack).
The Tkinter documentation [1] is rather short but the Tcl docs [2] have 
more info.


[1] http://effbot.org/tkinterbook/place.htm
[2] http://www.tcl.tk/man/tcl8.4/TkCmd/place.htm




Gabriel;

Thanks for the links but I'm having the same problems as before.

In the Tkinter link:
---
pane = Frame(master)
Label(pane, text="Pane Title").pack()
b = Button(pane, width=12, height=12,
   image=launch_icon, command=self.launch)
b.place(relx=1, x=-2, y=2, anchor=NE)
---
1) It will not work as written and wrapped as below.
2) When modified as shown, it works but not as advertised.
 (not even close)
---
import Tkinter
from Tkconstants import *
tk = Tkinter.Tk()

pane = Tkinter.Frame(tk)
pane.pack()
Tkinter.Label(pane, text="Pane Title-123456789x").pack()
b = Tkinter.Button(pane, width=12, height=12)
b.place(relx=1, x=-2, y=2, anchor=NE)
b.pack()

tk.mainloop()
---
Above: The label goes at the top and the big button is centered below. 
Same problem as with 'grid'.

  Not including the Label line:
  comment out both .pack's and you get a blank frame
  comment out 1st  .pack   and you get a blank frame
  comment out 2nd  .pack   and you get what might be the stated
 Part of Pane is visible and button overlaps. Button is not a fixed
 size. Remove '-123456789x' from label to see Button change size.
 And we have to use pack to even see the thing.

However this order:
---
pane = Tkinter.Frame(tk)
pane.pack()
#Tkinter.Label(pane, text="Pane Title-123456789x").pack()
b = Tkinter.Button(pane, width=12, height=12)
b.place(relx=1, x=-2, y=2, anchor=S)
b.pack()
Tkinter.Label(pane, text="Pane Title-123456789x").pack()

tk.mainloop()
---
it outputs Label at bottom and a big button centered above. It is still 
a parcel and first one defined sets the grid size. Period.  Also, the 
Button's width/height only take place if Button is defined before Label 
or .pack is never used on Button. The 2nd (not used) allows Label to set 
the grid dimensions.
I can't visualize that working properly in my current need.  The mockup 
board is to be size inflexible and real estate jammed with specifically 
sized replaceable sections.  The question is how to make it happen.



Back to your question.  Yes - there is a great need for dictionary 
adherence.  Especially when language translations are probable.
Also - The Military, the Engineering/Architectural, Building, Map Making 
 and Graphic Arts and Printing communities have all been 'trained' to 
the concept of grid. Not to mention Pilots and Navagators. The average 
person and the Reality Companies all understand the concept of parcels. 
 Grid points can be used without the need to fill the intervening. Take 
a look at the starts at night. ALL parcels must have one or more parcels 
between them if they are not contiguous. How else can one walk down the 
street?


Honestly, I'm not trying to be antagonistic.  I have enough problems 
reading bad English 'help' things as it is. Outright abuse of words only 
adds bitterness. I had two very strict English grammar teachers and one 
very dedicated literary one. 45 years latter, trying to work outside 
their 'drummed in' reflexes is actually still quite difficult. Who would 
have thought?


Like most people on the planet, if I say make it this by that, I expect 
it to be as stated.  Don't you?


Are there any other GUI's that run Python code unchanged on Linux and 
Windows?



Steve

side note:  Your English is far better than any other language I attempt
--
http://mail.python.org/mailman/listinfo/python-list


Re: zProblem

2009-04-13 Thread norseman

Steven D'Aprano wrote:

On Fri, 10 Apr 2009 10:50:57 -0700, norseman wrote:


Moderator:  I apologize for attaching anything.


This newsgroup has no moderator.




However, in order to explain my problem, I need to control the font
since text graphics only work for a given font.


Use the least common denominator available, so-called "ASCII graphics", 
and put a note that the diagrams are best viewed in a non-proportional 
font like Courier or equivalent. E.g.:


+---+
| Input |
+---+
|  +--+
|--|  Special |
|  +--+
*   ++
*  Box  *---| Output |
*   ++

Even if the lines don't quite line up, it's decipherable.

This is a newsgroup for a programming language. Nearly everyone will be 
using a monospaced font already, or at least nearly all the *serious* 
contributors, so that code blocks will line up correctly.


More importantly, you should describe the nature of your problem in the 
body of the post, as concisely as possible, and use attachments for as 
little content as possible. For many people, it is inconvenient and 
difficult to deal with attachments in their newsreader, and people won't 
bother unless they know the topic is of interest to them.


You should also read this:

http://www.catb.org/~esr/faqs/smart-questions.html




Nice link - Thank you.

A number of my friends set their internet things to use fonts of their 
choice. That includes a few who speak English.  We've learned that the 
pdf solves things nicely.


Appreciate the rest of the tips.


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


Re: tkFileDialog -> ImportError: No module named shell

2009-04-13 Thread Mike Driscoll
On Apr 13, 11:26 am, Alan G Isaac  wrote:
> Why do I get the ImportError below?
> What is the right way to do this?
> Thanks,
> Alan Isaac
>
> Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] 
> on win32
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> import Tkinter as tk
>  >>> root=tk.Tk()
>  >>> import tkFileDialog
>  >>> fh = tkFileDialog.asksaveasfile()
> Traceback (most recent call last):
>    File "boot_com_servers.py", line 44, in 
>    File "tbzr.pyo", line 125, in 
>    File "tbzr.pyo", line 60, in get_all_com_classes
>    File "contextmenu.pyo", line 9, in 
> ImportError: No module named shell
> Redirecting output to win32trace remote collector

Well, if you have tortoisehg installed, uninstall it. That was what
was giving me this exact error with wxPython file dialogs.

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


Re: GUI Programming

2009-04-13 Thread norseman

Gabriel wrote:

r wrote:

On Apr 12, 8:07 am, Gabriel  wrote:
 

Hello,

I'm python newbie and i need to write gui for my school work in python.
I need to write it really quick,


[snip]

Tkinter is built-in, why not start there?

from Tkinter import *
root = Tk()
root.mainloop()





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

  


It seems ugly to me..
--
http://mail.python.org/mailman/listinfo/python-list


===
Put your tongue in your cheek:  You have company! :) :)

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


Re: Python and XML Help

2009-04-13 Thread Scott David Daniels

ookrin wrote:

I'm in the process of learning python and PyQt4. I had decided to make
myself a simple app and soon discovered that I needed to crash into
xml to use some of the data I was going to be getting off of the
server.

I picked up enough xml to use the sax parser to get the data out of
the xml. I can get as far as printing it to the screen, but there is
where I get stuck


Assuming you are using a somewhat current Python (2.5 or later, you
did not specify), the etree package is buit in.  If not, you can
download it for your python easily.  You can then (for example)
use something like:
from xml.etree import cElementTree as ET
...
parsed = ET.parse('CharacterID.xml')
for node in parsed.getiterator('osArchitecture'): print node.text

or if you have the data in a string,
root = ET.fromstring('string')
print root[0].tag, root[0].text

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


REG: python c++ bindings

2009-04-13 Thread ext-golla.anil-ku...@nokia.com
 
Hi 
I need some material or link contain examples on python C++ bindings( calling 
C++ methods in python)
Can any body share the information.

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


Re: ANN: PyGUI 2.0.1

2009-04-13 Thread Andrew MacKeith


Greg Ewing wrote:

PyGUI 2.0.1 is available:

  http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/

Fixes some problems in setup.py affecting installation
on Linux and Windows.


What is PyGUI?
--

PyGUI is a cross-platform GUI toolkit designed to be lightweight
and have a highly Pythonic API.



I installed PyGUI-2.0.1 on Windows (32 bit, non Administrator access).
I got the following error in 2.0.1 when attempting the BlobEdit example:

D:\users\omh\runabq\pyGUI>c:\python26\python
Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> from GUI import Application,  ScrollableView, Document, Window, \
...   FileType, Cursor, rgb
  File "", line 1, in 
  File "c:\python26\Lib\site-packages\GUI\__init__.py", line 78, in __getattr__
traceback.print_stack()
Failed to import 'Application' from Applications
Traceback (most recent call last):
  File "c:\python26\Lib\site-packages\GUI\__init__.py", line 69, in __getattr__
module = __import__(modname, self.__dict__, locals(), [name])
  File "c:\python26\Lib\site-packages\GUI\Win32\Applications.py", line 8, in 

import Components, Windows
  File "c:\python26\Lib\site-packages\GUI\Win32\Components.py", line 12, in 

from Win32 import win_none
  File "c:\python26\lib\site-packages\GUI\Win32\__init__.py", line 2, in 

raise ImportError("This should not be imported.")
ImportError: This should not be imported.

I presume that one should be able to import GUI.Win32 if I need to import 
win_none from it.

If I comment out line 2, I get the following error:
...
  File "c:\python26\Lib\site-packages\GUI\Win32\Components.py", line 12, in 

from Win32 import win_none
ImportError: cannot import name win_none

The directory structure that was installed is as follows:
c:\python26\Lib\site-packages\GUI
c:\python26\Lib\site-packages\GUI\Generic
c:\python26\Lib\site-packages\GUI\Resources
c:\python26\Lib\site-packages\GUI\Resources\cursors
c:\python26\Lib\site-packages\GUI\Win32


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


Re: Detecting -i in a script

2009-04-13 Thread Marek Szuba
On 2009-04-13, Chris Rebert  wrote:

> The sys.flags.interactive bool.
>
> Details: http://docs.python.org/library/sys.html#sys.flags
Hmm, "New in version 2.6"... Are you aware of any way of extracting
this information in older versions of Python? My code needs to be
2.3-compatible.

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


Re: cx_Oracle - DLL load failed

2009-04-13 Thread Martin P. Hellwig

cwurld wrote:

Hi,

I am having some trouble getting cx_Oracle to work. When I try to
import cx_Oracle, I get the following error message:

ImportError: DLL load failed: %1 is not a valid Win32 application.

I am using Python 2.6 on WIndows. Oracle Client 10g.

Any ideas?

Thanks


Hmm some time ago I used cx, but I remember that I sometimes forgot to 
install the oracle client libraries (eventually just packed the needed 
binaries in the same dir as cx). Maybe something along that route?


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


Re: tkFileDialog -> ImportError: No module named shell

2009-04-13 Thread Alan G Isaac
On Apr 13, 11:26 am, Alan G Isaac  
wrote:
Why do I get the ImportError below? 
What is the right way to do this? 
Thanks, 
Alan Isaac 


Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC 
v.1310 32 bit (Intel)] on win32 Type "help", "copyright", 
"credits" or "license" for more information. 
 >>> import Tkinter as tk

 >>> root=tk.Tk()
 >>> import tkFileDialog
 >>> fh = tkFileDialog.asksaveasfile()
Traceback (most recent call last):
   File "boot_com_servers.py", line 44, in 
   File "tbzr.pyo", line 125, in 
   File "tbzr.pyo", line 60, in get_all_com_classes
   File "contextmenu.pyo", line 9, in 
ImportError: No module named shell 
Redirecting output to win32trace remote collector 




On 4/13/2009 2:28 PM Mike Driscoll apparently wrote:
Well, if you have tortoisehg installed, uninstall it. That was what 
was giving me this exact error with wxPython file dialogs. 




No, I don't have tortoisehg.
But, I do have Bazaar installed,
and that is the only place I see contextmenu.pyo.

And that appears to be the source of the problem:
https://bugs.launchpad.net/bzr/+bug/305085

Can you help me understand how
another application can interfere with Tkinter
in such a fashion?

Thank you!
Alan Isaac

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


Re: Detecting -i in a script

2009-04-13 Thread Chris Rebert
On Mon, Apr 13, 2009 at 12:09 PM, Marek Szuba  wrote:
> Hello there,
>
> Is there any way of detecting in a script whether the interpreter
> session running it has been launched with the -i option? My Google fu
> has failed me on this subject... Thanks in advance.

The sys.flags.interactive bool.

Details: http://docs.python.org/library/sys.html#sys.flags

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: REG: python c++ bindings

2009-04-13 Thread Diez B. Roggisch

ext-golla.anil-ku...@nokia.com schrieb:
 
Hi 



Please don't reply to existing posts. People read news and mails 
threaded, and this makes a post appear below other, non-related posts & 
causes confusion.


Create a new thread instead, by directly posting to the group or ML.


I need some material or link contain examples on python C++ bindings( calling 
C++ methods in python)
Can any body share the information.



Take a look at SIP.

http://www.riverbankcomputing.com/Docs/sip4/sipref.html#mappedtype

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


Re: tkFileDialog -> ImportError: No module named shell

2009-04-13 Thread Mike Driscoll
On Apr 13, 2:29 pm, Alan G Isaac  wrote:
> > On Apr 13, 11:26 am, Alan G Isaac 
> > wrote:
> >> Why do I get the ImportError below?
> >> What is the right way to do this?
> >> Thanks,
> >> Alan Isaac
> >> Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC
> >> v.1310 32 bit (Intel)] on win32 Type "help", "copyright",
> >> "credits" or "license" for more information.
> >>  >>> import Tkinter as tk
> >>  >>> root=tk.Tk()
> >>  >>> import tkFileDialog
> >>  >>> fh = tkFileDialog.asksaveasfile()
> >> Traceback (most recent call last):
> >>    File "boot_com_servers.py", line 44, in 
> >>    File "tbzr.pyo", line 125, in 
> >>    File "tbzr.pyo", line 60, in get_all_com_classes
> >>    File "contextmenu.pyo", line 9, in 
> >> ImportError: No module named shell
> >> Redirecting output to win32trace remote collector
>
> On 4/13/2009 2:28 PM Mike Driscoll apparently wrote:
>
> > Well, if you have tortoisehg installed, uninstall it. That was what
> > was giving me this exact error with wxPython file dialogs.
>
> No, I don't have tortoisehg.
> But, I do have Bazaar installed,
> and that is the only place I see contextmenu.pyo.
>
> And that appears to be the source of the 
> problem:https://bugs.launchpad.net/bzr/+bug/305085
>
> Can you help me understand how
> another application can interfere with Tkinter
> in such a fashion?
>
> Thank you!
> Alan Isaac

Here's my (probably flawed) understanding of what tortoisehg does:
According to their bug report, there's a dll mismatch that causes the
issue (see 
http://bitbucket.org/tortoisehg/stable/issue/67/thg-conflicts-with-other-python).

I haven't had any issues with IDLE and bzr as of yet, and it
definitely hasn't given my Wingware IDE any issues either. I wonder if
you need to just upgrade to the latest bzr to see if that fixes the
issue. I have a pretty old one (1.8)...then again, I'm using wxPython,
not Tkinter.

Anyway, somehow these DVCSes are messing with the shell itself, which
is what a file dialog tries to open too. When the file dialog goes to
open it, it executes some code automagically in the DVCS and then
crashes.

Hopefully someone else with more knowledge will step in and give us a
clue.

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


Detecting -i in a script

2009-04-13 Thread Marek Szuba
Hello there,

Is there any way of detecting in a script whether the interpreter
session running it has been launched with the -i option? My Google fu
has failed me on this subject... Thanks in advance.

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


Re: binary file compare...

2009-04-13 Thread Przemyslaw Kaminski
SpreadTooThin wrote:

> I want to compare two binary files and see if they are the same.
> I see the filecmp.cmp function but I don't get a warm fuzzy feeling
> that it is doing a byte by byte comparison of two files to see if they
> are they same.
> 
> What should I be using if not filecmp.cmp?

Well, here's something
http://www.daniweb.com/forums/thread115959.html
but it seems from the post on the bottom that filecmp does comparison of 
binary files.

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


Re: binary file compare...

2009-04-13 Thread SpreadTooThin
On Apr 13, 2:00 pm, Przemyslaw Kaminski  wrote:
> SpreadTooThin wrote:
> > I want to compare two binary files and see if they are the same.
> > I see the filecmp.cmp function but I don't get a warm fuzzy feeling
> > that it is doing a byte by byte comparison of two files to see if they
> > are they same.
>
> > What should I be using if not filecmp.cmp?
>
> Well, here's somethinghttp://www.daniweb.com/forums/thread115959.html
> but it seems from the post on the bottom that filecmp does comparison of
> binary files.

I just want to be clear, the comparison is not just based on file size
and creation date but by a byte by byte comparison of the data in each
file.
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary file compare...

2009-04-13 Thread Grant Edwards
On 2009-04-13, SpreadTooThin  wrote:

> I want to compare two binary files and see if they are the same.
> I see the filecmp.cmp function but I don't get a warm fuzzy feeling
> that it is doing a byte by byte comparison of two files to see if they
> are they same.

Perhaps I'm being dim, but how else are you going to decide if
two files are the same unless you compare the bytes in the
files?

You could hash them and compare the hashes, but that's a lot
more work than just comparing the two byte streams.

> What should I be using if not filecmp.cmp?

I don't understand what you've got against comparing the files
when you stated that what you wanted to do was compare the files.

-- 
Grant Edwards   grante Yow! Look DEEP into the
  at   OPENINGS!!  Do you see any
   visi.comELVES or EDSELS ... or a
   HIGHBALL?? ...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Overflow error (was Vol 67, Issue 192)

2009-04-13 Thread Scott David Daniels

Dave Angel wrote:

Ryniek90 wrote:
 But i've still haven't got answer for question: 
"What's the max. length of string bytes which Python can hold?"


sys.maxsize
The largest positive integer supported by the platform’s
Py_ssize_t type, and thus the maximum size lists, strings, dicts, and
many other containers can have.

>>
Thanks. I've wanted to check very carefully what's up, and i found 
this: "strings (currently restricted to 2GiB)".
It's here, in PEP #353 (PEP 0353 
). Besides of this, i've 
found in sys module's docstring this:


maxint = 2147483647
maxunicode = 1114111

Which when added gives us 2148597758.0 bytes, which are equal to 
2049.0624980926514 MiB's.


This arithmetic makes very little sense.  You are adding the maximum
value for a unicode code point and the maximum integer represented in
the underlying C compiler's int.  Were you to do some kind of arithmetic
on those two numbers, I'd do:
sys.maxint / math.ceil(log(sys.maxunicode, 256))
That is "supposed to be" the number of unicode characters in a
maximal-length sequence of bytes.  However, it doesn't even manage
that, as (I believe) even for those Pythons with 32-bit unicode
characters, sys.maxunicode is currently 0x10 (the largest
code point defined by the UNicode consortium).

How much RAM is in your system? Unless it's at least 50 gb, in a 64bit 
OS, I'd keep my max chunk size to much smaller than 2gb. For a typical 
32bit system with 2 to 4gb of RAM, I'd probably chunk the file a meg or 
so at a time. Using large sizes is almost always a huge waste of resources.


Agreed.  I you must do arithmetic to determine the chunk length, you
using the magic constant for practically everything, "42", can give you
the chunk size to use:
ord("4") * ord("2") * int("42") == 109200

:-)

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


Re: binary file compare...

2009-04-13 Thread SpreadTooThin
On Apr 13, 2:03 pm, Grant Edwards  wrote:
> On 2009-04-13, SpreadTooThin  wrote:
>
> > I want to compare two binary files and see if they are the same.
> > I see the filecmp.cmp function but I don't get a warm fuzzy feeling
> > that it is doing a byte by byte comparison of two files to see if they
> > are they same.
>
> Perhaps I'm being dim, but how else are you going to decide if
> two files are the same unless you compare the bytes in the
> files?
>
> You could hash them and compare the hashes, but that's a lot
> more work than just comparing the two byte streams.
>
> > What should I be using if not filecmp.cmp?
>
> I don't understand what you've got against comparing the files
> when you stated that what you wanted to do was compare the files.
>

I think its just the way the documentation was worded
http://www.python.org/doc/2.5.2/lib/module-filecmp.html

Unless shallow is given and is false, files with identical os.stat()
signatures are taken to be equal.
Files that were compared using this function will not be compared
again unless their os.stat() signature changes.

So to do a comparison:
filecmp.cmp(filea, fileb, False)
?




> --
> Grant Edwards                   grante             Yow! Look DEEP into the
>                                   at               OPENINGS!!  Do you see any
>                                visi.com            ELVES or EDSELS ... or a
>                                                    HIGHBALL?? ...

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


Re: Imports in python are static, any solution?

2009-04-13 Thread norseman

AJ Mayorga wrote:

For something like this I generally create a superclass to hold
configuration variables that will change overtime, doing that will save you
from insanity.

Class configVar:

#set initial values
Def __init__(self):
Self.A = 5
Self.B = 10
Self.C = 20


Class myMath(configVars):
def __init__(self):
pass

def SubAandB(self):
return self.A - self.B

def AddCandB(self):
return self.C + self.B

def MultiplyXbyA(self, x):
return self.A * x


m = myMath()
X = m.SubAandB()
Y = m.AddCandB()
Z = m.MultiplyXbyA(32)

Keeps your vars in a safer easier to handle, debug, and change kinda way
Good luck

AJ

-Original Message-
From: python-list-bounces+aj=xernova@python.org
[mailto:python-list-bounces+aj=xernova@python.org] On Behalf Of David
Stanek
Sent: Monday, April 13, 2009 12:12 PM
To: Ravi
Cc: python-list@python.org
Subject: Re: Imports in python are static, any solution?

On Mon, Apr 13, 2009 at 11:59 AM, Ravi  wrote:

foo.py :

   i = 10

  def fi():
 global i
 i = 99

bar.py :

   import foo
   from foo import i

   print i, foo.i
   foo.fi()
   print i, foo.i

This is problematic. Well I want i to change with foo.fi() .


Why not only import foo and using foo.i? In fi() when you set i = 99
you are creating a new object called i in foo's namespace.



===

Aj is right. In foo.py there are two definitions for 'i'. The initial 
and the replacement initiated by fi(). While initially there is no 'i' 
definition in bar itself.


To test, use my changes to bar.py

import foo
#from foo import i

i= foo.i
print i, foo.i
x= foo.fi()
print i, x, foo.i
x= foo.i
print  i, x, foo.i

the output will be:
10 10
10 None 99
10 99 99

output is same if you uncomment #from... and comment i=...
The '...import i' creates the "same" var as the i=... in the current run
If you comment out both the from and the i= then the print i will fail 
because i has not been defined in current space.

foo.fi() returns None (nothing) per it's definition.
whereas the first foo.i returns the initial i value and the foo.i after 
foo.fi() returns the 2nd value, foo's i reset to 99 by fi() inside foo.


Clear as Mud???


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


Re: GUI Programming

2009-04-13 Thread Lawson English

Gabriel wrote:

Hello,

I'm python newbie and i need to write gui for my school work in python.
I need to write it really quick, because i haven't much time .)
So question is, which of gui toolkits should i pick and learn? I heard 
PyGTK and Glade are best for quick gui programming? Is it good for 
beginner? Or is there something better?

I have some experience with java swing, btw..
--
http://mail.python.org/mailman/listinfo/python-list

I've been using wxpython for a while. They're all good, depending on 
what you need/want/etc.


I think wxpython has one of the most mature sets of optional widgets 
since its x-platform AND

x-language, but I may be mistaken.

take a look at the wx demo app and see if you find the right widgets 
already documented/implemented.



http://www.wxpython.com ...the demo app is part of the distribution IIRC.


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


PIL, and Parts of tuples

2009-04-13 Thread Vistro
I have two problems, and I can't find anything about either of them.
The first is that PIL does not seem to have any way to search each and every
pixel for a value, like

for pixel in img:
if pixel = ((60, 30), (58, 23), (87 57)):
# Get out of the for loop
# Also, save the pixel quardinates to a variable


Then, I also want it to look at a specific pixel (I've got that down), and
do something if the any one of the values in the tuple is out of range.

The issue is, the range is different for every value. Basically, it is to
see if the pixel is in an acceptable color range. So, say, the 60 above can
be anywhere from 58-62, but the 30 needs to be between 28-40.

Is there any way to parse/deal with a value at a specific "slot" in a tuple?
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary file compare...

2009-04-13 Thread Grant Edwards
On 2009-04-13, Grant Edwards  wrote:
> On 2009-04-13, SpreadTooThin  wrote:
>
>> I want to compare two binary files and see if they are the same.
>> I see the filecmp.cmp function but I don't get a warm fuzzy feeling
>> that it is doing a byte by byte comparison of two files to see if they
>> are they same.
>
> Perhaps I'm being dim, but how else are you going to decide if
> two files are the same unless you compare the bytes in the
> files?
>
> You could hash them and compare the hashes, but that's a lot
> more work than just comparing the two byte streams.
>
>> What should I be using if not filecmp.cmp?
>
> I don't understand what you've got against comparing the files
> when you stated that what you wanted to do was compare the files.

Doh!  I misread your post and thought were weren't getting a
warm fuzzying feeling _because_ it was doing a byte-byte
compare. Now I'm a bit confused.  Are you under the impression
it's _not_ doing a byte-byte compare?  Here's the code:

def _do_cmp(f1, f2):
bufsize = BUFSIZE
fp1 = open(f1, 'rb')
fp2 = open(f2, 'rb')
while True:
b1 = fp1.read(bufsize)
b2 = fp2.read(bufsize)
if b1 != b2:
return False
if not b1:
return True

It looks like a byte-by-byte comparison to me.  Note that when
this function is called the file lengths have already been
compared and found to be equal.

-- 
Grant Edwards   grante Yow! Alright, you!!
  at   Imitate a WOUNDED SEAL
   visi.compleading for a PARKING
   SPACE!!
--
http://mail.python.org/mailman/listinfo/python-list


Re: PIL, and Parts of tuples

2009-04-13 Thread Chris Rebert
On Mon, Apr 13, 2009 at 1:34 PM, Vistro  wrote:
> I have two problems, and I can't find anything about either of them.
> The first is that PIL does not seem to have any way to search each and every
> pixel for a value, like
> for pixel in img:
>     if pixel = ((60, 30), (58, 23), (87 57)):

> see if the pixel is in an acceptable color range. So, say, the 60 above can
> be anywhere from 58-62, but the 30 needs to be between 28-40.
> Is there any way to parse/deal with a value at a specific "slot" in a tuple?

Yes, use subscripting, just like with lists:

the_tuple = (60, 30)#for example

if not (58 <= the_tuple[0] <= 62) or not (28 <= the_tuple[1] <= 40):
#it's out of range, do something

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


Re: PIL, and Parts of tuples

2009-04-13 Thread Vistro
Actually, I screwed up.
See 60, 30? That's actually the range. The tuple to be checked will look
like

(40, 25, 51)

So yeah. Sorry for the bad info.

For a good time, go to Start:Run and type in format C

On Mon, Apr 13, 2009 at 3:41 PM, Chris Rebert  wrote:

> On Mon, Apr 13, 2009 at 1:34 PM, Vistro  wrote:
> > I have two problems, and I can't find anything about either of them.
> > The first is that PIL does not seem to have any way to search each and
> every
> > pixel for a value, like
> > for pixel in img:
> > if pixel = ((60, 30), (58, 23), (87 57)):
> 
> > see if the pixel is in an acceptable color range. So, say, the 60 above
> can
> > be anywhere from 58-62, but the 30 needs to be between 28-40.
> > Is there any way to parse/deal with a value at a specific "slot" in a
> tuple?
>
> Yes, use subscripting, just like with lists:
>
> the_tuple = (60, 30)#for example
>
> if not (58 <= the_tuple[0] <= 62) or not (28 <= the_tuple[1] <= 40):
>#it's out of range, do something
>
> Cheers,
> Chris
> --
> I have a blog:
> http://blog.rebertia.com
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary file compare...

2009-04-13 Thread SpreadTooThin
On Apr 13, 2:37 pm, Grant Edwards  wrote:
> On 2009-04-13, Grant Edwards  wrote:
>
>
>
> > On 2009-04-13, SpreadTooThin  wrote:
>
> >> I want to compare two binary files and see if they are the same.
> >> I see the filecmp.cmp function but I don't get a warm fuzzy feeling
> >> that it is doing a byte by byte comparison of two files to see if they
> >> are they same.
>
> > Perhaps I'm being dim, but how else are you going to decide if
> > two files are the same unless you compare the bytes in the
> > files?
>
> > You could hash them and compare the hashes, but that's a lot
> > more work than just comparing the two byte streams.
>
> >> What should I be using if not filecmp.cmp?
>
> > I don't understand what you've got against comparing the files
> > when you stated that what you wanted to do was compare the files.
>
> Doh!  I misread your post and thought were weren't getting a
> warm fuzzying feeling _because_ it was doing a byte-byte
> compare. Now I'm a bit confused.  Are you under the impression
> it's _not_ doing a byte-byte compare?  Here's the code:
>
> def _do_cmp(f1, f2):
>     bufsize = BUFSIZE
>     fp1 = open(f1, 'rb')
>     fp2 = open(f2, 'rb')
>     while True:
>         b1 = fp1.read(bufsize)
>         b2 = fp2.read(bufsize)
>         if b1 != b2:
>             return False
>         if not b1:
>             return True
>
> It looks like a byte-by-byte comparison to me.  Note that when
> this function is called the file lengths have already been
> compared and found to be equal.
>
> --
> Grant Edwards                   grante             Yow! Alright, you!!
>                                   at               Imitate a WOUNDED SEAL
>                                visi.com            pleading for a PARKING
>                                                    SPACE!!

I am indeed under the impression that it is not always doing a byte by
byte comparison...
as well the documentation states:
Compare the files named f1 and f2, returning True if they seem equal,
False otherwise.

That word... Sem... makes me wonder.

Thanks for the code! :)

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


How to run jython WSGI applications on Google AppEngine.

2009-04-13 Thread Alan Kennedy
Hi all,

You can find instructions about how to run jython Web applications on
Google AppEngine,
using WSGI and modjy, here.

http://jython.xhaus.com

You can see the jython 2.5 Demo WSGI application running, here.

http://jywsgi.appspot.com

Regards,

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


Re: binary file compare...

2009-04-13 Thread Peter Otten
Grant Edwards wrote:

> On 2009-04-13, Grant Edwards  wrote:
>> On 2009-04-13, SpreadTooThin  wrote:
>>
>>> I want to compare two binary files and see if they are the same.
>>> I see the filecmp.cmp function but I don't get a warm fuzzy feeling
>>> that it is doing a byte by byte comparison of two files to see if they
>>> are they same.
>>
>> Perhaps I'm being dim, but how else are you going to decide if
>> two files are the same unless you compare the bytes in the
>> files?
>>
>> You could hash them and compare the hashes, but that's a lot
>> more work than just comparing the two byte streams.
>>
>>> What should I be using if not filecmp.cmp?
>>
>> I don't understand what you've got against comparing the files
>> when you stated that what you wanted to do was compare the files.
> 
> Doh!  I misread your post and thought were weren't getting a
> warm fuzzying feeling _because_ it was doing a byte-byte
> compare. Now I'm a bit confused.  Are you under the impression
> it's _not_ doing a byte-byte compare?  Here's the code:
> 
> def _do_cmp(f1, f2):
> bufsize = BUFSIZE
> fp1 = open(f1, 'rb')
> fp2 = open(f2, 'rb')
> while True:
> b1 = fp1.read(bufsize)
> b2 = fp2.read(bufsize)
> if b1 != b2:
> return False
> if not b1:
> return True
> 
> It looks like a byte-by-byte comparison to me.  Note that when
> this function is called the file lengths have already been
> compared and found to be equal.

But there's a cache. A change of file contents may go undetected as long as
the file stats don't change:

 $ cat fool_filecmp.py
import filecmp, shutil, sys

for fn in "adb":
with open(fn, "w") as f:
f.write("yadda")

shutil.copystat("d", "a")
filecmp.cmp("a", "b", False)

with open("a", "w") as f:
f.write("*")
shutil.copystat("d", "a")

if "--clear" in sys.argv:
print "clearing cache"
filecmp._cache.clear()

if filecmp.cmp("a", "b", False):
print "file a and b are equal"
else:
print "file a and b differ"
print "a's contents:", open("a").read()
print "b's contents:", open("b").read()

$ python2.6 fool_filecmp.py
file a and b are equal
a's contents: *
b's contents: yadda

Oops. If you are paranoid you have to clear the cache before doing the
comparison:

$ python2.6 fool_filecmp.py --clear
clearing cache
file a and b differ
a's contents: *
b's contents: yadda

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


How to convert \n and \t symbols to new lines and tabs?

2009-04-13 Thread DSblizzard
How to convert string with \n and \t symbols to natural string - with
new lines and tabs?
--
http://mail.python.org/mailman/listinfo/python-list


Re: ValueError: I/O operation on closed file

2009-04-13 Thread dj
On Apr 11, 12:30 am, Dennis Lee Bieber  wrote:
> On Fri, 10 Apr 2009 13:25:25 -0700 (PDT), dj 
> declaimed the following in gmane.comp.python.general:
>
>
>
> > I have a handler which I use with a set of log levels for the python
> > logging module.
>
> > --- myhandler.py
> > 
> > import logging.handlers
>
> > # create my handler class
> > class MyHandler(logging.handlers.RotatingFileHandler):
> >     def __init__(self, fn):
> >         logging.handlers.RotatingFileHandler.__init__(self, fn,
>
> > maxBytes=10485760, backupCount=5)
>
> > # Register handler in the "logging.handlers" namespace
> > logging.handlers.MyHandler = MyHandler
>
>         Don't you need to pass an INSTANCE of the handler? Or SOMEWHERE
> create an instance for use. Note that the filename is one of the
> arguments needed to initialize this, and since we see no code with a
> root file name ... ???
>
>         No addHandler() anywhere?
>
> > 
>
> > Using it, repeatedly generates this error:
>
> > Traceback (most recent call last):
> >   File "C:\python26\lib\logging\handlers.py", line 74, in emit
> >     if self.shouldRollover(record):
> >   File "C:\python26\lib\logging\handlers.py", line 146, in
> > shouldRollover
> >     self.stream.seek(0, 2)  #due to non-posix-compliant Windows
> > feature
> > ValueError: I/O operation on closed file
>
>         That's a rather short traceback -- where are the calls to the logger
> that would trigger the emit() call? Where do you specify that this
> handler is suppose to be used
> --
>         Wulfraed        Dennis Lee Bieber               KD6MOG
>         wlfr...@ix.netcom.com             wulfr...@bestiaria.com
>                 HTTP://wlfraed.home.netcom.com/
>         (Bestiaria Support Staff:               web-a...@bestiaria.com)
>                 HTTP://www.bestiaria.com/

Hello again,

I thought I included the specifics of my custom logger, but I did not
do that.
Please allow me to present this issue again with the complete
details.

--- myhandler.py ---
import logging.handlers

# create my handler class
class MyHandler(logging.handlers.RotatingFileHandler):
def __init__(self, fn):
logging.handlers.RotatingFileHandler.__init__(self, fn,

maxBytes=10485760, backupCount=5)

# Register handler in the "logging.handlers" namespace
logging.handlers.MyHandler = MyHandler

--- myLogs.py -
import logging
import logging.handlers
from myhandler import MyHandler  #custom handler
import os

# EXCLUDED THE DETAILS FOR THE CUSTOMIZED LOGGER


#log file formatter
format = logging.Formatter("%(asctime)s %(levelname)s %(filename)s %
(lineno)d %(message)s")

# setup the logger instance
log = logging.getLogger("app_log")
# set the log level
log.setLevel(logging.DEBUG)
# add a method for the custom log level to the logger
setattr(log, 'userinfo', lambda *args: log.log(USERINFO, *args))

# create the handler for app.log
app_handler = logging.handlers.MyHandler(APP_LOG_FILENAME)#using
myhandler
# set handler level
app_handler.setLevel(logging.DEBUG)
# add the formatter to the handler
app_handler.setFormatter(format)


# create the handler for notice.log
notice_handler =  logging.handlers.MyHandler(NOTICE_LOG_FILENAME)  #
using my handler
# set handler level
notice_handler.setLevel(logging.ERROR)
# add the formatter to the handler
notice_handler.setFormatter(format)


# setup the logger for user.log
userLog = logging.getLogger("user_log")
# set the level
userLog.setLevel(logging.INFO)
# add a method for the custom log level to the logger
setattr(userLog, 'userinfo', lambda *args: userLog.log(USERINFO,
*args))

# create the  handler for user.log
user_handler =  logging.handlers.MyHandler(USER_LOG_FILENAME)  # using
myhandler
# handler level
user_handler.setLevel(logging.INFO)
# add the formatter to the handler
user_handler.setFormatter(format)

# add the handlers to log
log.addHandler(app_handler)
log.addHandler(notice_handler)

# add the handler to userLog
userLog.addHandler(user_handler)

- app.py ---

import logging
import myLogs


myLogs.log.debug('this is debug message')



###

I hope this provides much better clarification.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert \n and \t symbols to new lines and tabs?

2009-04-13 Thread MRAB

DSblizzard wrote:

How to convert string with \n and \t symbols to natural string - with
new lines and tabs?


You'll need to explain what you mean.

A string literal represents newline and tab with \n and \t. Are you
talking about that, or does the string actually contain the characters
\n and \n? What do you see what you print it? What do you see when you
use repr and print the result?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Who is your daddy: Can I find what object instantiates another object?

2009-04-13 Thread Steven D'Aprano
On Mon, 13 Apr 2009 19:12:21 +0200, Diez B. Roggisch wrote:

>> Can the Parser object know who its Daddy is?
> 
> Yes, by Daddy telling him so. That's how nature does it, and how you
> should do it. Or do you think that because DNA-tests are available to us
> we should just put all kids into a big pool and make them find out who
> their parents are themselves, once they grew up?

Oh, were you raised in a hippie commune in the Sixties too?


*wink*

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


Re: Who is your daddy: Can I find what object instantiates another object?

2009-04-13 Thread Aaron Brady
On Apr 13, 6:50 pm, Steven D'Aprano  wrote:
> On Mon, 13 Apr 2009 19:12:21 +0200, Diez B. Roggisch wrote:
> >> Can the Parser object know who its Daddy is?
>
> > Yes, by Daddy telling him so. That's how nature does it, and how you
> > should do it. Or do you think that because DNA-tests are available to us
> > we should just put all kids into a big pool and make them find out who
> > their parents are themselves, once they grew up?
>
> Oh, were you raised in a hippie commune in the Sixties too?
>
> *wink*

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


Re: binary file compare...

2009-04-13 Thread Steven D'Aprano
On Mon, 13 Apr 2009 15:03:32 -0500, Grant Edwards wrote:

> On 2009-04-13, SpreadTooThin  wrote:
> 
>> I want to compare two binary files and see if they are the same. I see
>> the filecmp.cmp function but I don't get a warm fuzzy feeling that it
>> is doing a byte by byte comparison of two files to see if they are they
>> same.
> 
> Perhaps I'm being dim, but how else are you going to decide if two files
> are the same unless you compare the bytes in the files?

If you start with an image in one format (e.g. PNG), and convert it to 
another format (e.g. JPEG), you might want the two files to compare equal 
even though their byte contents are completely different, because their 
contents (the image itself) is visually identical.

Or you might want a heuristic as a short cut for comparing large files, 
and decide that if two files have the same size and modification dates, 
and the first (say) 100KB are equal, that you will assume the rest are 
probably equal too.

Neither of these are what the OP wants, I'm just mentioning them to 
answer your rhetorical question :)



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


Re: Detecting -i in a script

2009-04-13 Thread Static Vagabond

I think getopt will help you achieve what you need.
http://docs.python.org/library/getopt.html

Here's a quick example:

import getopt
import sys

try:
opts, args = getopt.getopt(sys.argv[1:], "-i:vo:vhb?")
except getopt.GetoptError, err:
helpCommand() # defined elsewhere.
sys.exit()

for o, a in opts:
if o == "-i":
inputFile = a
elif o == "-o":
outputFile = a
elif o == "-?" or "-h":
helpCommand() # defined elsewhere.
elif o == "-b":
blank() # defined elsewhere.

Static.


Marek Szuba wrote:

On 2009-04-13, Chris Rebert  wrote:


The sys.flags.interactive bool.

Details: http://docs.python.org/library/sys.html#sys.flags

Hmm, "New in version 2.6"... Are you aware of any way of extracting
this information in older versions of Python? My code needs to be
2.3-compatible.


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


Re: PEP 3143 and daemon process

2009-04-13 Thread Ben Finney
On 13-Apr-2009, Alfredo Deza wrote:
> By "compliant", I do mean to reference PEP 3143 for building the app.

I'm still not sure what you mean by this. I can only assume you mean
that your program will assume the existence of a PEP 3143
implementation (like the ‘python-daemon’ library), and your program
will use its API.

> I am not sure how to continue now though, is weird, I can swear I
> searched for a while for libraries on how to daemonize correctly a
> Python application and could not find anything quite like it.

Note that, as described in PEP 3143, “daemonize a program” means
nothing more than making the *current program* become a daemon
process. It implies nothing special about external interaction with
that process; having a service channel for controlling a separate
process isn't part of becoming a daemon.

> And now I know of python-daemon, python-ll-core (has a daemon
> module) and daemon.py
> 
> 
> Do you think I am going in the right direction?

I'm still not clear on what your current direction is :-) As its
champion, I think using PEP 3143 as a basis is the right direction,
and have provided ‘python-daemon’ to help people get there.

> The initial idea was to be able to build something I saw was not
> available (or not fully available) but much needed. I have several
> projects that would benefit from a Daemonizing Module that is able
> to offer functionality like reload, restart, stop, start, logs,
> force quit etc...

You're asking, then, for what is commonly called a “service” process
model. When implemented on Unix, this makes use of a daemon, but does
something significantly more; PEP 3143 explicitly doesn't cover it,
but is designed to be a good basis for it.

What you want is someone to develop and champion a “service” PEP
http://mail.python.org/pipermail/python-ideas/2009-January/002606.html>
and implementation library. That person is not going to be me, but I
encourage use of the daemon library API as a basis for implementing
the Unix platform specifics of a service API.

-- 
 \   “One of the most important things you learn from the internet |
  `\   is that there is no ‘them’ out there. It's just an awful lot of |
_o__)‘us’.” —Douglas Adams |
Ben Finney 


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


Re: Detecting -i in a script

2009-04-13 Thread Chris Rebert
> Marek Szuba wrote:
>>
>> On 2009-04-13, Chris Rebert  wrote:
>>
>>> The sys.flags.interactive bool.
>>>
>>> Details: http://docs.python.org/library/sys.html#sys.flags
>>
>> Hmm, "New in version 2.6"... Are you aware of any way of extracting
>> this information in older versions of Python? My code needs to be
>> 2.3-compatible.

On Mon, Apr 13, 2009 at 5:32 PM, Static Vagabond  wrote:
> I think getopt will help you achieve what you need.
> http://docs.python.org/library/getopt.html

A. Please don't top-post. It makes following the conversation more
difficult by presenting it out of chronological order.

B. -i is an option to the Python interpreter *itself*, not the Python
script, and so gets gobbled up before the script even starts, thus
`getopt` won't work. Observe:

ch...@morpheus ~ $ cat foo.py
from sys import argv
print argv
ch...@morpheus ~ $ python -i foo.py
['foo.py']
>>>

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


Re: PEP 3143 and daemon process

2009-04-13 Thread Alfredo Deza
On Mon, Apr 13, 2009 at 8:33 PM, Ben Finney

> wrote:

> On 13-Apr-2009, Alfredo Deza wrote:
> > By "compliant", I do mean to reference PEP 3143 for building the app.
>
> I'm still not sure what you mean by this. I can only assume you mean
> that your program will assume the existence of a PEP 3143
> implementation (like the ‘python-daemon’ library), and your program
> will use its API.


Correct.

>
> > I am not sure how to continue now though, is weird, I can swear I
> > searched for a while for libraries on how to daemonize correctly a
> > Python application and could not find anything quite like it.
>
> Note that, as described in PEP 3143, “daemonize a program” means
> nothing more than making the *current program* become a daemon
> process. It implies nothing special about external interaction with
> that process; having a service channel for controlling a separate
> process isn't part of becoming a daemon.
>


>
> > And now I know of python-daemon, python-ll-core (has a daemon
> > module) and daemon.py
> > 
> >
> > Do you think I am going in the right direction?
>
> I'm still not clear on what your current direction is :-) As its
> champion, I think using PEP 3143 as a basis is the right direction,
> and have provided ‘python-daemon’ to help people get there.
>

> > The initial idea was to be able to build something I saw was not
> > available (or not fully available) but much needed. I have several
> > projects that would benefit from a Daemonizing Module that is able
> > to offer functionality like reload, restart, stop, start, logs,
> > force quit etc...
>
> You're asking, then, for what is commonly called a “service” process
> model. When implemented on Unix, this makes use of a daemon, but does
> something significantly more; PEP 3143 explicitly doesn't cover it,
> but is designed to be a good basis for it.
>

Ok, I wasn't aware of this. Always thought of 'service' as something not
Unix but more Win32.
Again, I apologize for the mix-up, I thought a Daemon was not only a
detached  process, but something that was able to act upon commands.

>
> What you want is someone to develop and champion a “service” PEP
>  http://mail.python.org/pipermail/python-ideas/2009-January/002606.html>
> and implementation library. That person is not going to be me, but I
> encourage use of the daemon library API as a basis for implementing
> the Unix platform specifics of a service API.
>

I read your proposal and it now makes sense the difference between 'service'
and 'daemon'. Thanks for taking the time to explain further, this will help
me out and avoid further confusion.

-Alfredo

>
> --
>  \   “One of the most important things you learn from the internet |
>  `\   is that there is no ‘them’ out there. It's just an awful lot of |
> _o__)‘us’.” —Douglas Adams |
> Ben Finney 
>
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v1.4.9 (GNU/Linux)
>
> iEYEARECAAYFAknj2d4ACgkQIiYF7H0aG3nJ2gCg2BVUX5mJXXS6IgKjlf+76zaP
> eOQAoKBcO/xEjoKzrjPYjG7lQHt6tGC9
> =i+du
> -END PGP SIGNATURE-
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Can I import from a directory that starts with a dot (.) ?

2009-04-13 Thread Matthew Wilson
I want to have .foo directory that contains some python code.  I can't
figure out how to import code from that .foo directory.  Is this even
possible?

TIA

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


Re: possible pairings in a set

2009-04-13 Thread Alan G Isaac

I cannot access this thread right now so my
answer my be rednundant, but anyway:
http://docs.python.org/library/itertools.html#itertools.combinations

>>> from itertools import combinations
>>> print(list(combinations(range(4),2)))
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

hth,
Alan Isaac
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary file compare...

2009-04-13 Thread Dave Angel

SpreadTooThin wrote:

On Apr 13, 2:37 pm, Grant Edwards  wrote:
  

On 2009-04-13, Grant Edwards  wrote:





On 2009-04-13, SpreadTooThin  wrote:
  

I want to compare two binary files and see if they are the same.
I see the filecmp.cmp function but I don't get a warm fuzzy feeling
that it is doing a byte by byte comparison of two files to see if they
are they same.


Perhaps I'm being dim, but how else are you going to decide if
two files are the same unless you compare the bytes in the
files?
  
You could hash them and compare the hashes, but that's a lot

more work than just comparing the two byte streams.
  

What should I be using if not filecmp.cmp?


I don't understand what you've got against comparing the files
when you stated that what you wanted to do was compare the files.
  

Doh!  I misread your post and thought were weren't getting a
warm fuzzying feeling _because_ it was doing a byte-byte
compare. Now I'm a bit confused.  Are you under the impression
it's _not_ doing a byte-byte compare?  Here's the code:

def _do_cmp(f1, f2):
bufsize =UFSIZE
fp1 =pen(f1, 'rb')
fp2 =pen(f2, 'rb')
while True:
b1 =p1.read(bufsize)
b2 =p2.read(bufsize)
if b1 !=2:
return False
if not b1:
return True

It looks like a byte-by-byte comparison to me.  Note that when
this function is called the file lengths have already been
compared and found to be equal.

--
Grant Edwards   grante Yow! Alright, you!!
  at   Imitate a WOUNDED SEAL
   visi.compleading for a PARKING
   SPACE!!



I am indeed under the impression that it is not always doing a byte by
byte comparison...
as well the documentation states:
Compare the files named f1 and f2, returning True if they seem equal,
False otherwise.

That word... Sem... makes me wonder.

Thanks for the code! :)


  
Some of this discussion depends on the version of Python, but didn't say 
so.  In version 2.61, the code is different (and more complex) than 
what's listed above.  The docs are different too.  In this version, at 
least, you'll want to explicitly pass the shallow=False parameter.  It 
defaults to 1, by which they must mean True.  I think it's a bad 
default, but it's still a useful function.  Just be careful to include 
that parameter in your call.


Further, you want to check the version included with your version.  The 
file filecmp.py is in the Lib directory, so it's not trouble to check it.



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


Re: Detecting -i in a script

2009-04-13 Thread Static Vagabond

Chris Rebert wrote:

Marek Szuba wrote:

On 2009-04-13, Chris Rebert  wrote:


The sys.flags.interactive bool.

Details: http://docs.python.org/library/sys.html#sys.flags

Hmm, "New in version 2.6"... Are you aware of any way of extracting
this information in older versions of Python? My code needs to be
2.3-compatible.


On Mon, Apr 13, 2009 at 5:32 PM, Static Vagabond  wrote:

I think getopt will help you achieve what you need.
http://docs.python.org/library/getopt.html


A. Please don't top-post. It makes following the conversation more
difficult by presenting it out of chronological order.

B. -i is an option to the Python interpreter *itself*, not the Python
script, and so gets gobbled up before the script even starts, thus
`getopt` won't work. Observe:

ch...@morpheus ~ $ cat foo.py
from sys import argv
print argv
ch...@morpheus ~ $ python -i foo.py
['foo.py']

Cheers,
Chris



Thanks for the tip Chris, been away from the newsgroups for a while and 
bad habits seem to have crept in.  All in all, a none-to-useful first 
post to comp.lang.python, here's hoping for a brighter future.


Can I presume the lack of a solution in your response means, 
essentially, prior to 2.6 there's no way of reading from the script that 
the interpreter has been launched in interactive mode?


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


Re: Detecting -i in a script

2009-04-13 Thread Chris Rebert
On Mon, Apr 13, 2009 at 6:10 PM, Static Vagabond  wrote:
> Chris Rebert wrote:
>>>
>>> Marek Szuba wrote:

 On 2009-04-13, Chris Rebert  wrote:

> The sys.flags.interactive bool.
>
> Details: http://docs.python.org/library/sys.html#sys.flags

 Hmm, "New in version 2.6"... Are you aware of any way of extracting
 this information in older versions of Python? My code needs to be
 2.3-compatible.
>>
>> On Mon, Apr 13, 2009 at 5:32 PM, Static Vagabond 
>> wrote:
>>>
>>> I think getopt will help you achieve what you need.
>>> http://docs.python.org/library/getopt.html
>>
>> A. Please don't top-post. It makes following the conversation more
>> difficult by presenting it out of chronological order.
>>
>> B. -i is an option to the Python interpreter *itself*, not the Python
>> script, and so gets gobbled up before the script even starts, thus
>> `getopt` won't work. Observe:
>>
>> ch...@morpheus ~ $ cat foo.py
>> from sys import argv
>> print argv
>> ch...@morpheus ~ $ python -i foo.py
>> ['foo.py']
>>
>> Cheers,
>> Chris
>
>
> Thanks for the tip Chris, been away from the newsgroups for a while and bad
> habits seem to have crept in.  All in all, a none-to-useful first post to
> comp.lang.python, here's hoping for a brighter future.
>
> Can I presume the lack of a solution in your response means, essentially,
> prior to 2.6 there's no way of reading from the script that the interpreter
> has been launched in interactive mode?

I'm not a (C)Python implementor, so I can't definitively answer that.
The fact that this functionality was added at all does, however, seem
to strongly imply that that is the case.
FWIW, I've scanned over the `sys` module, which would be the obvious
place to put such a feature or its rudiments, and can't find anything
else of use for the task.

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can I import from a directory that starts with a dot (.) ?

2009-04-13 Thread Ben Finney
Matthew Wilson  writes:

> I want to have .foo directory that contains some python code. I can't
> figure out how to import code from that .foo directory. Is this even
> possible?

Packages and modules need to have names that are valid Python
identifiers. That precludes the ‘.’ character (among many others).

You could delve into the import mechanism for ways to get a valid-named
module imported from a file with a different name; but surely it would
be simpler to have valid names on the filesystem in the first place.

-- 
 \   “The surest way to corrupt a youth is to instruct him to hold |
  `\   in higher esteem those who think alike than those who think |
_o__)   differently.” —Friedrich Nietzsche |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: Detecting -i in a script

2009-04-13 Thread Christian Heimes
Marek Szuba wrote:
> Is there any way of detecting in a script whether the interpreter
> session running it has been launched with the -i option? My Google fu
> has failed me on this subject... Thanks in advance.

There is no direct way to detect the interactive flag. However sys.ps1
and sys.ps2 are not set unless the interpreter runs in interactive mode.

import sys
isinteractive = hasattr(sys, "ps1")

The trick doesn't work if you want to get the flag's state before the
interactive interpreter starts.

You could query the internal state of the Py_InteractiveFlag flag with
ctypes. sys.flags does it, too.

import ctypes
ctypes.cast(ctypes.pythonapi.Py_InteractiveFlag,
ctypes.POINTER(ctypes.c_int)).contents.value

Christian

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


  1   2   >