Re: mod_python Unable to create file

2008-03-01 Thread Marc 'BlackJack' Rintsch
On Sat, 01 Mar 2008 22:47:02 -0800, kaush wrote:

> I am using Apache and mod_python to service POST/GET requests on MAC
> OS. My script tries to create a file
> 
> file = open(file_path, 'w')
> 
> This fails with the following error
> 
> EACCES
> Permission denied
> 
> What is missing?

To state the ovious: the rights to create a file at `file_path`.  Remember
that web servers usually have their own "user".

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


Re: How about adding rational fraction to Python?

2008-03-01 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> def mean(data): return sum(data)/len(data)
> 
> That does the right thing for data, no matter of what it consists of: 
> floats, ints, Decimals, rationals, complex numbers, or a mix of all of 
> the above.

One of those types is not like the others: for all of them except int,
the quotient operation actually is the inverse of multiplication.
So I'm unpersuaded that the "mean" operation above does the "right
thing" for ints.  If the integers being averaged were prices
in dollars, maybe the result type should even be decimal.

For this reason I think // is a good thing and I've gotten accustomed
to using it for integer division.  I can live with int/int=float but
find it sloppy and would be happier if int/int always threw an error
(convert explicitly if you want a particular type result).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Book Recomendations

2008-03-01 Thread js
I wonder why nobody mension Python Cookbook yet.
http://www.oreilly.com/catalog/pythoncook2/
Web version: http://aspn.activestate.com/ASPN/Cookbook/Python/

and Python Standard Library
http://www.oreilly.com/catalog/pythonsl/
http://effbot.org/zone/librarybook-index.htm

On Sun, Mar 2, 2008 at 4:09 PM, Paddy <[EMAIL PROTECTED]> wrote:
> On Mar 2, 12:56 am, Ira Solomon <[EMAIL PROTECTED]> wrote:
>  > I am an experienced programmer (40 years).  I've done Algol (if you've
>  > heard of that you must be old too), PL/1, VB,VBA, a little C, and a
>  > few other odd languages (e.g. Taskmate).
>  > I'm interested in learning Python and have downloaded a slew of books.
>  > Too many.
>  > I'd like a recommendation as to which books are considered to be the
>  > cream of the crop.
>  > I know there are tutorials on the web, but, again, I don't know the
>  > quality.  I would appreciate recommendations on those as well.
>  >
>  > Thanks
>  >
>  > Ira
>
>  Hi Ira,
>  Get Python installed on your machine - I would suggest the latest 2.5
>  release then either start up idle (or pythonwin if you have that on
>  windows), or just type python at a command line prompt to get you to
>  pythons shell.
>
>  The Python shell together with the official tutorial is a great way to
>  learn Python.
>
>  If you start to flag, then their are a few videos of pre-teen kids
>  learning Python here:
>  http://showmedo.com/videos/python?topic=beginner_programming
>  If they can learn it  ;-)
>
>  Welcome to Python, have fun!
>
>  - Paddy.
>
>
> --
>  http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Book Recomendations

2008-03-01 Thread Paddy
On Mar 2, 12:56 am, Ira Solomon <[EMAIL PROTECTED]> wrote:
> I am an experienced programmer (40 years).  I've done Algol (if you've
> heard of that you must be old too), PL/1, VB,VBA, a little C, and a
> few other odd languages (e.g. Taskmate).
> I'm interested in learning Python and have downloaded a slew of books.
> Too many.
> I'd like a recommendation as to which books are considered to be the
> cream of the crop.
> I know there are tutorials on the web, but, again, I don't know the
> quality.  I would appreciate recommendations on those as well.
>
> Thanks
>
> Ira

Hi Ira,
Get Python installed on your machine - I would suggest the latest 2.5
release then either start up idle (or pythonwin if you have that on
windows), or just type python at a command line prompt to get you to
pythons shell.

The Python shell together with the official tutorial is a great way to
learn Python.

If you start to flag, then their are a few videos of pre-teen kids
learning Python here:
http://showmedo.com/videos/python?topic=beginner_programming
If they can learn it  ;-)

Welcome to Python, have fun!

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


Re: How about adding rational fraction to Python?

2008-03-01 Thread Paul Rubin
Lie <[EMAIL PROTECTED]> writes:
> So basically they refused to satisfy everything that is still possible
> individually but would conflict if done together. 

I can't understand that.

> x = 1
> a = x + 1<< decides it's an int

No, so far a and x are both Num (indeterminate)

> b = x + 1.0  << error? or redefine to be float?

This determines that a, b, and x are all floats.  It's not "redefined"
since the types were unknown prior to this.  

Actually, I'm slightly wrong, 1.0 is not a float, it's a "Fractional"
which is a narrower class than Num but it could still be Float, Double,
or Rational.  Nums support addition, subtraction, multiplication, but
not necessarily division.  So int/int is an error.  Fractionals support
division.

> c = x + 1<< would this cause error while it worked in line 2?

No, c is also a float (actually Fractional)

> A slightly obfuscated example:
> l = [1, 1.0, 1]

This is the same as l = [1.0, 1.0, 1.0].  In Haskell, all elements
of a list must have the same type, so the 1.0 determines that l is
a list of fractionals.

> x = 1
> for n in l:
>   c = x + n

Haskell does not have loops, but if it did, all these values would be
fractionals.
-- 
http://mail.python.org/mailman/listinfo/python-list


mod_python Unable to create file

2008-03-01 Thread kaush
Hi,

I am using Apache and mod_python to service POST/GET requests on MAC
OS. My script tries to create a file

file = open(file_path, 'w')

This fails with the following error

EACCES
Permission denied

What is missing?

Thanks,
Kaushik

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


Re: Question about lambda and variable bindings

2008-03-01 Thread Terry Reedy

"Michael Torrie" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|I need to use a lambda expression

Lambda expressions are a convenience, not a necessity.  When having a 
problem, it sometimes helps to revert to the unabbreviated def statement.

tjr



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


Re: How about adding rational fraction to Python?

2008-03-01 Thread Lie
On Feb 29, 5:33 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> > > And rightly rejected by many other programming languages, including
> > > modern Python, not to mention calculators, real mathematics and
> > > common sense.
>
> > Lost me again.  I was not aware that calculators, real mathematics
> > and common sense were programming languages.
>
> I didn't say they were. Please parse my sentence again.

In the widest sense of the term computer and programming language,
actually calculators and real mathematics are programming languages.
Programming languages is a way to communicate problems with computer.
Computer is anything that does computation (and that includes
calculator and a room full of a bunch of people doing calculation with
pencil and paper[1]). The expressions we write in a calculator is a
(very limited) programming language, while mathematics conventions is
a language to communicate a mathematician's problems with the
computers[2] and other mathematicians

[1] Actually the term computer was first used to refer to this bunch
of people
[2] The computers in this sense is people that does computation
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-01 Thread Lie
On Mar 2, 2:32 am, Paul Rubin  wrote:
> Lie <[EMAIL PROTECTED]> writes:
> > I see, but the same arguments still holds true: the second line have
> > an implicit side-effect of redefining x's type into Fractional type.
> > If I were the designer of the language, I'd leave x's type as it is
> > (as Num) and coerce x for current calculation only.
>
> Num in Haskell is not a type, it is a class of types, i.e. if all you
> know about x is that it is a Num, then its actual type is
> indeterminate.  Types get inferred, they do not get coerced or
> "redefined".  The compiler looks at expressions referring to x, to
> deduce what x's type actually is.  If it is not possible to satisfy
> all constraints simultaneously, then the compiler reports an error.

So basically they refused to satisfy everything that is still possible
individually but would conflict if done together. (I know Haskell not
more than just its name so I don't understand the rationale behind the
language design at all) But I'm interested in how it handles these
cases:

x = 1
a = x + 1<< decides it's an int
b = x + 1.0  << error? or redefine to be float?
c = x + 1<< would this cause error while it worked in line 2?

A slightly obfuscated example:
l = [1, 1.0, 1]
x = 1
for n in l:
  c = x + n
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RELEASED Python 2.6a1 and 3.0a3

2008-03-01 Thread Terry Reedy

"Kay Schluehr" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| On 1 Mrz., 19:51, Barry Warsaw <[EMAIL PROTECTED]> wrote:
|
| > Python 2.6 is not only the next advancement in the Python 2 series, it
| > is also a transitionary release, helping developers begin to prepare
| > their code for Python 3.0.
|
| Isn't this a silly idea? People have to migrate from 2.5 or lower
| releases to Python 2.6 first just to migrate to Python 3.0?

You are quite free to update any code you want.  Barry just said that 2.6 
will help make the process easier. (At least it should for people who 
prefer incremental changes to doing it all at once.)   In any case, 2.5 and 
earlier code that does not depend on bugs later fixed should usually run 
unchanged in 2.6

| What are
| the inherent / technical reasons that prevent migration directly from
| 2.5 to 3.0?

None.

tjr



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


Re: RELEASED Python 2.6a1 and 3.0a3

2008-03-01 Thread Ben Finney
Kay Schluehr <[EMAIL PROTECTED]> writes:

> On 1 Mrz., 19:51, Barry Warsaw <[EMAIL PROTECTED]> wrote:
> 
> > Python 2.6 is not only the next advancement in the Python 2 series, it
> > is also a transitionary release, helping developers begin to prepare
> > their code for Python 3.0.
> 
> Isn't this a silly idea? People have to migrate from 2.5 or lower
> releases to Python 2.6 first just to migrate to Python 3.0? What are
> the inherent / technical reasons that prevent migration directly from
> 2.5 to 3.0?

One of the stated goals of the migration is that the '2to3' program
will only migrate Python 2.6 code -> Python 3.0 code. So, the
smoothest migration path will be:

  * get your program working with Python 2.6; then

  * use '2to3' to automatically translate that program to work with
Python 3.0; then

  * stop using Python 2.x for that program, only use Python 3.x.

Another reason is that good features from Python 3.0 will likely be
backported (if possible) to Python 2.6.x, but not to any earlier
version.

-- 
 \ "Dad always thought laughter was the best medicine, which I |
  `\guess is why several of us died of tuberculosis."  -- Jack |
_o__)   Handey |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Book Recomendations

2008-03-01 Thread subeen
On Mar 2, 6:56 am, Ira Solomon <[EMAIL PROTECTED]> wrote:
> I am an experienced programmer (40 years).  I've done Algol (if you've
> heard of that you must be old too), PL/1, VB,VBA, a little C, and a
> few other odd languages (e.g. Taskmate).
> I'm interested in learning Python and have downloaded a slew of books.
> Too many.
> I'd like a recommendation as to which books are considered to be the
> cream of the crop.
> I know there are tutorials on the web, but, again, I don't know the
> quality.  I would appreciate recommendations on those as well.
>
> Thanks
>
> Ira


I have found that 'Dive into Python' is a good book for people who
have experience with other languages. It's available free here:
http://www.diveintopython.org/

regards,
Subeen
http://love-python.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RELEASED Python 2.6a1 and 3.0a3

2008-03-01 Thread Kay Schluehr
On 1 Mrz., 19:51, Barry Warsaw <[EMAIL PROTECTED]> wrote:

> Python 2.6 is not only the next advancement in the Python 2 series, it
> is also a transitionary release, helping developers begin to prepare
> their code for Python 3.0.

Isn't this a silly idea? People have to migrate from 2.5 or lower
releases to Python 2.6 first just to migrate to Python 3.0? What are
the inherent / technical reasons that prevent migration directly from
2.5 to 3.0?

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


Re: Book Recomendations

2008-03-01 Thread Jeff Schwab
Ira Solomon wrote:
> I am an experienced programmer (40 years).  I've done Algol (if you've
> heard of that you must be old too), PL/1, VB,VBA, a little C, and a
> few other odd languages (e.g. Taskmate).
> I'm interested in learning Python and have downloaded a slew of books.
> Too many.
> I'd like a recommendation as to which books are considered to be the
> cream of the crop.
> I know there are tutorials on the web, but, again, I don't know the
> quality.  I would appreciate recommendations on those as well.

Python In A Nutshell:
http://www.oreilly.com/catalog/pythonian2/

Here's a previous discussion of books for newbies, but I gave my 
recommendations for other experienced programmers; be forwarned that I'm 
not quite as experienced as you appear to be. :)
http://www.nabble.com/newbie-in-python-td15608979.html#nabble.star15617714-1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SV: Where's GUI for Python?

2008-03-01 Thread Grant Edwards
On 2008-03-02, K Viltersten <[EMAIL PROTECTED]> wrote:
>>>import tkininter
>>>
>> When that fails, try without the stutter 
>> 
>> import tkinter
>
>
> I must be doing something wrong because
> neither tkinter nor tkininter works.

You probably don't have tkinter installed.  It's not installed
by default on many systems.

-- 
Grant Edwards   grante Yow!  Yow! I'm imagining
  at   a surfer van filled with
   visi.comsoy sauce!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: invert or not ?

2008-03-01 Thread Grant Edwards
On 2008-03-01, Stef Mientki <[EMAIL PROTECTED]> wrote:

> from the manual I read that a bitwise inversion should be done
> by invert. But from some experiments I see that not works
> equally well.

What experiments are those?

>>> print ~0xaa, not 0xaa
-171 False
>>> print ~0x55, not 0x55
-86 False
>>> 
>>> print ~True, not True
-2 False
>>> 

> Is this coincidence ?

Is what coincidence?

> (The disadvantage of invert is that I've to import operators)

No you don't.

-- 
Grant Edwards   grante Yow!  If elected, Zippy
  at   pledges to each and every
   visi.comAmerican a 55-year-old
   houseboy...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Telnet versus telnetlib

2008-03-01 Thread Grant Edwards
On 2008-03-01, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> En Fri, 29 Feb 2008 20:34:41 -0200, Sean Davis <[EMAIL PROTECTED]>  
> escribió:
>
>> When I do an analogous process using telnetlib, I get no debug output,
>> and most importantly, when I send the XML file to the host, I get no
>> printed page.  Unfortunately, I do not have access to the host to do
>> troubleshooting there, so I have to "feel" my way around.  Any
>> suggestions on what might be going wrong?
>>
>> In [12]: tn.write("""
>>: 
> \ is the quote character. You have to duplicate it "C:\\labels..." or use  
> a raw string r"""http://mail.python.org/mailman/listinfo/python-list


Re: Where's GUI for Python?

2008-03-01 Thread Bill
Peter Decker wrote, On 3/1/2008 9:58 PM:
> On Sat, Mar 1, 2008 at 3:35 PM, K Viltersten <[EMAIL PROTECTED]> wrote:
>> I'm certain there is an API for creating
>>  GUI's but as far i can find it in the
>>  http://docs.python.org/tut/tut.html
>>  the only "gui" is in "Guido".
> 
> Check out Dabo: http://dabodev.com
> 
> It uses the wxPython UI toolkit, but wraps it in a much more Pythonic API.
> 
> I've been using Dabo for over a year, and it rocks!!
> 

Hi Peter,

You should also take a look at wxGlade:

 http://wxglade.sourceforge.net/

which sits on top of wxPython:

 http://wxpython.org/

which wraps wxWidgets:

 http://www.wxwindows.org/


I've found that wxGlade is more usable, currently, than Dabo in it's 
visual layout tools that help you create the GUI for your apps.

If you want a more "Pythonic" API (more than wxPython/wxWidgets) and 
want to write your GUI using mainly code instead of a visual layout 
tool, then Dabo is probably the way to go.

If you want an interactive application that lets you visually create 
Frame or Dialog based applications, full of "widgets", then wxGlade is 
pretty good these days.  Dabo, last time I looked, didn't yet have a 
usable visual menu creation capability in it's toolset, and this is a 
major reason, for me, that I currently have gravitated back to wxGlade. 
  Also, although Dabo has a "Class Designer" that can design the GUI 
visually, and is in some ways more advanced than wxGlade, it seems in 
other ways to be more limiting.

Neither one, unfortunately, is very well documented, but wxGlade is 
fairly obvious, and directly generates wxPython code (not a "higher 
level" API as is done in Dabo), which lets you use the wxGlade and 
wxWidgets documentation to figure things out.

Also, BTW, I think the statement on the wxGlade site about "the 
generated code does nothing apart from displaying the created widgets", 
is not really true, and should be re-worded.  Current versions of 
wxGlade include the capability to automatically create simple 
event-handler functions, and automatically generates the code to connect 
the events generated by the GUI widgets to the event handlers.  In my 
opinion, this is much more than doing "nothing apart from displaying the 
created widgets".  It helps make it real easy to call your handler 
functions, and I don't really want it doing much more than that anyway.

In either case, when you write your own code, it is probably best to 
learn how to have the tool generate the code containing the classes that 
form the GUI interface, but, use derived classes (subclasses) in your 
own separate file(s) to form your application's interface to the GUI. 
That way, you can let wxGlade (or Dabo) always generate (and overwrite) 
its own code that remains entirely separate from your own code.


Bill










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


Re: Question about lambda and variable bindings

2008-03-01 Thread castironpi
On Mar 1, 8:50 pm, Michael Torrie <[EMAIL PROTECTED]> wrote:
> I need to use a lambda expression to bind some extra contextual data
> (should be constant after it's computed) to a call to a function.  I had
> originally thought I could use something like this demo (but useless) code:
>
> funcs=[]
>
> def testfunc(a,b):
>     print "%d, %d" % (a,b)
>
> for x in xrange(10):
>     funcs.append(lambda p: testfunc(x+2,p))
>
> Now what I'd like is to call, for example, funcs[0](4) and it should
> print out "2,4".  In other words I'd like the value of x+2 be encoded
> into the lambda somehow, for funcs[x].  However the disassembly shows
> this, which is reasonable, but not what I need:
>
> >>> dis.dis(funcs[0])
>
>   2           0 LOAD_GLOBAL              0 (testfunc)
>               3 LOAD_GLOBAL              1 (x)
>               6 LOAD_CONST               0 (2)
>               9 BINARY_ADD
>              10 LOAD_FAST                0 (p)
>              13 CALL_FUNCTION            2
>              16 RETURN_VALUE
>
> The LOAD_GLOBAL 1 (x) line is definitely a problem.  For one it refers
> to a variable that won't be in scope, should this lambda be called from
> some stack frame not descended from the one where I defined it.
>
> So how can I create a lambda expression that calculates a constant based
> on an expression, rather than referring to the object itself?  Can it be
> done?
>
> Michael

I hate that.  Especially since ints are immutable.

>>> from functools import partial
>>> funcs= [ partial( print, x ) for x in range( 10 ) ]
>>> for func in funcs:
... func()
...
0
1
2
3
4
5
6
7
8
9
>>>

takes advantage of 2.5+ functools.partial and 3.0 print.  You can use
sys.stdout instead of print in the example in 2.5, but without
partial, you're at:

class Val:
   def __init__( self, val ):
  self.val= val
   def __call__( self ):
  self.val+= 10

val= Val( 20 )
val()

.  There's also a CellMaker implementation somewhere on Py-Ideas, but
it was outlawed in 18 provinces, and it just evaluates and compiles a
string anyway.

for x in xrange(10):
fun= exec( 'lambda p: testfunc(%i+2,p)'% x )
funcs.append( fun )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about lambda and variable bindings

2008-03-01 Thread Michael Torrie
poof65 wrote:
> An idea, i don't know if it will work in your case.
> 
> for x in xrange(10):
>   funcs.append(lambda p,z=x: testfunc(z+2,p))

Good idea.  I will try it.  I also figured out a way to architecture my
program differently to avoid this problem.  But this idiom might be
handy in certain situations.  Suppose you need to provide a callback
function with a fixed signature to some library routine.  But you want
to add extra contextual data to your callback.  This just might be the
ticket.

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


Re: How to subclass a built-in int type and prevent comparisons

2008-03-01 Thread castironpi
On Mar 1, 2:58 pm, Michael Torrie <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Tell Wall.  But why not [ 2, 3 ]>= 2?  Back to your question, another
> > option is to not subclass.
>
> Umm, no.  You need to actually read the posts before you respond to
> them.  His question was whether or not to throw an exception in this
> case.  He's *already* subclassed the type.
>
> The first question was, should he throw an exception.  And given that
> Python 3.0 will throw exceptions, he is justified in throwing exceptions
> as well.  I have no idea what he would lose by throwing an exception.  I
> have no idea how else he would do this.
>
> His second question was, would his code for implementing __gt__ (and
> throwing exceptions) be likely efficient.  That I cannot say.

Point taken.  The is-a vs. has-a distinction was what I was looking
at.  Is it more work to the OP to disable the things in Int he doesn't
want, or to enable those he does?

On a tangent (you were alerted):

A horse with three legs is a horse.  A square with three sides is a
square.  A cup of coffee with no bottom is not a cup.

If he doesn't throw an exception, he can compare to an arbitrary
point, class-static, etc., post a message to a queue awaiting further
instructions and block to its return, fire a synchronous callback,
pause for user input, remove a certain element and set an op-abort
flag, return a special value ( NoCompare= object() ), NaN, INF, &c.,
upgrade one or both operands, vary the behavior with class or
instance, callback a coroutine omitting the point and assessing later,
add it to a list of problem data to be treated by a superior, or take
a special lunch break, after which the right-hand value is guaranteed
to conform.  You can try casting the RHV right-hand value to the
required type too.

Originally, exceptions came about as ways to respond to requests of a
class hierarchy that fail to evaluate for the derived type, such as
Ostrich().fly(), but expanded to include logic flow: do this this and
this, except when file doesn't close correctly.

In Python 1.0, a lot of classes set methods upon construction:  init:
self.data= data; self.__gt__= self.data.__gt__, and perhaps subclass
that.  Or move to C.

In the trade, customers don't care what code made the program they
bought.  The company doesn't care what code made the program.
Reinventing the wheel is cheap for certain wheels.  Hallway full of
doors; close some to get the product out sooner.  What might we want
down the road?  What's down the road?  Who is?

In the hobbies, you can see an elaborate mixin to simplify work later,
just for practice, or for the Zen-and-the art, like doing puzzles.

class SpecialInt( Selective, int ):
   meths= Selective.numerics( int )
   onlyif= [ partial( is_, int ), or_, partial( is_, SpecialInt ) ]

It just costs performance-- product performance, even if not
production team performance.

from functools import partial
from operator import is_, is_not
assert partial( is_, int )( type( 2 ) )
assert partial( is_not, int )( type( 2.5 ) )

But:

>>> class C: C
...
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in C
NameError: name 'C' is not defined

Can we have access to classes in their definitions?

class C: delayed( 'C' )

works fine.  If we don't want to permit calling a function on a half-
executed class, then postcreator(or something) would have to be
syntax.

Class decorators can do it:

* current= Current()
@current.delay
class SpecialInt:
   onlyif= [ partial( is_, int ), or_, partial( is_, current ) ]

Similarly:

* current= Current()
class SpecialInt:
   onlyif= [ partial( is_, int ), or_, partial( is_, current ) ]
current.delayedeval( SpecialInt )

But it starts to get really tangled:

current= Current()
@current.delay
class SpecialInt:
   onlyif= [ partial( is_, int ), or_, current.partial( partial, is_,
current ) ]

where current.partial returns a delegation object that replaces
current with the class current.delay wraps.  If you don't want current
to delegate too, then:

current= Current()
@current.delay
class SpecialInt:
   onlyif= [ partial( is_, int ), or_, current.partial( partial, is_,
current.ref ) ]

may be next best.

But all this is just to save two lines somewhere where you're allowed
to use a custom wrap-in class, since Current is borderline library,
and don't even mention 'standard'.  However if it saves ten seconds in
a coding competition, or captures the flash of an idea you get at 2
a.m. (make that 4 for the kids), then it's worth keeping around.
import obscure.  And

class SpecialInt:
   onlyif= [ partial( is_, int ) ]
SpecialInt.onlyif.extend( [ or_, partial( is_, SpecialInt ) ] )

sure is practical.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about lambda and variable bindings

2008-03-01 Thread poof65
An idea, i don't know if it will work in your case.

for x in xrange(10):
  funcs.append(lambda p,z=x: testfunc(z+2,p))

On Sun, Mar 2, 2008 at 3:50 AM, Michael Torrie <[EMAIL PROTECTED]> wrote:
> I need to use a lambda expression to bind some extra contextual data
>  (should be constant after it's computed) to a call to a function.  I had
>  originally thought I could use something like this demo (but useless) code:
>
>  funcs=[]
>
>  def testfunc(a,b):
> print "%d, %d" % (a,b)
>
>  for x in xrange(10):
> funcs.append(lambda p: testfunc(x+2,p))
>
>
>  Now what I'd like is to call, for example, funcs[0](4) and it should
>  print out "2,4".  In other words I'd like the value of x+2 be encoded
>  into the lambda somehow, for funcs[x].  However the disassembly shows
>  this, which is reasonable, but not what I need:
>
>  >>> dis.dis(funcs[0])
>   2   0 LOAD_GLOBAL  0 (testfunc)
>   3 LOAD_GLOBAL  1 (x)
>   6 LOAD_CONST   0 (2)
>   9 BINARY_ADD
>  10 LOAD_FAST0 (p)
>  13 CALL_FUNCTION2
>  16 RETURN_VALUE
>
>  The LOAD_GLOBAL 1 (x) line is definitely a problem.  For one it refers
>  to a variable that won't be in scope, should this lambda be called from
>  some stack frame not descended from the one where I defined it.
>
>  So how can I create a lambda expression that calculates a constant based
>  on an expression, rather than referring to the object itself?  Can it be
>  done?
>
>  Michael
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


class object interface document

2008-03-01 Thread Neil.Fang.CN
Hello

Where can I find the Python class object interface document, such as
struct PyClassObject, PyClass_New()? Thanks!

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


Re: Where's GUI for Python?

2008-03-01 Thread Peter Decker
On Sat, Mar 1, 2008 at 3:35 PM, K Viltersten <[EMAIL PROTECTED]> wrote:
> I'm certain there is an API for creating
>  GUI's but as far i can find it in the
>  http://docs.python.org/tut/tut.html
>  the only "gui" is in "Guido".

Check out Dabo: http://dabodev.com

It uses the wxPython UI toolkit, but wraps it in a much more Pythonic API.

I've been using Dabo for over a year, and it rocks!!

-- 

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Question about lambda and variable bindings

2008-03-01 Thread Michael Torrie
I need to use a lambda expression to bind some extra contextual data
(should be constant after it's computed) to a call to a function.  I had
originally thought I could use something like this demo (but useless) code:

funcs=[]

def testfunc(a,b):
print "%d, %d" % (a,b)

for x in xrange(10):
funcs.append(lambda p: testfunc(x+2,p))


Now what I'd like is to call, for example, funcs[0](4) and it should
print out "2,4".  In other words I'd like the value of x+2 be encoded
into the lambda somehow, for funcs[x].  However the disassembly shows
this, which is reasonable, but not what I need:

>>> dis.dis(funcs[0])
  2   0 LOAD_GLOBAL  0 (testfunc)
  3 LOAD_GLOBAL  1 (x)
  6 LOAD_CONST   0 (2)
  9 BINARY_ADD
 10 LOAD_FAST0 (p)
 13 CALL_FUNCTION2
 16 RETURN_VALUE

The LOAD_GLOBAL 1 (x) line is definitely a problem.  For one it refers
to a variable that won't be in scope, should this lambda be called from
some stack frame not descended from the one where I defined it.

So how can I create a lambda expression that calculates a constant based
on an expression, rather than referring to the object itself?  Can it be
done?

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


Re: Book Recomendations

2008-03-01 Thread Micah Cowan
Ira Solomon <[EMAIL PROTECTED]> writes:

> I am an experienced programmer (40 years).  I've done Algol (if you've
> heard of that you must be old too), PL/1, VB,VBA, a little C, and a
> few other odd languages (e.g. Taskmate).
> I'm interested in learning Python and have downloaded a slew of books.
> Too many.
> I'd like a recommendation as to which books are considered to be the
> cream of the crop.
> I know there are tutorials on the web, but, again, I don't know the
> quality.  I would appreciate recommendations on those as well.

I have found the official documentation available at python.org
(including both the tutorial and references) to be very
high-quality.

-- 
Micah J. Cowan
Programmer, musician, typesetting enthusiast, gamer...
http://micah.cowan.name/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where's GUI for Python?

2008-03-01 Thread castironpi
On Mar 1, 6:49 pm, "K Viltersten" <[EMAIL PROTECTED]> wrote:
> >> When that fails, try without the stutter 
>
> >> import tkinter
>
> > I must be doing something wrong because
> > neither tkinter nor tkininter works.
> > I tried both with and without stuttering.
> > I even asked my wife to stutter some but,
> > sadly, to no avail.
>
> > When Tim Chase mentioned "battery-installed",
> > i interpreted it as "all is there". It seems
> > that either
> > a) not all the batteries are installed in my
> > version (v2.5.2)
> > or
> > b) some setup/linkage needs to be performed
> > in order to get the GUI running.
>
> > The error itself is:
> > ImportError: No module named tkinter
>
> > Suggestions?
>
> Here's a suggestion. Python is case-sensitive,
> while the users trying to help you are not.
> When they say "tininkerbell", they may mean
> "Tinkerbell". Check with "help()", then
> "modules" and see if it's installed or not.
>
> Sincerely
> Yourself
>
> :)
>
> (Seriously speaking - i'm thankful.)- Hide quoted text -
>
> - Show quoted text -

AmbiguityWarning: Variables 'tklst' and 'tklist' resemble 'tkst'.
Automatic snap-to-slot has been disabled.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Book Recomendations

2008-03-01 Thread Ryan M.
On Mar 1, 7:56 pm, Ira Solomon <[EMAIL PROTECTED]> wrote:
> I am an experienced programmer (40 years).  I've done Algol (if you've
> heard of that you must be old too), PL/1, VB,VBA, a little C, and a
> few other odd languages (e.g. Taskmate).
> I'm interested in learning Python and have downloaded a slew of books.
> Too many.
> I'd like a recommendation as to which books are considered to be the
> cream of the crop.
> I know there are tutorials on the web, but, again, I don't know the
> quality.  I would appreciate recommendations on those as well.
>
> Thanks
>
> Ira

I would recommend checking out the official Python tutorial -
http://docs.python.org/tut/ - it has some valuable information, and is
always kept up to date.

I'm haven't looked at any Python books (yet), so I can't provide any
recommendations there.

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


Re: Book Recomendations

2008-03-01 Thread Tro
On Saturday 01 March 2008, Ira Solomon wrote:
> I am an experienced programmer (40 years).  I've done Algol (if you've
> heard of that you must be old too), PL/1, VB,VBA, a little C, and a
> few other odd languages (e.g. Taskmate).
> I'm interested in learning Python and have downloaded a slew of books.
> Too many.
> I'd like a recommendation as to which books are considered to be the
> cream of the crop.
> I know there are tutorials on the web, but, again, I don't know the
> quality.  I would appreciate recommendations on those as well.

The official tutorial is required reading. After that, Dive Into Python 
(http://diveintopython.org/).

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


Re: SV: Where's GUI for Python?

2008-03-01 Thread Ricardo Aráoz
K Viltersten wrote:
>>>import tkininter
>>>
>> When that fails, try without the stutter 
>>
>> import tkinter
> 
> 
> I must be doing something wrong because
> neither tkinter nor tkininter works.
> I tried both with and without stuttering.
> I even asked my wife to stutter some but,
> sadly, to no avail.
> 
> When Tim Chase mentioned "battery-installed", 
> i interpreted it as "all is there". It seems 
> that either
> a) not all the batteries are installed in my
> version (v2.5.2)
> or
> b) some setup/linkage needs to be performed
> in order to get the GUI running.
> 
> The error itself is:
> ImportError: No module named tkinter
> 
> Suggestions?
> 

import Tkinter

(first letter is uppercase)
-- 
http://mail.python.org/mailman/listinfo/python-list


Book Recomendations

2008-03-01 Thread Ira Solomon
I am an experienced programmer (40 years).  I've done Algol (if you've
heard of that you must be old too), PL/1, VB,VBA, a little C, and a
few other odd languages (e.g. Taskmate).
I'm interested in learning Python and have downloaded a slew of books.
Too many.
I'd like a recommendation as to which books are considered to be the
cream of the crop.
I know there are tutorials on the web, but, again, I don't know the
quality.  I would appreciate recommendations on those as well.

Thanks

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


Python Telnet formatting?

2008-03-01 Thread mentaltruckdriver
Hi everyone:

I posted here a couple days ago looking for some help creating a
Telnet-based chat server. You guys pointed me to Twisted, which has
solved most of my issues.

However, what I want to do is analyze strings received for keywords
such as 'listcmds' and have the server return something to the client.
I know how to do that part, at least.

The issue is, when I use clients like PuTTY, it returns a lot of what
appears to be formatting (e.g. if I typed Hello, it would return "\xff
\xfb\x1f\xff\
xfb \xff\xfb\x18\xff\xfb'\xff\xfd\x01\xff\xfb\x03\xff\xfd\x03Hello".)

How would I go about filtering this stuff out of the strings? The
thing is too, if I use other Telnet programs like Microsoft Telnet,
they don't have this formatting, so I want to be able to recognize if
it does have this formatting and act based on if it does or if it
doesn't.

Any help is appreciated, I know I'm probably asking too many questions
already :)

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


SV: Where's GUI for Python?

2008-03-01 Thread K Viltersten
>> When that fails, try without the stutter 
>> 
>> import tkinter
> 
> I must be doing something wrong because
> neither tkinter nor tkininter works.
> I tried both with and without stuttering.
> I even asked my wife to stutter some but,
> sadly, to no avail.
> 
> When Tim Chase mentioned "battery-installed", 
> i interpreted it as "all is there". It seems 
> that either
> a) not all the batteries are installed in my
> version (v2.5.2)
> or
> b) some setup/linkage needs to be performed
> in order to get the GUI running.
> 
> The error itself is:
> ImportError: No module named tkinter
> 
> Suggestions?


Here's a suggestion. Python is case-sensitive, 
while the users trying to help you are not.
When they say "tininkerbell", they may mean
"Tinkerbell". Check with "help()", then 
"modules" and see if it's installed or not.

Sincerely
Yourself

:)

(Seriously speaking - i'm thankful.)





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


SV: Where's GUI for Python?

2008-03-01 Thread K Viltersten
>>import tkininter
>>
> When that fails, try without the stutter 
> 
> import tkinter


I must be doing something wrong because
neither tkinter nor tkininter works.
I tried both with and without stuttering.
I even asked my wife to stutter some but,
sadly, to no avail.

When Tim Chase mentioned "battery-installed", 
i interpreted it as "all is there". It seems 
that either
a) not all the batteries are installed in my
version (v2.5.2)
or
b) some setup/linkage needs to be performed
in order to get the GUI running.

The error itself is:
ImportError: No module named tkinter

Suggestions?

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


SV: Surprised by the command "del"

2008-03-01 Thread K Viltersten
>>I'm reading the docs and at 5.2 the del
>>statement is discussed. At first, i thought
>>i've found a typo but as i tried that 
>>myself, it turns it actually does work so.
>>
>>  a = ["alpha", "beta", "gamma"]
>>  del a[2:2]
>>  a
>>
>>Now, i expected the result to be that the
>>"beta" element has been removed. Obviously, 
>>Python thinks otherwise. Why?!
>>
>>Elaboration:
>>I wonder why such an unintuitive effect has
>>been implemented. I'm sure it's for a very
>>good reason not clear to me due to my
>>ignorance. Alternatively - my expectations
>>are not so intuitive as i think.   :)
> 
> I think it should say 
> del a[1:2]
> then it works


While i'm thankful for the advice, i need to
point out that the question wasn't "how to"
but "why". Anyhow, it's been explained as a
matter of definition of a "slice".

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


Altering imported modules

2008-03-01 Thread Tro
Hi, list.

I've got a simple asyncore-based server. However, I've modified the asyncore 
module to allow me to watch functions as well as sockets. The modified 
asyncore module is in a specific location in my project and is imported as 
usual from my classes.

Now I'd like to use the tlslite library, which includes an asyncore mixin 
class. However, tlslite imports "asyncore", which doesn't include my own 
modifications.

I'd like to know if it's possible to make tlslite load *my* asyncore module 
without changing any of the tlslite code.

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


Re: sqlite3 adaptors mystery

2008-03-01 Thread Mel
Matej Cepl wrote:
[ ... ]
> However, when running this program it seems converter doesn’t seem to work,
> because I get:
> 
> [EMAIL PROTECTED] dumpBugzilla]$ rm test.db ; python testAdaptors.py
> [(u'False',), (u'True',)]
> [EMAIL PROTECTED] dumpBugzilla]$
> 
> There is probably something quite obvious what I do incorrectly, but I just
> don't see it. Could somebody kick me in the right direction, please?

There's nothing much wrong.  cur.fetchall is returning a list of all 
the selected rows, and each row is a tuple of fields.  Each tuple is 
being converted for display by repr, so the strings are shown as 
unicode, which is what they are internally.  Change the print to

for (field,) in cur.fetchall():
 print field

and you'll see your plain-text strings.

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

Re: cx_Freeze : LookupError: unknown encoding: ascii

2008-03-01 Thread Martin v. Löwis
> Can somebody point to some clues about options that need to be passed
> to FreezePython API to get the right executable.

You need to tell it to include the encodings.ascii module.

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


Re: Problems building 2.5.1 on AIX

2008-03-01 Thread Martin v. Löwis
> hasty:Python-2.5.1$ CC=/usr/vacpp/bin/cc_r ./configure --without-gcc
> checking MACHDEP... aix5
> checking EXTRAPLATDIR... 
> checking for --without-gcc... yes
> checking for gcc... cc
> checking for C compiler default output file name... configure: error: C 
> compiler cannot create executables
> See `config.log' for more details.
> 
> I get the same result with or without the --without-cgg.  There's nothing 
> obvious in config.log (not that I can ever make much sense out of the 
> gibberish configure generates).
> 
> Any ideas?

You really do have to check config.log. Check for any lines where it 
tries to invoke the compiler, and check whether it does so in the way
you expect it to.

 From the output you provide, it seems to use "cc" as the compiler,
not /usr/vacpp/bin/cc_r. Looking at the comfigure code, this is not
surprising: --without-gcc resets CC to cc.

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


sqlite3 adaptors mystery

2008-03-01 Thread Matej Cepl
Hi,

I am in the process of creating a small script for filling the 
sqlite3 database with data from rather large XML-RPC query (list 
of many bugs from the Red Hat Bugzilla) and I would love to use 
adaptors and converters for some data types which I am missing.

I have this test script (made hopefully pretty faithfully from the
documentation):

#!/usr/bin/python
import sqlite3
def adapt_boolean(bol):
 if bol:
 return "True"
 else:
 return "False"
 
def convert_boolean(bolStr):
 if str(bolStr) == "True":
 return bool(True)
 elif str(bolStr) == "False":
 return bool(False)
 else:
 raise ValueError, "Unknown value of bool attribute '%s'" \
% bolStr
 
sqlite3.register_adapter(bool,adapt_boolean)
sqlite3.register_converter("boolean",convert_boolean)

db = sqlite3.connect("test.db")
cur=db.cursor()
cur.execute("create table test(p boolean)")
p=False
cur.execute("insert into test(p) values (?)", (p,))
p=True
cur.execute("insert into test(p) values (?)", (p,))
cur.execute("select p from test")
print cur.fetchall()

And I would expect to print on output representation of bool values, i.e.,
something like

[False,True]

However, when running this program it seems converter doesn’t seem to work,
because I get:

[EMAIL PROTECTED] dumpBugzilla]$ rm test.db ; python testAdaptors.py
[(u'False',), (u'True',)]
[EMAIL PROTECTED] dumpBugzilla]$

There is probably something quite obvious what I do incorrectly, but I just
don't see it. Could somebody kick me in the right direction, please?

Thanks a lot,

Matěj Cepl
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: PIL transparency gradient

2008-03-01 Thread Allard Warrink
Thanks for the inspiration!
This what I did (Using your Python Editor (SPE), I really like to work
with SPE, keep up the good work!!):

#
import Image, os
p = # path to image file

im = Image.open(p)
# check if im has Alpha band...
if im.mode != 'RGBA':
im = im.convert('RGBA')
# create a vertical gradient...
gradient = Image.new('L', (1,255))
for y in range(255):
gradient.putpixel((0,254-y),y)
# resize the gradient to the size of im...
alpha = gradient.resize(im.size)
# put alpha in the alpha band of im...
im.putalpha(alpha)
# Save as png...
im.save(os.path.splitext(p)[0] + '.png', 'PNG

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


Re: Python COM automation - Controlling Microsoft Agent

2008-03-01 Thread Fuzzyman
On Mar 1, 12:47 am, Kamilche <[EMAIL PROTECTED]> wrote:
> Here's a snippet of code for pythoners to enjoy.
> Make the Microsoft genie speak text and dance about!


Code (with pretty  pictures!) to do similar things from IronPython:

http://www.ironpython.info/index.php/AgentServerObjects

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


Re: [Python-Dev] [Python-3000] RELEASED Python 2.6a1 and 3.0a3

2008-03-01 Thread Martin v. Löwis
> The 2.6a1 x86 MSI is there, but the 3.0a3 x86 MSI is still giving a 404.

Please try again - *those* files weren't actually there when I sent my
last message; I just built them.

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


Re: Surprised by the command "del"

2008-03-01 Thread From
On Sat, 1 Mar 2008 21:05:41 +0100, "K Viltersten"
<[EMAIL PROTECTED]> wrote:

>I'm reading the docs and at 5.2 the del
>statement is discussed. At first, i thought
>i've found a typo but as i tried that 
>myself, it turns it actually does work so.
>
>  a = ["alpha", "beta", "gamma"]
>  del a[2:2]
>  a
>
>Now, i expected the result to be that the
>"beta" element has been removed. Obviously, 
>Python thinks otherwise. Why?!
>
>Elaboration:
>I wonder why such an unintuitive effect has
>been implemented. I'm sure it's for a very
>good reason not clear to me due to my
>ignorance. Alternatively - my expectations
>are not so intuitive as i think.   :)


I think it should say 
del a[1:2]
then it works


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


cx_Freeze : LookupError: unknown encoding: ascii

2008-03-01 Thread Rakesh Kumar
Hi -
   I created a binary using the cx_Freeze utility on Linux (wxWidgets
2.8 / Python 2.5/ Mandriva 2008 ).

  When I tried to run the binary - this is the error that I got on the
console.

  File "gdataapi.py", line 44, in __init__
self.service.ProgrammaticLogin()
  File "/opt/software/gdata-py/src/gdata/service.py", line 284, in
ProgrammaticLogin
auth_connection.putrequest('POST', '/accounts/ClientLogin')
  File "/usr/lib/python2.5/httplib.py", line 806, in putrequest
host_enc = self.host.encode("ascii")
LookupError: unknown encoding: ascii


Can somebody point to some clues about options that need to be passed
to FreezePython API to get the right executable.

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


Re: [Python-Dev] [Python-3000] RELEASED Python 2.6a1 and 3.0a3

2008-03-01 Thread Paul Moore
On 01/03/2008, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > As of 4:50 PM  EST, the links to Windows installers give 404 File Not
>  > Found.
>  >
>  > I gather that they are still in process,
>  > and notice that there is no public c.l.p. announcement.
>
>
> I just fixed that. The files were there; just the links were wrong.

The 2.6a1 x86 MSI is there, but the 3.0a3 x86 MSI is still giving a 404.

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


Re: [Python-3000] RELEASED Python 2.6a1 and 3.0a3

2008-03-01 Thread Barry Warsaw
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On Mar 1, 2008, at 5:26 PM, Martin v. Löwis wrote:

>> As of 4:50 PM  EST, the links to Windows installers give 404 File Not
>> Found.
>>
>> I gather that they are still in process,
>> and notice that there is no public c.l.p. announcement.
>
> I just fixed that. The files were there; just the links were wrong.

Thanks for fixing these Martin!

- -Barry

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

iQCVAwUBR8nY1HEjvBPtnXfVAQJ3YgP/TYr0X5vRqvVDEMgsHxHuiSuYZCIr8y36
ibAh3RAGeLLK7C7NiOyAfxkesf91HCbL1in0TcnD06QZy52O8elBa927JOomP3mc
Y6K4Y49JhxonBrmGcmasnc9PFjbhXtGdWLREinuzpB5itLpRv+SevMhxP27Fp8qr
df173TV4hpk=
=nf32
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where's GUI for Python?

2008-03-01 Thread Roy H. Han
Konrad, I use wxPython with wxGlade.

I love wxGlade!
wxGlade http://wxglade.sourceforge.net/

You need to look at this documentation to code event handling.
wxWidgets http://www.wxwidgets.org/manuals/stable/wx_classesbycat.html

You can also try coding the GUI manually, but it is much easier to use
wxGlade.
wxPython http://wiki.wxpython.org/AnotherTutorial

Roy


On Sat, Mar 1, 2008 at 5:05 PM, Tim Chase <[EMAIL PROTECTED]>
wrote:

> > I'm certain there is an API for creating
> > GUI's but as far i can find it in the
> > http://docs.python.org/tut/tut.html
> > the only "gui" is in "Guido".
> >
> > What do i miss?
>
>
> The batteries-included GUI:
>
>   import tkininter
>
> Add-on solutions include wxPython, PythonCard and many others.  GIYF:
>
>   http://google.com/search?q=python+gui
>
> -tkc
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: [Python-3000] RELEASED Python 2.6a1 and 3.0a3

2008-03-01 Thread Martin v. Löwis
> As of 4:50 PM  EST, the links to Windows installers give 404 File Not 
> Found.
> 
> I gather that they are still in process,
> and notice that there is no public c.l.p. announcement. 

I just fixed that. The files were there; just the links were wrong.

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


Re: Pb with 2.5.2 & PyScripter

2008-03-01 Thread M�ta-MCI (MVP)
Hi!

Problem solved, after reset layouts.
Thanks, all!

Michel Claveau

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


Re: A python STUN client is ready on Google Code.

2008-03-01 Thread Tim Chase
> |I upload a new version. Add more print log into my code to help people
> | understand my program
> 
> Announcements should include a short paragraph explaining what the 
> announcement is about for those of us not in the know.  IE, what is 
> STUN? -- and therefore, what is a STUN client? 

I believe this STUN client refers to

http://en.wikipedia.org/wiki/Simple_traversal_of_UDP_over_NATs

which is used if both user A and user B are behind a NAT'ing 
(Network Address Translating) firewall, and need to talk directly 
with each other.

-tkc



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


Re: Where's GUI for Python?

2008-03-01 Thread Tim Chase
> I'm certain there is an API for creating
> GUI's but as far i can find it in the
> http://docs.python.org/tut/tut.html
> the only "gui" is in "Guido".
> 
> What do i miss?


The batteries-included GUI:

   import tkininter

Add-on solutions include wxPython, PythonCard and many others.  GIYF:

   http://google.com/search?q=python+gui

-tkc


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


Please test Phatch on Windows (was Re: ANN: Phatch = PHoto bATCH processor and renamer based on PIL)

2008-03-01 Thread SPE - Stani's Python Editor
I have been working the last couple of days purely on bug fixing and
to port the code of Phatch fully to Windows as there were many issues.
This has improved:
- Phatch can now create droplets on Windows (win32 extensions
required)
- Installed fonts are retrieved from the Windows registry
- Image file dialogs are now working correctly
- Missing icons are added (including a phatch.ico) and are now
displayed in the windows titlebars
- Image Inspector was missing a panel
- Preview in Image Inspector now displays correctly
- (...)

Besides that Phatch now features for all platforms:
- fonts can be defined with a nice dropdown autocomplete list
- drop down lists with convenient values in all actions
- the action masks now ships with some predefined masks (such as torn
edges)
- right click in the actions dialog box to see the source of an action
- View>Droplet nows shows the name of the action box rendered in the
logo
- Dutch translation is 100% complete

As such no new features have been added, but the user experience feels
much more polished now.

Please read *carefully* the installation instructions first:
http://photobatch.wikidot.com/install#toc6

People who have been using Phatch before should clear their font cache
(if it exists). Simply delete the file:
C:\Documents and Settings\Username\.phatch\fonts

I did the Phatch port on a Windows 2000 machine, so I am curious to
hear how Phatch works on Windows XP and Vista. I will fix any bug (as
far as possible) which is reported quickly in the next couple of days.

You can help translating Phatch here:
https://translations.launchpad.net/phatch/trunk/+pots/phatch

Thanks in advance,

Stani

On 18 feb, 15:58, "SPE - Stani's Python Editor"
<[EMAIL PROTECTED]> wrote:
> I'm pleased to announce the release ofPhatchwhich is a
> powerful batch processor and renamer.Phatchexposes a big part of the
> Python Imaging Library through an user friendly GUI. (It is using
> python-pyexiv2 to offer more extensive EXIF and IPTC support.)Phatch
> is not targeted at manipulating individual pictures (such as with
> Gimp), but repeating the same actions on hundreds or thousands of
> images.
>
> If you know PIL and have some nice recipes laying around, it is very
> easy to write plugins asPhatchgenerates the corresponding GUI
> automagically just like in Django. Any existings PIL scripts can be
> added very easily. Let me know if you want to contribute or have any
> questions.
>
> Homepage:http://photobatch.stani.be(free download link below)
> Tutorials:http://photobatch.wikidot.com/tutorials
> Translations:https://translations.launchpad.net/phatch/trunk/+pots/phatch
> License: GPLv3
> Screenshot:http://photobatch.wikidot.com/local--files/start/Screenshot-Phatch3d.jpg
> (the perspective and reflection is produced byPhatchitself)
>
> Phatchhas many features, like:
> - EXIF information inspector with thumbnail
> - limit jpeg file size when saving
> - tons of actions organized by tags (including perspective, round
> corners, shadow, reflection, ...)
> - console version (Phatchcan now run without a gui on servers)
> - batch rename and copy files based on exif metadata
> - data stamping (http://photobatch.wikidot.com)
> - online documentation wiki (http://photobatch.wikidot.com)
>
> Linux only features:
> - desktop or panel droplets on which images or folders can be dropped
> (will be ported to Windows & Mac)
> - Nautilus and desktop integration (with its own mime type and
> nautilus extension)
> - manpage with examples
>
> With python-pyexiv2 the following featues are added:
> - embedding the original EXIF and IPTC tags in the image
>
> All actions mostly have a separate pil function in their source code,
> so they could be read as a recipe book for PIL:
> * Auto Contrast - Maximize image contrast
> * Background - Put colour under transparent image
> * Border - Crop or add border to all sides
> * Brightness - Adjust brightness from black to white
> * Canvas - Crop the image or enlarge canvas without resizing the image
> * Colorize - Colorize grayscale image
> * Common - Copies the most common pixel value
> * Contrast - Adjust from grey to black & white
> * Convert Mode - Convert the color mode of an image (grayscale, RGB,
> RGBA or CMYK)
> * Copy - Copy image file
> * Effect - Blur, Sharpen, Emboss, Smooth, ...
> * Equalize - Equalize the image histogram
> * Fit - Downsize and crop image with fixed ratio
> * Grayscale - Fade all colours to gray
> * Invert - Invert the colors of the image (negative)
> * Maximum - Copies the maximum pixel value
> * Mask - Apply a transparency mask
> * Median - Copies the median pixel value
> * Minimum - Copies the minimum pixel value
> * Offset - Offset by distance and wrap around
> * Posterize - Reduce the number of bits of colour channel
> * Perspective - Shear 2d or 3d
> * Rank - Copies the rank'th pixel value
> * Reflect - Drops a reflection
> * Rename - Rename image file
> * Rotate - Rotate with random angle
> * Round - Round or crossed corners with var

Re: Pb with 2.5.2 & PyScripter

2008-03-01 Thread Colin J. Williams
Méta-MCI (MVP) wrote:
> Re!
> 
> An exemple. With this script:
>a=123
>b=456
>d=a+b+c
> (note than 'c' is not defined).
> 
> When I run, inside Pyscripter, the error-dialog is showed, and, one 
> second after, PyScripter is closed.
> This problem is present since Python 2.5.2.
> 
> I search, for know if it's a problem only on my computer, or a more 
> general problem.
> 
> Thanks by advance for your(s) answer(s).
> 
> @-salutations
I ran your script and an 
exception.NameError is reported.

I say OK to the error and repeat the 
run.  PyScripter is not closed.

This is with xp and Python 2.5.2

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


Re: PIL transparency gradient

2008-03-01 Thread SPE - Stani's Python Editor
On 1 mrt, 22:04, Allard Warrink <[EMAIL PROTECTED]> wrote:
> I would like to create a transparency gradient over an image using
> PIL. But I don't have a clue how to do this...
> Is there anyone out here who could give me some advise?

Phatch (PHoto & bATCH) is an application based on PIL. Its actions
contain many useful PIL recipes, such as applying a transparency
gradient to an image. You basically need to create an 1pxx256px
grayscale image which goes from 0 to 255. After that you can stretch
it to the image size and add it as an alpha channel. You'll find the
source code for this in the phatch/actions/mask.py Every action
contains a 'raw' PIL function that can work independently outside the
context of Phatch. This is by design, inspired by the MVC model in
which you could see PIL as the model and Phatch as the View.

You can get Phatch at:
http://photobatch.stani.be

Read first *carefully* the installation instructions for your
platform:
http://photobatch.wikidot.com/install

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


Re: A python STUN client is ready on Google Code.

2008-03-01 Thread Terry Reedy

"hawk gao" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|I upload a new version. Add more print log into my code to help people
| understand my program

Announcements should include a short paragraph explaining what the 
announcement is about for those of us not in the know.  IE, what is 
STUN? -- and therefore, what is a STUN client? 



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


Where's GUI for Python?

2008-03-01 Thread K Viltersten
I'm certain there is an API for creating
GUI's but as far i can find it in the
http://docs.python.org/tut/tut.html
the only "gui" is in "Guido".

What do i miss?

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


SV: Surprised by the command "del"

2008-03-01 Thread K Viltersten
>> I'm reading the docs and at 5.2 the del
>> statement is discussed. At first, i thought
>> i've found a typo but as i tried that 
>> myself, it turns it actually does work so.
>> 
>>   a = ["alpha", "beta", "gamma"]
>>   del a[2:2]
>>   a
>> 
>> Now, i expected the result to be that the
>> "beta" element has been removed. Obviously, 
>> Python thinks otherwise. Why?!
> 
> Remember that slices are specified as half-open 
> intervals. So a[m:n] includes m-n elements, 
> those indexed from m to n-1.

Got it. Thanks!

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


PIL transparency gradient

2008-03-01 Thread Allard Warrink
I would like to create a transparency gradient over an image using
PIL. But I don't have a clue how to do this...
Is there anyone out here who could give me some advise?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to subclass a built-in int type and prevent comparisons

2008-03-01 Thread Michael Torrie
[EMAIL PROTECTED] wrote:
> Tell Wall.  But why not [ 2, 3 ]>= 2?  Back to your question, another
> option is to not subclass.

Umm, no.  You need to actually read the posts before you respond to
them.  His question was whether or not to throw an exception in this
case.  He's *already* subclassed the type.

The first question was, should he throw an exception.  And given that
Python 3.0 will throw exceptions, he is justified in throwing exceptions
as well.  I have no idea what he would lose by throwing an exception.  I
have no idea how else he would do this.

His second question was, would his code for implementing __gt__ (and
throwing exceptions) be likely efficient.  That I cannot say.

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


Re: Pb with 2.5.2 & PyScripter

2008-03-01 Thread M�ta-MCI (MVP)
Hi!

Thank you for return.
I will uninstall+reinstall Pyscripter.

@-salutations
-- 
Michel Claveau

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


rpc shortcut

2008-03-01 Thread castironpi
RPC might be -really- easy.

Mixin class:

getattribute returns a remoting callable if ('name') is callable, or
in a special list.  On call, pack the parameters, execute locally, and
broadcast.  You'd need two mixins, BroadcasterMixin and ReceiverMixin,
but the same code can still run-- how can behavior depend on whether a
given class is listening or "talking" in a given instance?

Also, customize mixins: BcastMixin, RceiveMixin with ServerSideMixin,
ClientSideMixin, or BothSidesMixin, the first two executing state
change in one place, and informing of the new state, or independently,
opt'ly with some verification in worries of non-determinism.  Or,
perhaps, @ServerSide and @ClientSide decorations.

It sucks when bandwidth cost might depend on certain parameters-- big
state changes vs. big processing time vs. big parameter lists
comparatively, esp'ly when they aren't right as separate functions...
though do cf. multimethods for param. value checking on this:
@servside @params( 'i', lambda i: i> 100 ) def func( i ) / @cliside
@params( default ) def func( i ).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Surprised by the command "del"

2008-03-01 Thread Steve Holden
K Viltersten wrote:
> I'm reading the docs and at 5.2 the del
> statement is discussed. At first, i thought
> i've found a typo but as i tried that 
> myself, it turns it actually does work so.
> 
>   a = ["alpha", "beta", "gamma"]
>   del a[2:2]
>   a
> 
> Now, i expected the result to be that the
> "beta" element has been removed. Obviously, 
> Python thinks otherwise. Why?!
> 
> Elaboration:
> I wonder why such an unintuitive effect has
> been implemented. I'm sure it's for a very
> good reason not clear to me due to my
> ignorance. Alternatively - my expectations
> are not so intuitive as i think.   :)
> 
It deletes all the elements referred to by the slice. But since 2-2==0, 
there are zero elements in the slice, and the list is unchanged when all 
zero of them have been deleted:

 >>> a = ["alpha", "beta", "gamma"]
 >>> a[2:2]
[]
 >>>

You would have got the result you expected with

 del a[2]

or

del a[2:3]

or

 del a[-1]

or ...

Remember that slices are specified as half-open intervals. So a[m:n] 
includes m-n elements, those indexed from m to n-1.

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

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


Re: Surprised by the command "del"

2008-03-01 Thread castironpi
On Mar 1, 2:05 pm, "K Viltersten" <[EMAIL PROTECTED]> wrote:
> I'm reading the docs and at 5.2 the del
> statement is discussed. At first, i thought
> i've found a typo but as i tried that
> myself, it turns it actually does work so.
>
>   a = ["alpha", "beta", "gamma"]
>   del a[2:2]
>   a
>
> Now, i expected the result to be that the
> "beta" element has been removed. Obviously,
> Python thinks otherwise. Why?!
>
> Elaboration:
> I wonder why such an unintuitive effect has
> been implemented. I'm sure it's for a very
> good reason not clear to me due to my
> ignorance. Alternatively - my expectations
> are not so intuitive as i think.   :)

It's the Phillips vs. the flathead.  Is b in x[a:b:c] an endpoint or a
distance?

This is Python too; you're welcome to implement:
 - b means length
 - one-based indices
 - inclusive
 - b out of bounds exceptions

A slice object (a,b,c) is passed to
whatevercollection.__getitem__, .__setitem__, or .__delitem__.
-- 
http://mail.python.org/mailman/listinfo/python-list


Surprised by the command "del"

2008-03-01 Thread K Viltersten
I'm reading the docs and at 5.2 the del
statement is discussed. At first, i thought
i've found a typo but as i tried that 
myself, it turns it actually does work so.

  a = ["alpha", "beta", "gamma"]
  del a[2:2]
  a

Now, i expected the result to be that the
"beta" element has been removed. Obviously, 
Python thinks otherwise. Why?!

Elaboration:
I wonder why such an unintuitive effect has
been implemented. I'm sure it's for a very
good reason not clear to me due to my
ignorance. Alternatively - my expectations
are not so intuitive as i think.   :)

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


Re: pySQLite Insert speed

2008-03-01 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> I hav read on this forum that SQL coding (A) below is preferred over
> (B), but I find (B) is much faster (20-40% faster)
> 
> (A)
> 
> sqla= 'INSERT INTO DTABLE1 VALUES (%d, %d, %d, %f)'  %  values
> curs.execute(sqla)
> 
> (B)
>  pf= '?, ?, ?, ?'
> sqlxb= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf
> curs.execute( sqlxb, values )
> 
> Any intution on why (A) is slower?

You most certainly have not found that A is the preferred over B - the 
opposite is true. Using A will make you vulnerable against 
SQL-injection-attacks. B OTOH will ensure that the parameters are 
properly escaped or otherwise dealt with.

Regarding the intuition - that depends on what actually happens inside 
B. If B works in a way that it

  - converts arguments to strings

  - escapes these where necessary

  - builts one SQL-statement out of it

  - excutes the SQL

then B is slower than A because A is just string-interpolation, whereas 
B is sanitizing + string-interpolation. So it must be slower.

But a "sane" DB will instead directly use the SQL passed in B, and 
transmit the parameter as binary into the backend, resulting in more 
compact representation + lesser or now marshalling overhead plus 
possible query parsing overhead reduction due to cached execution plans. 
Which could explain B being more performant.

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


Re: why not bisect options?

2008-03-01 Thread Paul Rubin
Raymond Hettinger <[EMAIL PROTECTED]> writes:
> The sort() function guarantees that it calls the key function exactly
> once for each member of the list. 

That is a time-space tradeoff though, and it presupposes that it's
possible to write a key function.  Depending on the objects involved,
it could be that it's easier to write a comparison function than a
key function.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-01 Thread Paul Rubin
Lie <[EMAIL PROTECTED]> writes:
> I see, but the same arguments still holds true: the second line have
> an implicit side-effect of redefining x's type into Fractional type.
> If I were the designer of the language, I'd leave x's type as it is
> (as Num) and coerce x for current calculation only.

Num in Haskell is not a type, it is a class of types, i.e. if all you
know about x is that it is a Num, then its actual type is
indeterminate.  Types get inferred, they do not get coerced or
"redefined".  The compiler looks at expressions referring to x, to
deduce what x's type actually is.  If it is not possible to satisfy
all constraints simultaneously, then the compiler reports an error.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Import, how to change sys.path on Windows, and module naming?

2008-03-01 Thread Steve Holden
Jeremy Nicoll - news posts wrote:
> Jeremy Nicoll - news posts <[EMAIL PROTECTED]> wrote:
> 
>> If I understand correctly, when I import something under Windows, Python
>> searches the directory that the executing script was loaded from, then
>> other directories as specified in "sys.path".
> 
> Sorry to followup my own question, but I ran
> 
>  for p,q in enumerate(sys.path): print p, q
> 
> and got:
> 
> 0 C:\Documents and Settings\Laptop\My Documents\JN_PythonPgms
> 1 C:\Program Files\~P-folder\Python25\Lib\idlelib
> 2 C:\WINDOWS\system32\python25.zip
> 3 C:\Program Files\~P-folder\Python25\DLLs
> 4 C:\Program Files\~P-folder\Python25\lib
> 5 C:\Program Files\~P-folder\Python25\lib\plat-win
> 6 C:\Program Files\~P-folder\Python25\lib\lib-tk
> 7 C:\Program Files\~P-folder\Python25
> 8 C:\Program Files\~P-folder\Python25\lib\site-packages
> 9 C:\Program Files\~P-folder\Python25\lib\site-packages\win32
> 10 C:\Program Files\~P-folder\Python25\lib\site-packages\win32\lib
> 11 C:\Program Files\~P-folder\Python25\lib\site-packages\Pythonwin
> 
> Does every Windows user have: 2 C:\WINDOWS\system32\python25.zip
> in their sys.path?  What's the point of having a zip in the path?
> 
So that the files inside the zip can be imported as modules and 
packsges, of course.

> Also, looking in  C:\WINDOWS\system32\   I don't actually have a file called
> python25.zip, but I do have one called  python25.dll - so has something gone
> wrong in creation of sys.path?
> 
No. I'm not sure why the zip file is on there by default.

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

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


RELEASED Python 2.6a1 and 3.0a3

2008-03-01 Thread Barry Warsaw
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On behalf of the Python development team and the Python community, I'm  
happy to announce the first alpha release of Python 2.6, and the third  
alpha release of Python 3.0.

Python 2.6 is not only the next advancement in the Python 2 series, it  
is also a transitionary release, helping developers begin to prepare  
their code for Python 3.0.  As such, many features are being  
backported from Python 3.0 to 2.6.  It makes sense to release both  
versions in at the same time, the precedence for this having been set  
with the Python 1.6 and 2.0 releases.

During the alpha testing cycle we will be releasing both versions in  
lockstep, on a monthly release cycle.  The releases will happen on the  
last Friday of every month.  If this schedule works well, we will  
continue releasing in lockstep during the beta program.  See PEP 361  
for schedule details:

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

Please note that these are alpha releases, and as such are not  
suitable for production environments.  We continue to strive for a  
high degree of quality, but there are still some known problems and  
the feature sets have not been finalized.  These alphas are being  
released to solicit feedback and hopefully discover bugs, as well as  
allowing you to determine how changes in 2.6 and 3.0 might impact  
you.  If you find things broken or incorrect, please submit a bug  
report at

 http://bugs.python.org

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

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

and the Python 3.0 web site:

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

We are planning a number of additional alpha releases, with the final  
release schedule still to be determined.

Enjoy,
- -Barry

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

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

iQCVAwUBR8mlu3EjvBPtnXfVAQKePAQAgx6w9wztfJaSWkbKrbwur2U6t6o5aIY5
pyMa00CZWY06p8099BztcSjgp5rKrd6/9V7cJ0NP7NLZ+tz20uRfyI8uqoIYBIWC
ibJay6SSnzgOQM3PRIJV/K/m0dVPPPVD1LDnoEvuu+cKUpV434yHdgWkMPswsxUd
fLydrXABlOM=
=l6aj
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Import, how to change sys.path on Windows, and module naming?

2008-03-01 Thread Jeremy Nicoll - news posts
Jeremy Nicoll - news posts <[EMAIL PROTECTED]> wrote:

> If I understand correctly, when I import something under Windows, Python
> searches the directory that the executing script was loaded from, then
> other directories as specified in "sys.path".

Sorry to followup my own question, but I ran

 for p,q in enumerate(sys.path): print p, q

and got:

0 C:\Documents and Settings\Laptop\My Documents\JN_PythonPgms
1 C:\Program Files\~P-folder\Python25\Lib\idlelib
2 C:\WINDOWS\system32\python25.zip
3 C:\Program Files\~P-folder\Python25\DLLs
4 C:\Program Files\~P-folder\Python25\lib
5 C:\Program Files\~P-folder\Python25\lib\plat-win
6 C:\Program Files\~P-folder\Python25\lib\lib-tk
7 C:\Program Files\~P-folder\Python25
8 C:\Program Files\~P-folder\Python25\lib\site-packages
9 C:\Program Files\~P-folder\Python25\lib\site-packages\win32
10 C:\Program Files\~P-folder\Python25\lib\site-packages\win32\lib
11 C:\Program Files\~P-folder\Python25\lib\site-packages\Pythonwin

Does every Windows user have: 2 C:\WINDOWS\system32\python25.zip
in their sys.path?  What's the point of having a zip in the path?

Also, looking in  C:\WINDOWS\system32\   I don't actually have a file called
python25.zip, but I do have one called  python25.dll - so has something gone
wrong in creation of sys.path?

-- 
Jeremy C B Nicoll - my opinions are my own.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-01 Thread Anand Patil
Not sure if this is common knowledge yet but Sympy,
http://code.google.com/p/sympy, has a rational type.

In [2]: from sympy import *

In [3]: Rational(21,4)
Out[3]: 21/4

In [4]: Rational(21,4)+Rational(3,4)
Out[4]: 6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Import, how to change sys.path on Windows, and module naming?

2008-03-01 Thread Steve Holden
Jeremy Nicoll - news posts wrote:
> If I understand correctly, when I import something under Windows, Python
> searches the directory that the executing script was loaded from, then other
> directories as specified in "sys.path".
> 
Technically, I believe it just puts the script's directory at the start 
of sys.path, then uses sys.path as its module search path.

> I assume there are standard locations inside my installed Python - in my
> case inside:  C:\Program Files\~P-folder\Python25  - where I could put my
> modules and they'd automatically be found?  But even if that's the norm, I
> don't want to put my own modules in such directories, partly because a
> uninstall or reinstall or upgrade of Python might lose my stuff, and partly
> because I don't believe in mixing distributed code with home-grown code. 
> 
There's Lib/site-packages, which is where third-party code normally goes.

> However I'm quite happy to have a line or three of code to alter  sys.path 
> to suit my set-up, if that's a normal way to handle this problem.  Where
> does one do that?
> 
Take a look at site.py, and see that it runs sitecustomize.py when present.

> 
> Also, I presume that there's a risk that the module name that I give to any
> of my utilities will clash with a present or future standard module's name.
> Does that mean that I should give my own modules names like "JNfoo" rather
> than "foo", etc?  Or something like "JNutils.foo"?
> 
You can always be sure your own modules will be loaded in preference to 
shadowing system modules if you put your directories on the path before 
the standard directories, but most people don't spend a lot of time 
worrying about this.

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

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


Re: Beginner's assignment question

2008-03-01 Thread castironpi
On Mar 1, 10:07 am, Lorenzo Gatti <[EMAIL PROTECTED]> wrote:
> On Mar 1, 3:39 pm, Schizoid Man <[EMAIL PROTECTED]> wrote:
>
> > As in variable assignment, not homework assignment! :)
>
> > I understand the first line but not the second of the following code:
>
> > a, b = 0, 1
> > a, b = b, a + b
>
> > In the first line a is assigned 0 and b is assigned 1 simultaneously.
>
> > However what is the sequence of operation in the second statement? I;m
> > confused due to the inter-dependence of the variables.
>
> The expressions of the right of the assignment operator are evaluated
> before assigning any new values, to the destinations on the left side
> of the assignment operator.
> So substitutig the old values of a and b the second assignment means
>
> a, b = 0, 0 + 1
>
> Simplifying the Python Reference Manual ("6.3 Assignment Statements")
> a little :
>
> assignment_stmt ::= target_list "="+ expression_list
>
> An assignment statement evaluates the expression list (remember that
> this can be a single expression or a comma-separated list, the latter
> yielding a tuple) and assigns the single resulting object to each of
> the target lists, from left to right.
>
> [...]
>
> WARNING: Although the definition of assignment implies that overlaps
> between the left-hand side and the right-hand side are `safe' (for
> example "a, b = b, a" swaps two variables), overlaps within the
> collection of assigned-to variables are not safe! For instance, the
> following program prints "[0, 2]":
>
> x = [0, 1]
> i = 0
> i, x[i] = 1, 2
> print x
>
> Lorenzo Gatti

If you understand

a, b, c= 1, 2, 3

Then

a, b, c= 1, 2, 3+1

is the next step.

About terminology, you might get some weird glances from the vets. if
you say 'a assigned to 0', instead of '0 assigned to a'.  Of course,
it may be more opinion than some vet. natural language speakers
realize, that is whether it's only convention or not, if one says 'I
went to the store' instead of 'the store went to me'-- same picture,
except (cf. relativity) how much force the store applied to travel--
which doesn't show up in every story problem anyway), hence Williams's
term '0 is assigned to a', and don't forget, they're on side effects
here, hence Gatti's warning.  Put another way, the thing on the right
'evaluates' to something.

There may be some 'agent-patient' confusion here but 'a' isn't
really 'assigned' in any deep sense, though it is 'declared' -in- that
statement too.  'The interpreter obtains space for a' (the space word
is deep!, as in 'time-space trade-off') and 'The interpreter writes 0
in a's space' are both pretty literal.  You can say, 'a is assigned
the value 0', just not 'a is assigned -to- it.'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pb with 2.5.2 & PyScripter

2008-03-01 Thread Ricardo Aráoz
Méta-MCI (MVP) wrote:
> Re!
> 
> An exemple. With this script:
> a=123
> b=456
> d=a+b+c
> (note than 'c' is not defined).
> 
> When I run, inside Pyscripter, the error-dialog is showed, and, one 
> second after, PyScripter is closed.
> This problem is present since Python 2.5.2.
> 
> I search, for know if it's a problem only on my computer, or a more 
> general problem.
> 
> Thanks by advance for your(s) answer(s).
> 
> @-salutations

Just tried it with PyScripter v 1.9.5.0 and Python 2.5.2.
Error dialog showed but PyScripter did not close.

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


Re: SQLLITE

2008-03-01 Thread castironpi
On Mar 1, 11:54 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> nexes schrieb:
>
> > Hello All,
> >    I am having a minor problem when I try and do this:
> >       c.execute("insert into [tblTranscripts] (MovieID,Transcript)
> > Values(" + movieID + ",'" + formatText + "');")   (don't even bother
> > commenting of the sql style I know its bad form but this is a simple
> > script). Whenever I try and do the insert I get table not found,
> > however when I perform the sql through sqlite's command line program
> > (the sql is outputted via a print statement) it works fine.  Any ideas?
>
> No, and without more context nobody will have. Does working with the
> table with other statments work, how do you connect the DB, are you sure
> you really use the same DB-file and so forth.
>
> Diez

There's a number of things it could be-- narrow it down a little more
(for the reader).  Beginner stuff is usually forgetting 'use
moviedata'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SQLLITE

2008-03-01 Thread Diez B. Roggisch
nexes schrieb:
> Hello All,
>I am having a minor problem when I try and do this:
>   c.execute("insert into [tblTranscripts] (MovieID,Transcript)
> Values(" + movieID + ",'" + formatText + "');")   (don't even bother
> commenting of the sql style I know its bad form but this is a simple
> script). Whenever I try and do the insert I get table not found,
> however when I perform the sql through sqlite's command line program
> (the sql is outputted via a print statement) it works fine.  Any ideas?

No, and without more context nobody will have. Does working with the 
table with other statments work, how do you connect the DB, are you sure 
you really use the same DB-file and so forth.

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


Re: tcp functions

2008-03-01 Thread Diez B. Roggisch
Gif schrieb:
> is there a module for tcp functions or any other quick way to connect,
> listen, send and recieve from tcp?
> thanks in advance

Reading the docs helps - hint: module "socket".

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


Re: pySQLite Insert speed

2008-03-01 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Steve, I want to make sure I understand. My test code is below, where
> ph serves as a placeholder. I am preparing for a case where the number
> of ? will be driven by the length of the insert record (dx)
> 
> dtable= 'DTABLE3'
> print 'Insert data into table  %s,  version #3' % dtable
> ph= '?, ?, ?, ?'
> sqlx= 'INSERT INTO %s VALUES ( %s ) ' % (dtable,ph)
> t0a=time.time()
> for dx in d1:
>   curs1.execute(sqlx,dx)
> print (time.time()-t0a)
> print curs1.lastrowid
> conn1.commit()
> 
> I think you are saying that sqlx is re-evaluated in each loop, i.e.
> not the same as pure hard coding of
> sqlx= 'INSERT INTO DTABLE3 VALUES ( ?, ?, ?, ? ) '
> Is that right? 

Yes. If the sql is constant then you would be performing an unnecessary 
computation inside the loop. Not a biggie, but it all takes time. Is the 
loop above your original code? If so I was wrong about the loop.

> Hence (if I understand python convention), this can be
> solved by adding
> sqlx= copy.copy(sqlx)
> before the looping. And in tests adding this step saved about 5-10% in
> time.
> 
Now this I don;t really understand at all. What's the point of trying to 
replace sqlx with a copy of itself? Perhaps if you explained what you 
hope this will achieve I could comment more intelligently.

> And yes, I can see why (B) is always better from a security
> standpoint.  The python solutions for problems such as there are a
> great help for people like me, in the sense that the most secure way
> does not have a speed penalty (and in this case is 3-4x faster).

Yes, it's a real win-win. Since both the table and the number of 
arguments appear to be variable one possible solution is to build a dict 
that would allow you to look up the right SQL using the table name. So, 
suppose you have the following tables and number of arguments:

tables = (("table1", 3),
   ("table2", 5),
   ("table3", 2)
  )

you could create a suitable dict as (untested):

tdict = {}
for tbl, ct in tables:
 tdict[tbl] = "INSERT INTO %s VALUES (%s)" % \
 (tbl, ", ".join(["?"] * ct))

Then you can use the table to look up the right SQL, quite a fast 
operation compared with actually building it.

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

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


tcp functions

2008-03-01 Thread Gif
is there a module for tcp functions or any other quick way to connect,
listen, send and recieve from tcp?
thanks in advance
-- 
http://mail.python.org/mailman/listinfo/python-list


Import, how to change sys.path on Windows, and module naming?

2008-03-01 Thread Jeremy Nicoll - news posts
If I understand correctly, when I import something under Windows, Python
searches the directory that the executing script was loaded from, then other
directories as specified in "sys.path".

I assume there are standard locations inside my installed Python - in my
case inside:  C:\Program Files\~P-folder\Python25  - where I could put my
modules and they'd automatically be found?  But even if that's the norm, I
don't want to put my own modules in such directories, partly because a
uninstall or reinstall or upgrade of Python might lose my stuff, and partly
because I don't believe in mixing distributed code with home-grown code. 

However I'm quite happy to have a line or three of code to alter  sys.path 
to suit my set-up, if that's a normal way to handle this problem.  Where
does one do that?


Also, I presume that there's a risk that the module name that I give to any
of my utilities will clash with a present or future standard module's name.
Does that mean that I should give my own modules names like "JNfoo" rather
than "foo", etc?  Or something like "JNutils.foo"?

-- 
Jeremy C B Nicoll - my opinions are my own.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pb with 2.5.2 & PyScripter

2008-03-01 Thread M�ta-MCI (MVP)
Re!

An exemple. With this script:
a=123
b=456
d=a+b+c
(note than 'c' is not defined).

When I run, inside Pyscripter, the error-dialog is showed, and, one 
second after, PyScripter is closed.
This problem is present since Python 2.5.2.

I search, for know if it's a problem only on my computer, or a more 
general problem.

Thanks by advance for your(s) answer(s).

@-salutations
-- 
Michel Claveau



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


Re: at-exit-thread

2008-03-01 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> On Feb 29, 1:55 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] schrieb:
>>
>>> The Python main interpreter has an at-exit list of callables, which
>>> are called when the interpreter exits.  Can threads have one?  What's
>>> involved, or is the best way merely to subclass Thread?
>> Is that some sort of trick-question?
>>
>> class MyThread(Thread):
>>
>> def run(self):
>> while some_condition:
>>  do_something()
>> do_something_after_the_thread_ends()
>>
>> The atexit stuff is for process-termination which is/may be induced by
>> external signals - which is the reason why these callbacks extist.
>> Threads don't have that, thus no need.
> 
> That depends.  If a thread adds an object it creates to a nonlocal
> collection, such as a class-static set, does it have to maintain a
> list of all such objects, just to get the right ones destroyed on
> completion?  Processes destroy their garbage hassle-free; how can
> threads?  And don't forget Thread.run( self ) in the example, if
> anyone ever wants to make use of the 'target' keyword.

That is both totally unrelated to the original question and plain wrong. 
Processes don't destroy their garbage themselves, not automagically or 
anything. If you _want_, you can put atexit-handlers that do clean up 
some stuff, but you'll have to equip them with the necessary context 
yourself.

And a

kill -9 

won't run *anything* of your own code.

The OS is eventually responsible for cleaning up.

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


Re: How about adding rational fraction to Python?

2008-03-01 Thread Lie
On Mar 1, 11:23 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
(snip)
> But the type of `x` must be specialized somehow.  `x` doesn't start as
> `Int` or `Integer` but the very generic and AFAIK abstract type class `Num`.
>
> After seeing the second line the compiler finds an implementation for `+`
> and the type class `Fractional` for both operands and now thinks `x` must
> be a `Fractional`, a subclass of `Num`.
>
> Then comes the third line with `length` returning an `Int` and the
> `Fractional` `x` but there is no implementation for a `+` function on
> those types.

I see, but the same arguments still holds true: the second line have
an implicit side-effect of redefining x's type into Fractional type.
If I were the designer of the language, I'd leave x's type as it is
(as Num) and coerce x for current calculation only.
-- 
http://mail.python.org/mailman/listinfo/python-list


SQLLITE

2008-03-01 Thread nexes
Hello All,
   I am having a minor problem when I try and do this:
  c.execute("insert into [tblTranscripts] (MovieID,Transcript)
Values(" + movieID + ",'" + formatText + "');")   (don't even bother
commenting of the sql style I know its bad form but this is a simple
script). Whenever I try and do the insert I get table not found,
however when I perform the sql through sqlite's command line program
(the sql is outputted via a print statement) it works fine.  Any ideas?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-01 Thread Marc 'BlackJack' Rintsch
On Fri, 29 Feb 2008 17:29:32 -0800, Lie wrote:

> On Feb 28, 10:00 am, Paul Rubin  wrote:
>> More examples:
>>
>>x = 1
>>y = len(s) + x
>>
>> => ok, decides that x is an int
>>
>>x = 1
>>y = x + 3.0
>>
>> => ok, decides that x is a float
>>
>>x = 1
>>y = x + 3.0
>>z = len(s) + x
>>
>> => forbidden, x cannot be an int and float at the same time.
>>
>> > I am so glad you're not the designer of Python.
>>
>> This is how Haskell works and I don't notice much complaints about it.
> 
> Ok, that means the line "y = x + 3.0" have a side effect of "x =
> float(x)"? I think I would say that is an implicit behavior.

But the type of `x` must be specialized somehow.  `x` doesn't start as
`Int` or `Integer` but the very generic and AFAIK abstract type class `Num`.

After seeing the second line the compiler finds an implementation for `+`
and the type class `Fractional` for both operands and now thinks `x` must
be a `Fractional`, a subclass of `Num`.

Then comes the third line with `length` returning an `Int` and the
`Fractional` `x` but there is no implementation for a `+` function on
those types.

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


Re: Beginner's assignment question

2008-03-01 Thread Lorenzo Gatti
On Mar 1, 3:39 pm, Schizoid Man <[EMAIL PROTECTED]> wrote:
> As in variable assignment, not homework assignment! :)
>
> I understand the first line but not the second of the following code:
>
> a, b = 0, 1
> a, b = b, a + b
>
> In the first line a is assigned 0 and b is assigned 1 simultaneously.
>
> However what is the sequence of operation in the second statement? I;m
> confused due to the inter-dependence of the variables.

The expressions of the right of the assignment operator are evaluated
before assigning any new values, to the destinations on the left side
of the assignment operator.
So substitutig the old values of a and b the second assignment means

a, b = 0, 0 + 1

Simplifying the Python Reference Manual ("6.3 Assignment Statements")
a little :

assignment_stmt ::= target_list "="+ expression_list

An assignment statement evaluates the expression list (remember that
this can be a single expression or a comma-separated list, the latter
yielding a tuple) and assigns the single resulting object to each of
the target lists, from left to right.

[...]

WARNING: Although the definition of assignment implies that overlaps
between the left-hand side and the right-hand side are `safe' (for
example "a, b = b, a" swaps two variables), overlaps within the
collection of assigned-to variables are not safe! For instance, the
following program prints "[0, 2]":

x = [0, 1]
i = 0
i, x[i] = 1, 2
print x

Lorenzo Gatti




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


Re: Beginner's assignment question

2008-03-01 Thread Colin J. Williams
Schizoid Man wrote:
> As in variable assignment, not homework assignment! :)
> 
> I understand the first line but not the second of the following code:
> 
> a, b = 0, 1
> a, b = b, a + b
> 
> In the first line a is assigned 0 and b is assigned 1 simultaneously.
> 
> However what is the sequence of operation in the second statement? I;m 
> confused due to the inter-dependence of the variables.
In the second line a now points to the 
value 1 and b points to 1 (the sum of 
zero and one) in a unitary operation 
(i.e. in turn, but effectively 
simultaneously).

You might disassemble the code to see 
the sequence.

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


Re: Pb with 2.5.2 & PyScripter

2008-03-01 Thread Colin J. Williams
Méta-MCI (MVP) wrote:
> Hi, all!
> 
> Since the install of Python 2.5.2, Pyscripter (1.9.9.1) close for each 
> error.
> Is it only me?  Or another guys have the same thing?
> 
> @-salutations
> 
> Michel Claveau
> 
> 
> 
> 
Could you be more explicit please?

I use PyScripter and do not have this 
problem.

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



Re: pySQLite Insert speed

2008-03-01 Thread mdboldin
Steve, I want to make sure I understand. My test code is below, where
ph serves as a placeholder. I am preparing for a case where the number
of ? will be driven by the length of the insert record (dx)

dtable= 'DTABLE3'
print 'Insert data into table  %s,  version #3' % dtable
ph= '?, ?, ?, ?'
sqlx= 'INSERT INTO %s VALUES ( %s ) ' % (dtable,ph)
t0a=time.time()
for dx in d1:
  curs1.execute(sqlx,dx)
print (time.time()-t0a)
print curs1.lastrowid
conn1.commit()

I think you are saying that sqlx is re-evaluated in each loop, i.e.
not the same as pure hard coding of
sqlx= 'INSERT INTO DTABLE3 VALUES ( ?, ?, ?, ? ) '
Is that right?  Hence (if I understand python convention), this can be
solved by adding
sqlx= copy.copy(sqlx)
before the looping. And in tests adding this step saved about 5-10% in
time.

And yes, I can see why (B) is always better from a security
standpoint.  The python solutions for problems such as there are a
great help for people like me, in the sense that the most secure way
does not have a speed penalty (and in this case is 3-4x faster).
-- 
http://mail.python.org/mailman/listinfo/python-list


Beginner's assignment question

2008-03-01 Thread Schizoid Man
As in variable assignment, not homework assignment! :)

I understand the first line but not the second of the following code:

a, b = 0, 1
a, b = b, a + b

In the first line a is assigned 0 and b is assigned 1 simultaneously.

However what is the sequence of operation in the second statement? I;m 
confused due to the inter-dependence of the variables.
-- 
http://mail.python.org/mailman/listinfo/python-list


Problems building 2.5.1 on AIX

2008-03-01 Thread Roy Smith
I've got an AIX-5.2 box that I'm trying to build Python 2.5.1 on.  
Configure dies pretty much immediately:

hasty:Python-2.5.1$ CC=/usr/vacpp/bin/cc_r ./configure --without-gcc
checking MACHDEP... aix5
checking EXTRAPLATDIR... 
checking for --without-gcc... yes
checking for gcc... cc
checking for C compiler default output file name... configure: error: C 
compiler cannot create executables
See `config.log' for more details.

I get the same result with or without the --without-cgg.  There's nothing 
obvious in config.log (not that I can ever make much sense out of the 
gibberish configure generates).

Any ideas?
-- 
http://mail.python.org/mailman/listinfo/python-list


UponAcquiring synchro. class

2008-03-01 Thread castironpi
from __future__ import with_statement
'''
3)  upon_acquiring( lockA, lockB )( function, *ar, **kwar )

upon_acquiring spawns new thread upon acquiring locks A and B.  Locks
may be specified in any order, as none is acquired until all are free.

The options to spawn a new thread upon call, lock, and not release
until "it's its turn"; just block until then; and vary honoring order
are open.

6) @with_self
Prepends the function object to itself to the parameter list

'''
'''
a lockA lockB
b lockA lockB
c lockA lockB
d lockA lockC
e lockB lockD
f lockE lockF

assert a< b
assert b< c
assert c< d
assert c< e
assert f in.
'''
'''
A  (A,B)1 (A,C)2 (A,B)3
B  (A,B)1 (A,B)3
C  (A,C)2 (C,D,E)4
D  (C,D,E)4
E  (C,D,E)4
a.lock: A, a.state: Free, a.waiters: [ X1(a,b), X2(a,c), X3(a,b) ]
b.lock: B, b.state: Free, b.waiters: [ X1(a,b), X3(a,b) ]
c.lock: C, c.state: Free, X3.waiters: [ X2(a,c), X4(c,d,e) ]
d.lock: D, d.state: Free, X3.waiters: [ X4(c,d,e) ]
e.lock: E, e.state: Free, X3.waiters: [ X4(c,d,e) ]

acq a,b
x1= a,b
a.waiters+= x1
b.waiters+= x1
#same as
if a.state is free and b.state is free:
  a.state= taken
  b.state= taken
  a.waiters-= x1
  b.waiters-= x1
  a.lock.release() #acq?
  b.lock.release() #acq?
  x1.lock.release()
acq a,c
x2= a,c
a.waiters+= x2
c.waiters+= x2
if a.state is free and c.state is free:
  a.state= taken
  c.state= taken
  a.waiters-= x2
  c.waiters-= x2
  a.lock.release() #acq?
  c.lock.release() #acq?
  x2.lock.release()
acq a,b
x3= a,b
a.waiters+= x3
b.waiters+= x3
acq c,d,e
x4= c,d,e
c.waiters+= x4
d.waiters+= x4
e.waiters+= x4
'''

from thread import start_new_thread
from threading import Lock, Thread, Event
import time
from functools import partial

class LockDeps:
def __init__( self, lock, state, waiters ):
self.lock, self.state, self.waiters= \
lock, state, waiters
class LockSet:
#ok to use them elsewhere, just gets in line.
def __init__( self, *locks ):
self._locks= locks
self._lock= Lock()
self._lock.acquire()
self._remains= set( locks )
self._doneevt= Event()
self.th= None
self.retval= None
def release( self, *locks ):
for lock in locks:
lock.release()
self._remains.remove( lock )
def releaseall( self ):
for lock in self._remains:
lock.release()
self._remains.clear()

class UponAcquiring:
def __init__( self ):
self._deps= {}
self._oplock= Lock()
def acq( self, *locks ):
lckset= LockSet( *locks )
return partial( self._enqueue, lckset )
def _enqueue( self, lckset, fun, *ar, **kwar ):
with self._oplock:
for lock in lckset._locks:
dep= self._deps.get( lock )
if None is dep:
dep= LockDeps( lock, False, [] )
self._deps[ lock ]= dep
dep.waiters.append( lckset )
th= Thread( target= self._functhd,
args= ( lckset, fun )+ ar,
kwargs= kwar )
lckset.th= th
th.start()
self._analyze( lckset )
return lckset
def _functhd( self, lckset, fun, *ar, **kwar ):
try:
with lckset._lock:
lckset.retval=\
fun( lckset, *ar, **kwar )
lckset._doneevt.set()
finally:
with self._oplock:
lckset.releaseall()
for lock in lckset._locks:
self._deps[ lock ].state= False
self._analyze( lckset )
def _analyze( self, lckset ):
with self._oplock:
for lock in lckset._locks:
dep= self._deps[ lock ]
if dep.state: continue
for lckset in dep.waiters:
assert lock in lckset._locks
for lock2 in lckset._locks:
if self._deps[  lock2 ].state:
break
else:
for lock2 in lckset._locks:
dep2= self._deps[ lock2 ]
dep2.state= True
assert dep2.waiters.count(
lckset )== 1
dep2.waiters.remove(
lckset )
lock2.acquire()
lckset._lock.release()
break

results= []
ver= results.index
lcksets= set()
import random
from sys import stdout
def callback( locks, i ):
stdout.write( 'cb%i '% i )
time.sleep( random.uniform( 0, .01 ) )
results.append( i )
if random.choice( [ False, True ] ):
locks.releaseall()
#if random.random()< 0.1:
#   raise Exception()

while 1:
class Case1:
lockA, lockB, lockC= Lock(), Lock(), Lock()
lockD, lockE, lockF= Lock(), Lock(), Lock()
a= ( lockA, lockB )
b= ( lockA, lockB )
c= ( lockA, 

Re: joining strings question

2008-03-01 Thread patrick . waldo
>def category_iterator(source):
>  source = iter(source)
>  try:
>while True:
>  item = source.next()

This gave me a lot of inspiration.  After a couple of days of banging
my head against the wall, I finally figured out a code that could
attach headers, titles, numbers, and categories in their appropriate
combinations--basically one BIG logic puzzle.

It's not the prettiest thing in the world, but it works.  If anyone
has a better way to do it, then I'll be all ears.  Anyways, thank you
all for your input, it helped me think outside the box.

import re

data = ['RULES', 'Approval and Promulgation of Air Quality
Implementation Plans:', 'Illinois; Revisions to Emission Reduction
Market System, ', '11042 [E8-3800]', 'E8-3800.pdf', 'Ohio; Oxides of
Nitrogen Budget Trading Program; Correction, ', '11192 [Z8-2506]',
'Z8-2506.pdf', 'NOTICES', 'Agency Information Collection Activities;
Proposals, Submissions, and Approvals, ', '11108-0 [E8-3934]',
'E8-3934.pdf', 'Data Availability for Lead National Ambient Air
Quality Standard Review, ', '0-1 [E8-3935]', 'E8-3935.pdf',
'Environmental Impacts Statements; Notice of  Availability, ', '2
[E8-3917]', 'E8-3917.pdf']

NOTICES = re.compile(r'NOTICES')
RULES = re.compile(r'RULES')
TITLE = re.compile(r'[A-Z][a-z].*')
NUM = re.compile(r'\d.*')
PDF = re.compile(r'.*\.pdf')

counted = []
sorted = []
title = []
tot = len(data)
x=0
while x < tot:
try:
item = data[x]
title = []
if NOTICES.match(item) or RULES.match(item):
module = item
header = ''
if TITLE.match(data[x+1]) and TITLE.match(data[x+2]) and
NUM.match(data[x+3]):
#Header
header = data[x+1]
counted.append(data[x+1])
sorted.append(data[x+1])
#Title
counted.append(data[x+2])
sorted.append(data[x+2])
#Number
counted.append(data[x+3])
sorted.append(data[x+3])
title.append(''.join(sorted))
print title, module
print
sorted = []
x+=1
elif TITLE.match(data[x+1]) and NUM.match(data[x+2]):
#Title
counted.append(data[x+1])
sorted.append(data[x+1])
#Number
counted.append(data[x+2])
sorted.append(data[x+2])
title.append(''.join(sorted))
print title, module
print
sorted = []
x+=1
else:
print item, "strange1"
break
x+=1
else:
if item in counted:
x+=1
elif PDF.match(item):
x+=1
elif TITLE.match(data[x]) and TITLE.match(data[x+1]) and
NUM.match(data[x+2]):
#Header
header = data[x]
counted.append(data[x])
sorted.append(data[x])
#Title
counted.append(data[x+1])
sorted.append(data[x+1])
#Number
counted.append(data[x+2])
sorted.append(data[x+2])
title.append(''.join(sorted))
sorted = []
print title, module
print
x+=1
elif TITLE.match(data[x]) and NUM.match(data[x+1]):
#Title
sorted.append(header)
counted.append(data[x])
sorted.append(data[x])
#Number
counted.append(data[x+1])
sorted.append(data[x+1])
title.append(''.join(sorted))
sorted = []
print title, module
print
x+=1
else:
print item, "strange2"
x+=1
break
except IndexError:
break
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why not bisect options?

2008-03-01 Thread rbossy
Selon Raymond Hettinger <[EMAIL PROTECTED]>:

> [Robert Bossy]
> > I thought it would be useful if insort and consorts* could accept the
> > same options than list.sort, especially key and cmp.
>
> If you're going to do many insertions or searches, wouldn't it be
> *much* more efficient to store your keys in a separate array?
>
> The sort() function guarantees that it calls the key function exactly
> once for each member of the list.  With and bisect/insort, successive
> searches can call the key function over and over again with the same
> value.

Yeah, sure. Thanks for pointing that out.

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


Re: invert or not ?

2008-03-01 Thread Steve Holden
Stef Mientki wrote:
> hello,
> 
> from the manual I read that a bitwise inversion should be done by invert.
> But from some experiments I see that not works equally well.
> Is this coincidence ?
> 
> (The disadvantage of invert is that I've to import operators)
> 
Bitwise inversion is performed by the "~" operator. I think your 
experimentation has been inadequate:

 >>> for i in range(-1, 1):
... if (not i) == (~i):
... print i
...
-1
 >>>

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

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


ANN: eric 4.1.1 released

2008-03-01 Thread Detlev Offenbach
Hi,

eric4 4.1.1 has been released today. This release fixes a few bugs
reported 
since the last release.

As usual it is available via
http://www.die-offenbachs.de/eric/index.html.

Please note, that the first stable release of the Rope refactoring plugin
was 
released as well.

What is eric?
-
Eric is a Python (and Ruby) IDE with all batteries included. It is
expandable via a plugin architecture. These plugins are downloadable
separately.

Regards,
Detlev
-- 
Detlev Offenbach
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


SV: SV: Running test01.py under Windows (basic level)

2008-03-01 Thread K Viltersten
 def bloppA ():
 print "a very advanced piece of code"
>>>
>>> go to File -> Open, open your saved file,
>>> and use the Run menu (or press F5).
>>
>> When i try that i get this.
>>
> == RESTART ===
>
>>
>> And nothing more. Do i use wrong "print"?!
> 
> You *defined* a function, but aren't *executing* 
> it. Append a line:
> 
> bloppA()
> 
> and try again.


Rookie mistake. Thank you.

-- 
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


SV: SV: Running test01.py under Windows (basic level)

2008-03-01 Thread K Viltersten

>> There will be poking around with %PATH%, i can
>> tell. Never liked to do that under Windows.
>
> No need to do that... Create an "alias.txt" file containing: 
> python=c:\path\to\your\python.exe $*
> Execute (once, logged as administrator):
> reg add "HKLM\SOFTWARE\Microsoft\Command Processor"
>   /v AutoRun /t REG_SZ /d
>   "doskey /macrofile=path\to\your\alias.txt"
> Open a new cmd console. Typing python is enough to invoke the interpreter.
> Documentation for the DOSKEY command: 
> http://technet2.microsoft.com/WindowsServer/en/library/f7f45601-5178-48c6-9219-51bd6f7abd3f1033.mspx
>
> If you don't like the above recipe, create a "python.cmd" file containing:
> @c:\path\to\your\python.exe %*
> and save it somewhere in your PATH.

It worked. Thanks!

>>> have you worked out the Tutorial?
>>
>> Not yet. I started off using some small things.
>> I tend to learn by doing. Or rather making. A
>> lot of errors, that is.   :)
>
> At least overview it. Python syntax is very clear and legible, so probably 
> you can figure yourself a lot of things, but there are some important 
> topics that you have to know and are explained in the Tutorial. It isn't 
> very long.

Naa, reading tutorials is for idiots... You can
answer my questions instead. It's not like you've
got anything better to do. I bet you've read the
tutorial, haven't you?

(a period of awkward silence...)

(a short while of WTF?!)

Oh, ah! This guy was joking. Pfew...

Yes, i was definitely joking here.   :)
I do intend to go through the tutorial and i do
deeply appreciate all the help i've received/ i'll
receive. If all goes the way i hope, i'll be at a
new project soon and it's written in Python. Great
opportunity to learn it, right?

By the way - thanks!

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


Re: Getting a free TCP port & blocking it

2008-03-01 Thread theneb
On Feb 29, 11:11 pm, Tim Roberts <[EMAIL PROTECTED]> wrote:
> theneb <[EMAIL PROTECTED]> wrote:
> >Hi all,
> >I'm attempting to block a TCP port from any other application from
> >using it until I free it from python, this is so that:
> >1). Generate a random free user-space port
> >2). Generate the script for the external program with the port
> >3). Free the port before external program execution.
>
> What's the point?  Why can't the actual user of the port create the port,
> and then notify the other side of the port number?
The system the app will run on will be creating three instances of the
external application, the python app has to keep track of which port
the external app is running on.

>
> And why don't you just specify a port number of 0 and let the system assign
> you a free port number?
> --
> Tim Roberts, [EMAIL PROTECTED]
> Providenza & Boekelheide, Inc.

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


  1   2   >