Re: mod_python Unable to create file

2008-03-02 Thread kaush
On Mar 1, 11:24 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> 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

Thanks Marc.
In Apache what are the ways/directives to set the rights to a folder?
-- 
http://mail.python.org/mailman/listinfo/python-list


FW: Escaping a triple quoted string' newbie question

2008-03-02 Thread Jules Stevenson
Hello, 

Apologies if the terminology in this email is a little incorrect, I'm still
finding my feet.

I'm using python to generate some script for another language (MEL, in maya,
specifically expressions). Maya runs python too, but unfortunately its
expression language still has to use the maya syntax.

If I pass the expression this code:

#runtime code [mel]
expRuntime="""float $pos[]=particleShape1.worldPosition;
setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0];
setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1];
setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2];
"""
dynExpression (p, s=expRuntime, rad=1)  #generate the expression

Then maya errors out, however if I pass maya an 'escaped' version:

expRuntime="""float $pos[]=particleShape1.worldPosition;\r\nsetAttr
(\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\r\nsetAttr
(\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\r\nsetAttr
(\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2];" -rad
particleShape1;"""

Then all is well. My question is, is there any way to convert the first
variable example to the second? It's a lot easier to type and on the eye.

Tia, Jules

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


Re: sqlite3 adaptors mystery

2008-03-02 Thread Matej Cepl
On 2008-03-01, 23:41 GMT, Mel wrote:
> 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.

Thanks for your help, but plain-text strings is not what 
I wanted. The boolean variables was what I was after. See this 
modified version of the script:

#!/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(":memory:")
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")
for (field,) in cur.fetchall():
print field,type(field)

The output here is:

[EMAIL PROTECTED] dumpBugzilla]$ python testAdaptors.py False 
True 
[EMAIL PROTECTED] dumpBugzilla]$ 

I thought that converter is there for just exactly this -- that 
I would get back bool values not strings.

Sorry for not being clear in the first run.

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


Re: Telnet versus telnetlib

2008-03-02 Thread Gabriel Genellina
En Sun, 02 Mar 2008 02:09:14 -0200, Grant Edwards <[EMAIL PROTECTED]>  
escribi�:

> 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"""
> Or use a forward slash:
>
> "C:/labels/anzick_primary_sample.lbl"

I didn't menction that alternative because it generates a different  
string; the resulting xml document may or may not be equivalent.

-- 
Gabriel Genellina

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

Re: RELEASED Python 2.6a1 and 3.0a3

2008-03-02 Thread Kay Schluehr
On 2 Mrz., 06:53, Ben Finney <[EMAIL PROTECTED]>
wrote:

> One of the stated goals of the migration is that the '2to3' program
> will only migrate Python 2.6 code -> Python 3.0 code.

Yes, I know. Why?

"The master said so" isn't an entirely satisfying answer. What are the
*technical reasons* that make it hard to apply '2to3' directly on
Python 2.4 or Python 2.5?

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


Re: sqlite3 adaptors mystery

2008-03-02 Thread Matej Cepl
On 2008-03-02, 08:16 GMT, Matej Cepl wrote:
> Thanks for your help, but plain-text strings is not what 
> I wanted. The boolean variables was what I was after. See this 
> modified version of the script:

OK, I got it -- I was missing detect_types parameter of the 
connect method.

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

Re: Python Telnet formatting?

2008-03-02 Thread Gabriel Genellina
En Sat, 01 Mar 2008 22:51:08 -0200, <[EMAIL PROTECTED]> escribi�:

> 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".)

They are part of the telnet protocol; 0xFF (IAC=Interpret as Command)  
starts a two or three byte command sequence.
Weren't you using telnetlib? It's supposed to handle this transparently.

> 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 client could send similar commands at the start of the session, or  
even later.

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

It isn't too hard to filter them out, if you want to do it by hand. See  
the source for telnetlib, and the original Telnet specificacion, RFC 854  
http://www.rfc-archive.org/getrfc.php?rfc=854 and RFC 855.

-- 
Gabriel Genellina

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

Re: class object interface document

2008-03-02 Thread Gabriel Genellina
En Sun, 02 Mar 2008 00:55:23 -0200, Neil.Fang.CN <[EMAIL PROTECTED]>  
escribió:

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

PyClass_* and PyInstance_* are for old-style classes and instances  
respectively, and will disappear in v3.0.
PyInstance is in the section 7.5.2 in the Python/C API Reference Manual; I  
don't find any documentation on PyClass itself.

-- 
Gabriel Genellina

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


RE: Escaping a triple quoted string' newbie question

2008-03-02 Thread Jules Stevenson
Sorry, original post got a bit mangled, which didn't help the explanation at
all, reposted stuff:

Apologies if the terminology in this email is a little incorrect, I'm still
finding my feet.

I'm using python to generate some script for another language (MEL, in maya,
specifically expressions). Maya runs python too, but unfortunately its
expression language still has to use the maya syntax.

If I pass the expression this code (excuse the double spacing, email seems
to e ignoring my line breaks):

#runtime code [mel]
expRuntime="""
float $pos[]=particleShape1.worldPosition;

setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0]; 

setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1]; 

setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2]; 
"""
dynExpression (p, s=expRuntime, rad=1)  #generate the expression

Then maya errors out, however if I pass maya an 'escaped' version:

expRuntime="""
float $pos[]=particleShape1.worldPosition;\nsetAttr
(\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\nsetAttr
(\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\nsetAttr
(\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2]; """

Then all is well. My question is, is there any way to convert the first
variable example to the second? It's a lot easier to type and on the eye.


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


Re: Beginner's assignment question

2008-03-02 Thread Schizoid Man
Lorenzo Gatti 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

Thank you for the explanation. I guess my question can be simplified as:

First step: a, b = 0, 1
No problem here as a and b are assigned values.

Second step: a, b = b, a + b

Now my question is does b become a + b after a becomes 1 or while a 
stays at 0?

As the assignment occurs simultaneously I suppose the answer is while a 
stays at 0.

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


Re: Beginner's assignment question

2008-03-02 Thread Gabriel Genellina
En Sun, 02 Mar 2008 08:25:49 -0200, Schizoid Man <[EMAIL PROTECTED]> escribi�:

> Lorenzo Gatti 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
>
> Thank you for the explanation. I guess my question can be simplified as:
>
> First step: a, b = 0, 1
> No problem here as a and b are assigned values.
>
> Second step: a, b = b, a + b
>
> Now my question is does b become a + b after a becomes 1 or while a
> stays at 0?
>
> As the assignment occurs simultaneously I suppose the answer is while a
> stays at 0.

Read the previous response carefully and you'll answer your question. The  
right hand side is EVALUATED in full before values are assignated to the  
left hand side. Evaluating b, a+b results in 1, 1. The, those values are  
assigned to a, b.

-- 
Gabriel Genellina

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

Re: RELEASED Python 2.6a1 and 3.0a3

2008-03-02 Thread Carl Banks
On Mar 2, 4:02 am, Kay Schluehr <[EMAIL PROTECTED]> wrote:
> On 2 Mrz., 06:53, Ben Finney <[EMAIL PROTECTED]>
> wrote:
>
> > One of the stated goals of the migration is that the '2to3' program
> > will only migrate Python 2.6 code -> Python 3.0 code.
>
> Yes, I know. Why?
>
> "The master said so" isn't an entirely satisfying answer. What are the
> *technical reasons* that make it hard to apply '2to3' directly on
> Python 2.4 or Python 2.5?

Well, even if you wanted to apply 2to3 to Python 2.5, you'd (probably)
have to modify your code to make it 2to3-compatible.  So if you're
going to do that, you might as well upgrade to 2.6 to take advantage
of new warnings and new idioms that are more conducive automatic
translation.

2to3 is not a general tool to convert any given source code from 2.6
to 3.0.  It's designed to make it possible to write code that works in
Python 2.6 and Python 3.0, but to do that you have to use a
"transitional Python" dialect that's a subset of 2.6.  (It would be
quite  to attempt a general code translator, of course.)

Anyway, I think there are a few cases in Python 2.5 where there's no
easy way to write something that 2to3 can handle, and some
specifically transitional features were added to 2.6 to remedy this.
I don't recall specifics, though.  It may be for the cases where
things that previously returned lists now return iterators.

Finally, 2.6 will have the benefit of being cross-checked with 3.0 to
ensure that 2to3 does what it's supposed to when used as intended.
All bets are off if you attempt it with 2.5.

In the end, the real *technical* reason might have been the developers
thought it wasn't worth the effort to backport it to 2.5.  The above
problems were probably solvable with enough effort, but would that
have been a wise use of resources?

One parenthetical I will add: 2to3 always seemed to me to be more of a
way to enfore constraint on the design of Python 3.0.  If a proposed
feature couldn't be automatically ported to 3.0, then it was a big
strike against the proposal.  That it could end up being a useful
transitional tool is nice, but it never seemed to be its primary
purpose.


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


Re: Escaping a triple quoted string' newbie question

2008-03-02 Thread Gabriel Genellina
En Sun, 02 Mar 2008 08:33:51 -0200, Jules Stevenson <[EMAIL PROTECTED]>  
escribi�:

> Sorry, original post got a bit mangled, which didn't help the  
> explanation at
> all, reposted stuff:
>
> Apologies if the terminology in this email is a little incorrect, I'm  
> still
> finding my feet.
>
> I'm using python to generate some script for another language (MEL, in  
> maya,
> specifically expressions). Maya runs python too, but unfortunately its
> expression language still has to use the maya syntax.
>
> If I pass the expression this code (excuse the double spacing, email  
> seems
> to e ignoring my line breaks):
>
> #runtime code [mel]
> expRuntime="""
> float $pos[]=particleShape1.worldPosition;
>
> setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0];
>
> setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1];
>
> setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2];
> """
> dynExpression (p, s=expRuntime, rad=1)#generate the expression
>
> Then maya errors out, however if I pass maya an 'escaped' version:
>
> expRuntime="""
> float $pos[]=particleShape1.worldPosition;\nsetAttr
> (\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\nsetAttr
> (\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\nsetAttr
> (\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2]; """
>
> Then all is well. My question is, is there any way to convert the first
> variable example to the second? It's a lot easier to type and on the eye.

Except for the doble-space on the first version, \n is the line separator  
on both, so I'll ignore them.
"""one
two"""
is the same thing as "one\ntwo" (even on Windows). The only remaining  
difference that I see is " -> \"

def mayaquote(text):
   return text.replace('"', '\\"')

-- 
Gabriel Genellina

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

Re: FW: Escaping a triple quoted string' newbie question

2008-03-02 Thread Duncan Booth
"Jules Stevenson" <[EMAIL PROTECTED]> wrote:

> Hello, 
> 
> Apologies if the terminology in this email is a little incorrect, I'm
> still finding my feet.
> 
> I'm using python to generate some script for another language (MEL, in
> maya, specifically expressions). Maya runs python too, but
> unfortunately its expression language still has to use the maya
> syntax. 
> 
> If I pass the expression this code:
> 
> #runtime code [mel]
> expRuntime="""float $pos[]=particleShape1.worldPosition;
> setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0];
> setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1];
> setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2];
> """
> dynExpression (p, s=expRuntime, rad=1) #generate the expression
> 
> Then maya errors out, however if I pass maya an 'escaped' version:
> 
> expRuntime="""float $pos[]=particleShape1.worldPosition;\r\nsetAttr
> (\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\r\nsetAttr
> (\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\r\nsetAttr
> (\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2];" -rad
> particleShape1;"""
> 
> Then all is well. My question is, is there any way to convert the
> first variable example to the second? It's a lot easier to type and on
> the eye. 
> 
Escaping the quotes doesn't change the string, so the only difference I can 
see between your strings is that you have split the lines by carriage-
return+linefeed instead of just linefeed characters. If so:
   s = expRuntime.replace('\n', '\r\n')
should have the desired effect.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner's assignment question

2008-03-02 Thread castironpi
On Mar 2, 4:49 am, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Sun, 02 Mar 2008 08:25:49 -0200, Schizoid Man <[EMAIL PROTECTED]> escribi�:
>
>
>
>
>
> > Lorenzo Gatti 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
>
> > Thank you for the explanation. I guess my question can be simplified as:
>
> > First step: a, b = 0, 1
> > No problem here as a and b are assigned values.
>
> > Second step: a, b = b, a + b
>
> > Now my question is does b become a + b after a becomes 1 or while a
> > stays at 0?
>
> > As the assignment occurs simultaneously I suppose the answer is while a
> > stays at 0.
>
> Read the previous response carefully and you'll answer your question. The  
> right hand side is EVALUATED in full before values are assignated to the  
> left hand side. Evaluating b, a+b results in 1, 1. The, those values are  
> assigned to a, b.
>
> --
> Gabriel Genellina- Hide quoted text -
>
> - Show quoted text -

Another way to think of it is:

a, b= b, a+b

--->

X= b, a+b
a, b= X

where X is a pair (2-tuple, two-element tuple, ordered pair, &c.)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Question about lambda and variable bindings

2008-03-02 Thread Duncan Booth
Michael Torrie <[EMAIL PROTECTED]> wrote:

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

There are three obvious ways to solve your problem:

1) Using a default argument as above is the original and used to be the 
only way to do it.

2) Using a factory function to generate the function:

def gencaller(fn, x):
   def caller(p):
   return fn(x+2, p)
   return caller

for x in xrange(10):
   funcs.append(gencaller(testfunc, x))

3) Using functools.partial:

from functools import partial
for x in xrange(10):
funcs.append(partial(testfunc, x+2))

or even: funcs = [partial(testfunc, x+2) for x in range(10)]

A lot depends on what your real code actually wants to pass as the 
parameters. If they are some complicated expression you cannot evaluate 
until it is called then use a factory function, if it is something simple 
as in your example then partial is easily the cleanest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Book Recomendations

2008-03-02 Thread David Cook
On 2008-03-02, Jeff Schwab <[EMAIL PROTECTED]> wrote:

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

Another vote for the Nutshell book, which I find a very useful and practical
book.  

I never found the "Dive in" book useful.

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


Re: Python app at startup!

2008-03-02 Thread SMALLp
Program:

import os
import wx

app = wx.App()
frame = wx.Frame(None, -1, "MyFrame")
frame.Show()

app.MainLoop()


python.exe setup.py py2exe

from distutils.core import setup
import py2exe

setup(windows=['prog.py'])


<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Feb 29, 7:21 am, SMALLp <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote:
>
>>
>> > Does it do the same thing when you run it with the Python interpreter?
>>
>> No. The programm works fine! In interupter and when i "compile" it.
>
> My guess is that you're not including something in the .exe that you
> need.  What does your py2exe command line and setup.py look like?
> 


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


Re: sqlite3 adaptors mystery

2008-03-02 Thread Mel
Matej Cepl wrote:
> Thanks for your help, but plain-text strings is not what 
> I wanted. The boolean variables was what I was after. See this 
> modified version of the script:
> 
> #!/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(":memory:")
> 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")
> for (field,) in cur.fetchall():
> print field,type(field)
> 
> The output here is:
> 
> [EMAIL PROTECTED] dumpBugzilla]$ python testAdaptors.py False  'unicode'>
> True 
> [EMAIL PROTECTED] dumpBugzilla]$ 
> 
> I thought that converter is there for just exactly this -- that 
> I would get back bool values not strings.
> 
> Sorry for not being clear in the first run.

Sorry about the misunderstanding.  It seems you want

db = sqlite3.connect("test.db", detect_types=sqlite3.PARSE_DECLTYPES)

After this, the print shows

False 
True 


Mel.

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


Re: Python Telnet formatting?

2008-03-02 Thread Bjoern Schliessmann
Gabriel Genellina wrote:

> They are part of the telnet protocol; 0xFF (IAC=Interpret as
> Command) starts a two or three byte command sequence.
> Weren't you using telnetlib? It's supposed to handle this
> transparently.

With Twisted you don't need Telnetlib, twisted.conch.telnet does the
job. I would definitely look at twisted.words, too.

Regards,


Björn

-- 
BOFH excuse #329:

Server depressed, needs Prozac

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


Re: How about adding rational fraction to Python?

2008-03-02 Thread Lie
On Mar 2, 2:02 pm, Paul Rubin  wrote:
> 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.

That's quite complex and restrictive, but probably it's because my
mind is not tuned to Haskell yet. Anyway, I don't think Python should
work that way, because Python have a plan for numerical integration
which would unify all numerical types into an apparent single type,
which requires removal of operator's limitations.

On Mar 2, 2:23 pm, Paul Rubin  wrote:
> 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.

In __future__ Python or Python 3.0, that mean function would work for
all types. And divisions on int is also inverse of multiplications,
just like subtraction is the inverse of addition:
from __future import division
a = 10
b = 5
c = a / b
if c * b == a: print 'multiplication is inverse of division'
-- 
http://mail.python.org/mailman/listinfo/python-list


tcp

2008-03-02 Thread Gif
i have this small script which after some router configurations works.

##

#! /usr/bin/python
import socket

HOST = ''
PORT = 1515
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
conn.send('HTTP/1.1 200 OK\r\n')
conn.send('Content-Type: text/html\r\n')
conn.send('Server: test/1.0\r\n\r\n')
conn.send('test')
s.close()

##

as you see it listens to 1515 until a connection is established and
then it accepts it...
the problem is that when it accepts the connection it sends those
strings and exits, but then it exits the program. i want it to listen
to 1515 then accept a connection, send.. and then listen to the port
again and again until new connections are found.

i've been struggling with try..except,while and all kinds of loops but
always new erros pop up, or it overflows.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tcp

2008-03-02 Thread 7stud
On Mar 2, 6:09 am, Gif <[EMAIL PROTECTED]> wrote:
> i have this small script which after some router configurations works.
>
> ##
>
> #! /usr/bin/python
> import socket
>
> HOST = ''
> PORT = 1515
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.bind((HOST, PORT))
> s.listen(1)
> conn, addr = s.accept()
> conn.send('HTTP/1.1 200 OK\r\n')
> conn.send('Content-Type: text/html\r\n')
> conn.send('Server: test/1.0\r\n\r\n')
> conn.send('test')
> s.close()
>
> ##
>
> as you see it listens to 1515 until a connection is established and
> then it accepts it...
> the problem is that when it accepts the connection it sends those
> strings and exits, but then it exits the program. i want it to listen
> to 1515 then accept a connection, send.. and then listen to the port
> again and again until new connections are found.
>
> i've been struggling with try..except,while and all kinds of loops but
> always new erros pop up, or it overflows.

while True:
  conn, addr = s.accept()
  ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Sparta api

2008-03-02 Thread Noorhan Abbas
Hello,
I wonder if anybody has used the sparta api for linking RDF to Python.
I was trying to run the example supplied by sparta and I got this error message

Traceback (most recent call last):
  File "C:/Python25/TestSpartaApi.py", line 10, in 
store = Graph()
  File "C:\Python25\lib\rdflib\Graph.py", line 265, in __init__
self.__store = store = plugin.get(store, Store)()
  File "C:\Python25\lib\rdflib\rdflib\plugin.py", line 27, in get
raise Exception("could not get plugin for %s, %s: %s" % (name, kind, e))
Exception: could not get plugin for default, : 

Any idea what is the problem?

Noorhan


  __
Sent from Yahoo! Mail.
A Smarter Inbox. http://uk.docs.yahoo.com/nowyoucan.html-- 
http://mail.python.org/mailman/listinfo/python-list

Can one get "for x in y" to work for non builtin classes?

2008-03-02 Thread Preben Randhol
Hi

I'm making a kind of ordered dictionary class. It is not exactly a
dictionary, but it uses a list and dictionary to store the data. 

Something like:

class dbase(list):
'''Database class keeping track of the order and data'''

def __init__(self):
self.__data = {}
self.__order = []
self.__uniq_id = 0

I'm just wondering if it is possible to get my class to work so that if
one do:


d=dbase()
d.append("Data")
d.append([1,2])

one can do like this to iterate over the data.

for x in d:
...

I'm looking at the list class but I don't quite understand from pydoc
which __ __ methods I have to implement to get the above to work.

Thanks in advance

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


Re: Can one get "for x in y" to work for non builtin classes?

2008-03-02 Thread Preben Randhol
On Sun, 2 Mar 2008 15:06:17 +0100
Preben Randhol <[EMAIL PROTECTED]> wrote:

>   class dbase(list):

Sorry the definition of the class is:

class dbase(object):

it doesn't derive from the list class.

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


Python newbie

2008-03-02 Thread t3chn0n3rd
i am a python newbie.  My studies have me in many directions
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First post from a Python newbiw

2008-03-02 Thread Steve Turner
Marc 'BlackJack' Rintsch wrote: 

: On Sun, 02 Mar 2008 14:15:09 +, Steve Turner wrote:
: 
:: Apart from doing something like
:: a=[0,0,0]
:: b=[0,0,0]
:: c=[0,0,0]
:: d=[a,b,c]
:: 
:: is there a better way of creating d??
: 
: a = [[0] * 3 for dummy in xrange(3)]

Thanks, Marc.

-- 
Steve

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


Re: tcp

2008-03-02 Thread Gif
you could at least check before posting. as i said i've tried like
1000 ways of doing that, and im so desparate that i'm thinking of
quiting python. This damn thing just doesnt work. when i do as you
post the server never even replies, as it tends to accept connections
all the time.

anyone has a better idea?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where's GUI for Python?

2008-03-02 Thread Peter Decker
On Sat, Mar 1, 2008 at 10:04 PM, Bill <[EMAIL PROTECTED]> wrote:

>  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 have used wxGlade, and while it worked well enough, it didn't seem
to fit my brain. I always found myself "thinking backwards" in order
to guess how the tool needed me to do things.

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

I didn't like that wxGlade generated code. If I later edited the code,
I could no longer use wxGlade to refine the design.

I've been amazed that so many people actually *like* working with
wxPython-style code. I always hated it, and even tried a few times to
make my own wrapper to insulate me from it (it was never very good).
When I found out about Dabo, I took to it instantly and got much more
productive very quickly. I was certain that everyone else would
respond the way that I did.

Obviously that's not what happened. I think that one of the reasons is
that I never coded in C++, so the ALL_CAPS_CONSTANTS style and the
whole getter/setter mentality seemed foreign to me. I'm a Python
programmer, and don't have to switch gears when writing UI code
anymore. I think if you like the sort of code that you need to use
wxPython directly, you're probably perfectly happy to code at that
level. For me, though, everytime I see raw wxPython code these days I
cringe, and am thankful that I don't have to deal with it anymore.

-- 

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


First post from a Python newbiw

2008-03-02 Thread Steve Turner
I finally decided to have a go with Python and am working through the 
tutorial.

On my old BBC Computer I could do something like this:

DIM A(2,2)

to create a 3 by 3 array of data. Then I could set any point:

A(0,0) = foo
A(0,1) = bar
etc.

In Python I thought I could do this with:

>>> a=[0,0,0]
>>> b=[a,a,a]
>>> b
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> b[1][1]='foo'
>>> b
[[0, 'foo', 0], [0, 'foo', 0], [0, 'foo', 0]]
>>>

I can understand why as b[1][1]='foo' is actually changing a[1]

Apart from doing something like
a=[0,0,0]
b=[0,0,0]
c=[0,0,0]
d=[a,b,c]

is there a better way of creating d??

-- 
Steve
 

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


Hyphenation: PyHyphen 0.4.1 and textwrap2-0.1.1 released

2008-03-02 Thread Dr. leo
This latest version of PyHyphen is only important for Python 2.4 addicts who
encountered a missing type when compiling. Further, a few signed/unsigned
mismatch warnings coming from MSVC should be fixed. As I have only Python
2.5, I'd be interested in any experiences when compiling it with Python 2.4.

Visit http://cheeseshop.python.org/pypi/PyHyphen

Further, as suggested here some days ago, I have integrated 'textwrap ' with
PyHyphen. While I anticipated lots of work and hoped for volunteers, I have
done it myself now. And it was a cake walk! Just had to insert roughly a
handfull of lines... Pure Python is pure fun!

Visit http://cheeseshop.python.org/pypi/textwrap2

Bests
Stefan


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


Re: Book Recomendations

2008-03-02 Thread Tommy Nordgren

On 2 mar 2008, at 01.56, 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.
>
> Thanks
>
> Ira
> -- 
> http://mail.python.org/mailman/listinfo/python-list
I would recommend "Programming Python", by Mark Lutz, from O'Reillys
--
"Home is not where you are born, but where your heart finds peace" -
Tommy Nordgren, "The dying old crone"
[EMAIL PROTECTED]


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


Keeping the console window

2008-03-02 Thread K Viltersten
I've proudly connected Notepad++ to edit
and run my fantastic software. When that
started to work, i noticed that all the
printing disappears as the console window
vanishes upon the program completion.

How can i trick Python program to keep on
running even if the actual statements 
have been exectuted?

Some kind of reading from keyboard?

--
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: First post from a Python newbiw

2008-03-02 Thread Marc 'BlackJack' Rintsch
On Sun, 02 Mar 2008 14:15:09 +, Steve Turner wrote:

> Apart from doing something like
> a=[0,0,0]
> b=[0,0,0]
> c=[0,0,0]
> d=[a,b,c]
> 
> is there a better way of creating d??

a = [[0] * 3 for dummy in xrange(3)]

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


Re: Can one get "for x in y" to work for non builtin classes?

2008-03-02 Thread Giles Brown
On Mar 2, 2:08 pm, Preben Randhol  wrote:
> On Sun, 2 Mar 2008 15:06:17 +0100
>
> Preben Randhol <[EMAIL PROTECTED]> wrote:
> >class dbase(list):
>
> Sorry the definition of the class is:
>
> class dbase(object):
>
> it doesn't derive from the list class.
>
> Preben

http://docs.python.org/lib/typeiter.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tcp

2008-03-02 Thread Steve Holden
7stud wrote:
> On Mar 2, 6:09 am, Gif <[EMAIL PROTECTED]> wrote:
>> i have this small script which after some router configurations works.
>>
>> ##
>>
>> #! /usr/bin/python
>> import socket
>>
>> HOST = ''
>> PORT = 1515
>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>> s.bind((HOST, PORT))
>> s.listen(1)
>> conn, addr = s.accept()
>> conn.send('HTTP/1.1 200 OK\r\n')
>> conn.send('Content-Type: text/html\r\n')
>> conn.send('Server: test/1.0\r\n\r\n')
>> conn.send('test')
>> s.close()
>>
>> ##
>>
>> as you see it listens to 1515 until a connection is established and
>> then it accepts it...
>> the problem is that when it accepts the connection it sends those
>> strings and exits, but then it exits the program. i want it to listen
>> to 1515 then accept a connection, send.. and then listen to the port
>> again and again until new connections are found.
>>
>> i've been struggling with try..except,while and all kinds of loops but
>> always new erros pop up, or it overflows.
> 
> while True:
>   conn, addr = s.accept()
>   ...

And now you get to start asking all the interesting questions that come 
up, like "How do I get my server to respond to multiple requests in 
parallel?"

It's a long road, but it's fun.

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


Python-based regular expression parser that allows patterns to call functions?

2008-03-02 Thread Andrew Warkentin
I am writing a filtering HTTP proxy (the site is 
http://xuproxy.sourceforge.net/). I want it to be compatible with 
Proxomitron (http://proxomitron.info/) filters. I need a regular 
expression parser that allows patterns to call functions (or more 
likely, class methods), to implement "matching commands" (look at the 
Proxmitron documentation to see what I mean). Does anyone know if such a 
library exists for Python, or do I have to write my own parser?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tcp

2008-03-02 Thread Diez B. Roggisch
Gif schrieb:
> you could at least check before posting. as i said i've tried like
> 1000 ways of doing that, and im so desparate that i'm thinking of
> quiting python. This damn thing just doesnt work. when i do as you
> post the server never even replies, as it tends to accept connections
> all the time.
> 
> anyone has a better idea?

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

Nobody here knows what you did - post code & stacktraces of at least one 
of your "1000 ways". Or quit python and try a language that is more 
friendly to reading your mind instead requiring you to spell out things 
in a computer readable way. You might need to hibernate a couple of 
centuries though until it's sufficient to open notepad and write "I'm a 
ubercool programmer, do make me the application of my dreams".

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


Re: tcp

2008-03-02 Thread Gif
sorry for acting like a fool but this is just to weirdly easy that i
can't get to work. i've written a small web server in another language
and this is more like copying code.
i already have everything figured out, except this one but noone seems
either willing or capable of helping me.
again sorry but i was in a very bad mood.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-02 Thread Paul Rubin
Lie <[EMAIL PROTECTED]> writes:
> That's quite complex and restrictive, but probably it's because my
> mind is not tuned to Haskell yet.

That aspect is pretty straightforward, other parts like only being
able to do i/o in functions having a special type are much more confusing.

> Anyway, I don't think Python should
> work that way, because Python have a plan for numerical integration
> which would unify all numerical types into an apparent single type,
> which requires removal of operator's limitations.

Well I think the idea is to have a hierarchy of nested numeric types,
not a single type.

> from __future import division
> a = 10
> b = 5
> c = a / b
> if c * b == a: print 'multiplication is inverse of division'

Try with a=7, b=25

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


Re: tcp

2008-03-02 Thread Gif
i would like to apologize once more. i understand that you are saying
"what a fool he is waiting for us to solve all his problems", cause
i've said that for other posts, when they seemed "immature". It's just
that i couldn't find a way out of 20 lines of code and this drove me
mad.

i end this topic here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tcp

2008-03-02 Thread Grant Edwards
On 2008-03-02, Gif <[EMAIL PROTECTED]> wrote:

> sorry for acting like a fool but this is just to weirdly easy
> that i can't get to work. i've written a small web server in
> another language and this is more like copying code. i already
> have everything figured out, except this one but noone seems
> either willing or capable of helping me.

Because you don't seem either willing or capable of describing
your problem in enough detail to allow anybody to help you.

Post a small program that demonstrates the "problem".

Describe precisely how that program fails to do what you want
it to.

-- 
Grant Edwards   grante Yow!  I was giving HAIR
  at   CUTS to th' SAUCER PEOPLE
   visi.com... I'm CLEAN!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Telnet formatting?

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

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

And we told you that you needed to implement the telnet protocol.

> 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".)

That "stuff" that you call "formatting" are commands for the
telnet protocol.  Apparently you've ignored what I told you
about implementing the telnet protocol (or using something that
does).

> How would I go about filtering this stuff out of the strings?

Once again:  If you're trying to write a telnet server, you
need to implement the telnet protocol.

> The thing is too, if I use other Telnet programs like
> Microsoft Telnet, they don't have this formatting,

Different telnet clients act a little differently.  Some won't
try to negotiate with the tenlet server until the server starts
the negotiation.

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

You have to handle the telnet protocol if you want to talk to
telnet clients.

-- 
Grant Edwards   grante Yow!  Yow! Those people
  at   look exactly like Donnie
   visi.comand Marie Osmond!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's BNF

2008-03-02 Thread MartinRinehart
Gabriel Genellina wrote:

> About the generated page: I think it would be more useful if each symbol
> links to its definition, instead of showing an alert(). This way it's
> easier to navigate the tree, specially with complex declarations.

That was my first shot. It didn't work. (Every line is its own table
because
you can't put named anchors inside a table, something I really
regret.)
If the production is already viewable, there's no jump when you click
the
link.. If the production is on the last page (many are)
you jump to the last page and then have to hunt down the production.
Remind me to figure out Ajax so you get what we really want: click on
it
and see its definition highlighted.

> You can place the current text into a "title" attribute and most browsers
> will show it as a tooltip.

Great! Consider it done. Konqueror, Firefox, Opera and even MSIE.

How would ,  and  make our lives easier?

I also tried putting the definitions into the status bar. If you ever
feel
tempted to do something similar, let the urge pass. (This now works
in Firefox 2 if you use the correct settings to allow javascript to
write
to the status bar. It doesn't work in Konqueror or Opera and I can't
even find the settings for MSIE.) Trying to get this to work DID get me
to considerably improve the readability of the HTML, so it wasn't a
total waste.

The tooltips are a big step forward. Thanks again.

Improved version at
http://www.MartinRinehart.com/articles/python-parse-bnf.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Network server- / client-side messaging

2008-03-02 Thread castironpi
'''
a website wants to show you different arrangements of framed pictures
on a wall.  you can click, drag, scale, and rotate pictures in place.
you can also drag new pictures in to it.

spacing is uniform and settable-- if you rotate one, the readout of
the total square area changes along with the new value.  you can also
select themes from the host that determine formulae for spacing, based
on established aesthetics constraints.

user clicks a picture and clicks rotate.  clientside doesn't want to
transmit the whole array back to the server for calculation, but
calculation takes a long time, due to the complexity of the spacing
formulae.  therefore, maintain paralell data on both sides: client for
displaying and interfacing, so as not to inform the server of every
mouse click, and server side to decrease transmission redundancy and
size.  do not broadcast every click, but do not broadcast entire
interface state.  constraint-based best-fit labor distribution is
between.

changes are sent to the server in the form of the change parameters
(perhaps a change object), the layout is updated roughly (still by
server-side procedures), and then precisely (along with the sq. ft.
readout) when the calculation completes.  the interface remains
continuously active.

Partial cast:
'''

class PictureClientSide:
def __init__( self, image ):
self._image= image
def on_scale( self, *params ):
change= self.whatchange( scale, *params )
self.tell_the_server( change )
def on_rotate( self, *params ):
change= self.whatchange( rotate, *params )
self.tell_the_server( change )
def server_says( self, layoutchange ):
renderchange( layoutchange )

class PictureServerSide:
def __init__( self, image ):
self._image= image
def client_says( self, change ):
preliminary= self.calculation()
preliminary_change= whatchange( preliminary )
tell_the_client( preliminary_change )
completed= self.other_calculation()
completed_change= whatchange( completed )
tell_the_client( completed_change )

'''
It's too tangled to proceed.  What if a second client 'change' and the
first server 'completed' cross paths?  Will you cancel the first
change explicitly or just drop it?  Are you shooting for five-nines
quality, or one?  What about signal loss and reordering?  Will you
retransmit an entire message upon suspected loss, or intervalled AYT
messages (are you there)?  What about an immediate time estimate?  How
general can the underlying framework be?  The rest is a brainstorm.
Please critique.
'''

class PictureClientSide( ClientSide ):
settings= Setting1(), Setting2()
@incremental
def server_says( self, layoutchange ):
renderchange( layoutchange )

class PictureServerSide( ServerSide ):
settings= Setting3(), Setting4()

'''
We may want to distinguish requests in both directions.  Depending on
which side takes care of the rotation, server_says may divide based on
increment.
'''

class PictureClientSide( ClientSide ):
@incremental( 1 )
def server_says( self, layoutchange ):
renderchange( layoutchange )
@incremental( 2 )
def server_says( self, layoutchange ):
renderchange( layoutchange )

'''
Furthermore, you may want the time estimate in its own method.
'''

class PictureClientSide( ClientSide ):
@incremental( layoutchange, 1 )
def server_says( self, layoutchange ):
renderchange( layoutchange )
@incremental( layoutchange, 2 )
def server_says( self, layoutchange ):
renderchange( layoutchange )
@message( timeout_message )
def timeout_message( self, etc ):
report( etc )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Book Recomendations

2008-03-02 Thread Ken Dere
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.
> 
> Thanks
> 
> Ira

I started off with Fortran 6X so I have been in the business about as long. 
Do just about everything now in Python.

I liked Learning Python


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


Re: Keeping the console window

2008-03-02 Thread Sam
You may use python in interactive mode:

$ python -i yourScript.py

Or use a blocking readline:

$ cat yourScript.py
import sys
sys.stdin.readline()

++

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


Re: tcp

2008-03-02 Thread Diez B. Roggisch
Gif schrieb:
> sorry for acting like a fool but this is just to weirdly easy that i
> can't get to work. i've written a small web server in another language
> and this is more like copying code.
> i already have everything figured out, except this one but noone seems
> either willing or capable of helping me.
> again sorry but i was in a very bad mood.

Writing a webserver (you NEVER stated that that is your ultimate goal) 
is a two-liner in Python.

See the module SimpleHTTPServer.

Using the extremely lowlevel module socket is a totally different beast. 
It requires rather deep knowledge of unix sockets, and has a steep 
learning curve.

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


Re: Can one get "for x in y" to work for non builtin classes?

2008-03-02 Thread castironpi
On Mar 2, 8:15 am, Giles Brown <[EMAIL PROTECTED]> wrote:
> On Mar 2, 2:08 pm, Preben Randhol 
> [EMAIL PROTECTED]> wrote:
> > On Sun, 2 Mar 2008 15:06:17 +0100
>
> > Preben Randhol <[EMAIL PROTECTED]> wrote:
> > >    class dbase(list):
>
> > Sorry the definition of the class is:
>
> >         class dbase(object):
>
> > it doesn't derive from the list class.
>
> > Preben
>
> http://docs.python.org/lib/typeiter.html

Be careful on your descision to return an ordered iterator or not--
that is, whether it iterates over the dictionary or the list (if I
understand you correctly).  If the order's unimportant then please
disregard.

You can also use:

>>> a= [2,3,4]
>>> b= iter( a )
>>> next( b )
2
>>> next( b )
3
>>> next( b )
4
-- 
http://mail.python.org/mailman/listinfo/python-list


Question on importing and function defs

2008-03-02 Thread TC
I have a problem.  Here's a simplified version of what I'm doing:

I have functions a() and b() in a module called 'mod'.  b() calls a().

So now, I have this program:

from mod import *

def a():
blahblah

b()


The problem being, b() is calling the a() that's in mod, not the new
a() that I want to replace it.  (Both a()'s have identical function
headers, in case that matters.)  How can I fix this?

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


Beautiful Code in Python?

2008-03-02 Thread js
Hi,

Have you ever seen Beautiful Python code?
Zope? Django? Python standard lib? or else?

Please tell me what code you think it's stunning.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Keeping the console window

2008-03-02 Thread castironpi
On Mar 2, 9:55 am, Sam <[EMAIL PROTECTED]> wrote:
> You may use python in interactive mode:
>
> $ python -i yourScript.py
>
> Or use a blocking readline:
>
> $ cat yourScript.py
> import sys
> sys.stdin.readline()
>
> ++
>
> Sam

FWIW, for what it's worth, you can invoke the interpreter from a batch
file/shell script too, and just use the native PAUSE instruction to
prompt for 'any key to continue'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Book Recomendations

2008-03-02 Thread James Matthews
I liked Core Python Programming 2nd edition!

On Sun, Mar 2, 2008 at 4:27 PM, Ken Dere <[EMAIL PROTECTED]> wrote:

> 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.
> >
> > Thanks
> >
> > Ira
>
> I started off with Fortran 6X so I have been in the business about as
> long.
> Do just about everything now in Python.
>
> I liked Learning Python
>
>
> Ken D.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://search.goldwatches.com/?Search=Movado+Watches
http://www.jewelerslounge.com
http://www.goldwatches.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python-based regular expression parser that allows patterns to call functions?

2008-03-02 Thread castironpi
On Mar 2, 8:41 am, Andrew Warkentin <[EMAIL PROTECTED]> wrote:
> I am writing a filtering HTTP proxy (the site 
> ishttp://xuproxy.sourceforge.net/). I want it to be compatible with
> Proxomitron (http://proxomitron.info/) filters. I need a regular
> expression parser that allows patterns to call functions (or more
> likely, class methods), to implement "matching commands" (look at the
> Proxmitron documentation to see what I mean). Does anyone know if such a
> library exists for Python, or do I have to write my own parser?

To make a list of commands available:

class C:
   def behavior( self ): pass
   def behavior2( self ): pass
   cmds= [ behavior, behavior2 ]

Then search C.cmds for a match to the regular expression.
C.behavior.func_name contains the string 'behavior' for checking.  You
might need to "bind" the contents of C.cmds before you call them too.
More info available, just ask.

You can also do:

class C:
   @string_callable
   def behavior( self ): pass
   @string_callable
   def behavior2( self ): pass

and

class C:
   def behavior( self ): pass
   def behavior2( self ): pass
   cmds= [ 'behavior', 'behavior2' ]

(strings this time), and use getattr( C, 'behavior' ) or for c= C(),
getattr( c, 'behavior' ).

class C:
   def behavior( self ): pass
   def behavior2( self ): pass
   cmds= [ 'behavior', 'behavior2' ]
C.cmds= commandmap( C, C.cmds )

can generate a dictionary of strings to methods.  And there's always

getattr( c, strA ), for your choice of strA, which throws an exception
if strA is not an attribute (method or property) of c, and hasattr( c,
strA ) can test if it is.

You less often want to generate distinct functions based on parameters
only, but you can.

c= C()
def behavior3( self ): pass
c.behavior3= behavior3

so c.behavior3() is legal.

Where does that get you?
-- 
http://mail.python.org/mailman/listinfo/python-list


SV: Where's GUI for Python?

2008-03-02 Thread K Viltersten
>>  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 have used wxGlade, and while it worked well 
> enough, it didn't seem to fit my brain. I 
> always found myself "thinking backwards" in order
> to guess how the tool needed me to do things.
> For me, though, everytime I see raw wxPython code 
> these days I cringe, and am thankful that I don't 
> have to deal with it anymore.

May i see a short sample of the two different
ways of coding, please? I'm very curious how
they differ (and of course, decide what's the
most pleasurable way for me).

As long as we're on the subject, i also wonder
if there's a general concensus on which 
technology is recommended in the different 
types of projects that are developed. (E.g. 
"use A for small/fast fixes, use B for stuff
you'll need to maintain later on".)

--
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: Question on importing and function defs

2008-03-02 Thread Gary Herron
TC wrote:
> I have a problem.  Here's a simplified version of what I'm doing:
>
> I have functions a() and b() in a module called 'mod'.  b() calls a().
>
> So now, I have this program:
>
> from mod import *
>
> def a():
> blahblah
>
> b()
>
>
> The problem being, b() is calling the a() that's in mod, not the new
> a() that I want to replace it.  (Both a()'s have identical function
> headers, in case that matters.)  How can I fix this?
>
> Thanks for any help.
>   

Since b calls mod.a, you could replace mod.a with your new a.  Like 
this:  (Warning, this could be considered bad style because it will 
confuse anyone who examines the mod module in an attempt to understand 
you code.)


  import mod

  def replacement_a():
...

  mod.a = replacement_a

  ...


Or another option.  Define b to take, as a parameter, the "a" function 
to call.

In mod:

  def a():
   ...

  def b(fn=a):  # to set the default a to call
...

And you main program:

  from mod import *

  def my_a():
...

  b(my_a)


Hope that helps

Gary Herron

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


Re: Beautiful Code in Python?

2008-03-02 Thread Michele Simionato
On Mar 2, 5:23 pm, js <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Have you ever seen Beautiful Python code?
> Zope? Django? Python standard lib? or else?
>
> Please tell me what code you think it's stunning.

The doctest module in the standard library.

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


Problem with the strip string method

2008-03-02 Thread Colin J. Williams
The Library Reference has
strip( [chars])

Return a copy of the string with the 
leading and trailing characters removed. 
The chars argument is a string 
specifying the set of characters to be 
removed. If omitted or None, the chars 
argument defaults to removing 
whitespace. The chars argument is not a 
prefix or suffix; rather, all 
combinations of its values are stripped:
 >>> '   spacious   '.strip()
 'spacious'
 >>> 'www.example.com'.strip('cmowz.')
 'example'

Only the last two examples below behave 
as expected.

Is it intended that the full range of 
characters be handled?

Colin W.

[Dbg]>>> 'ab$%\n\rcd'.strip('%')
'ab$%\n\rcd'
[Dbg]>>> 'ab$%cd'.strip('$')
'ab$%\n\rcd'
[Dbg]>>> 'ab$%cd'.strip('$')
'ab$%cd'
[Dbg]>>> '  ab$%cd  '.strip('$')
'  ab$%cd  '
[Dbg]>>> '  ab$%cd  '.strip('%')
'  ab$%cd  '
[Dbg]>>> '   spacious   '.strip()
'spacious'
[Dbg]>>> 'www.example.com'.strip('cmowz.')
'example'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-02 Thread Paul Rubin
Lie <[EMAIL PROTECTED]> writes:
> You hit the right note, but what I meant is the numeric type
> unification would make it _appear_ to consist of a single numeric type
> (yeah, I know it isn't actually, but what appears from outside isn't
> always what's inside).

That is clearly not intended; floats and decimals and integers are
really different from each other and Python has to treat them distinctly.

> > Try with a=7, b=25
> 
> They should still compare true, but they don't. The reason why they
> don't is because of float's finite precision, which is not exactly
> what we're talking here since it doesn't change the fact that
> multiplication and division are inverse of each other.

What?  Obviously they are not exact inverses for floats, as that test
shows.  They would be inverses for mathematical reals or rationals,
but Python does not have those.

> One way to handle this situation is to do an epsilon aware
> comparison (as should be done with any comparison involving floats),
> but I don't do it cause my intention is to clarify the real problem
> that multiplication is indeed inverse of division and I want to
> avoid obscuring that with the epsilon comparison.

I think you are a bit confused.  That epsilon aware comparison thing
acknowledges that floats only approximate the behavior of mathematical
reals.  When we do float arithmetic, we accept that "equal" often
really only means "approximately equal".  But when we do integer
arithmetic, we do not expect or accept equality as being approximate.
Integer equality means equal, not approximately equal.  That is why
int and float arithmetic cannot work the same way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can one get "for x in y" to work for non builtin classes?

2008-03-02 Thread Preben Randhol
On Sun, 2 Mar 2008 08:09:24 -0800 (PST)
[EMAIL PROTECTED] wrote:

> On Mar 2, 8:15 am, Giles Brown <[EMAIL PROTECTED]> wrote:

> > http://docs.python.org/lib/typeiter.html
> 
> Be careful on your descision to return an ordered iterator or not--
> that is, whether it iterates over the dictionary or the list (if I
> understand you correctly).  If the order's unimportant then please
> disregard.

I was thinking to iterate over the list which contains the uniq_ids as
order is important :-)

Thanks!

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

Re: How about adding rational fraction to Python?

2008-03-02 Thread Lie
On Mar 2, 10:02 pm, Paul Rubin  wrote:
> Lie <[EMAIL PROTECTED]> writes:
> > Anyway, I don't think Python should
> > work that way, because Python have a plan for numerical integration
> > which would unify all numerical types into an apparent single type,
> > which requires removal of operator's limitations.
>
> Well I think the idea is to have a hierarchy of nested numeric types,
> not a single type.

You hit the right note, but what I meant is the numeric type
unification would make it _appear_ to consist of a single numeric type
(yeah, I know it isn't actually, but what appears from outside isn't
always what's inside).

> > from __future import division
> > a = 10
> > b = 5
> > c = a / b
> > if c * b == a: print 'multiplication is inverse of division'
>
> Try with a=7, b=25

They should still compare true, but they don't. The reason why they
don't is because of float's finite precision, which is not exactly
what we're talking here since it doesn't change the fact that
multiplication and division are inverse of each other. One way to
handle this situation is to do an epsilon aware comparison (as should
be done with any comparison involving floats), but I don't do it cause
my intention is to clarify the real problem that multiplication is
indeed inverse of division and I want to avoid obscuring that with the
epsilon comparison.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question on importing and function defs

2008-03-02 Thread Nick Miller
TC wrote:
> I have a problem.  Here's a simplified version of what I'm doing:
>
> I have functions a() and b() in a module called 'mod'.  b() calls a().
>
> So now, I have this program:
>
> from mod import *
>
> def a():
> blahblah
>
> b()
>
>
> The problem being, b() is calling the a() that's in mod, not the new
> a() that I want to replace it.  (Both a()'s have identical function
> headers, in case that matters.)  How can I fix this?
>
> Thanks for any help.
>   

The only problem I could see with this is a local function issue. 
Meaning that even when you write the new a() function in the main source 
file, b() doesn't know it exists because it's relying on it's own 
"local" a() in the module. I'm also new to using Python so I that's all 
I can think would be the problem.

Nick

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


SV: Keeping the console window

2008-03-02 Thread K Viltersten
> You may use python in interactive mode:
> 
> $ python -i yourScript.py
> 
> Or use a blocking readline:
> 
> $ cat yourScript.py
> import sys
> sys.stdin.readline()


Thanks guys!

--
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: Problem with the strip string method

2008-03-02 Thread Jorge Godoy
Colin J. Williams wrote:

> Return a copy of the string with the
> leading and trailing characters removed.
  

> Only the last two examples below behave
> as expected.

They all looks OK to me.

> [Dbg]>>> 'ab$%\n\rcd'.strip('%')
> 'ab$%\n\rcd'

No "%" at the beginning or end of string.  Nothing changed.

> [Dbg]>>> 'ab$%cd'.strip('$')
> 'ab$%\n\rcd'

No "$" at the beginning or end of string.  Nothing changed.  I believe that
you didn't copy this from the standard input due to the presence of "\r\n"
on the answer...

> [Dbg]>>> 'ab$%cd'.strip('$')
> 'ab$%cd'

No "$" at the beginning or end of string.  Nothing changed.

> [Dbg]>>> '  ab$%cd  '.strip('$')
> '  ab$%cd  '

No "$" at the beginning or end of string.  Nothing changed.

> [Dbg]>>> '  ab$%cd  '.strip('%')
> '  ab$%cd  '

No "%" at the beginning or end of string.  Nothing changed.

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


Re: Problem with the strip string method

2008-03-02 Thread Martin Blume
"Colin J. Williams" schrieb 
> The Library Reference has
> strip( [chars])
> 
> Return a copy of the string with the 
> leading and trailing characters removed. 
  

It's "leading and trailing", not 
"leading, trailing or embedded".

>>> "xxxaaaxxx".strip("x")
'aaa'
>>> "xxxaaaxxxaaaxxx".strip("x")
'aaaxxxaaa'
>>>

HTH 
Martin



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


Re: Article of interest: Python pros/cons for the enterprise

2008-03-02 Thread Paul Rubin
Robert Brown <[EMAIL PROTECTED]> writes:
> Unfortunately, performance often comes at the cost of safety and
> correctness.  Optimized C programs can crash when pointers walk off the
> end of arrays or they can yield incorrect results when integers overflow
> the limits of the hardware.

Yes, even unoptimized C programs can do that.  C is just plain dangerous.

> [SBCL Common Lisp]
> Very rarely, say inside a loop, I temporarily change my default compiler
> settings.  Inside the lexical scope of these declarations, the compiled
> code does no run-time type checking and trusts me.  Here, broken Lisp
> code can crash the system (just as broken C code can), but the compiled
> code runs very fast.
> 
> I trade off safety for speed, but only where necessary.

It seems to me that this trade-off results from a problem with the
language's expressivity.  If you have a sound argument that the
subscripts in your loop are actually safe, you ought to be able to
express that argument to the compiler for static checking.  That
should result in safe code with no runtime checks needed.

That said, trying to provide that level of expressivity is at the
cutting edge of programming language research, and in real-world
languages, for now, we have to live with some runtime checks.
But in an example like (pseudocode):

   for i in 1..100:
   hack(x[i])

it should be enough to check outside the loop in constant time that
1..100 are valid subscripts for x, then generate the loop code with
no check on each separate access.  That is maybe not possible in C
because i might be aliased to something, but in a sane language it
should be possible.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python-based regular expression parser that allows patterns to call functions?

2008-03-02 Thread Paul McGuire
On Mar 2, 8:41 am, Andrew Warkentin <[EMAIL PROTECTED]> wrote:
> I am writing a filtering HTTP proxy (the site 
> ishttp://xuproxy.sourceforge.net/). I want it to be compatible with
> Proxomitron (http://proxomitron.info/) filters. I need a regular
> expression parser that allows patterns to call functions (or more
> likely, class methods), to implement "matching commands" (look at the
> Proxmitron documentation to see what I mean). Does anyone know if such a
> library exists for Python, or do I have to write my own parser?

Andrew -

Pyparsing allows you to define parse actions that get called when
element within a grammar are matched.  These actions can update
external data structures, modify the matched text, or can be used to
provide additional semantic validation.  Here's an example:

from pyparsing import *

integer = Regex(r"\b\d+\b")
# could also be written as
#~ integer = WordStart() + Word(nums) + WordEnd()

# convert matched text to actual integer
def cvt_to_int (tokens):
return int(tokens[0])

# only accept integers < 100
def must_be_less_than_100(tokens):
if (tokens[0]) >= 100:
raise ParseException("only integers < 100 are allowed")

# add value to running tally of matches
def increment_tally(tokens):
global running_total
running_total += tokens[0]

integer.setParseAction( cvt_to_int)
integer.addParseAction( must_be_less_than_100 )
integer.addParseAction( increment_tally )

# could also be written as
#~ integer.setParseAction( cvt_to_int,
#~ must_be_less_than_100,
#~ increment_tally )

running_total = 0
print integer.searchString("absdlkj 1 5 12 121 78 22")
print running_total

Prints:

[[1], [5], [12], [78], [22]]
118

More info about pyparsing at http://pyparsing.wikispaces.com, plus
more examples, and links to other doc sources.

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


Re: Question on importing and function defs

2008-03-02 Thread TC
On Mar 2, 11:37 am, Gary Herron <[EMAIL PROTECTED]> wrote:
> TC wrote:
> > I have a problem.  Here's a simplified version of what I'm doing:
>
> > I have functions a() and b() in a module called 'mod'.  b() calls a().
>
> > So now, I have this program:
>
> > from mod import *
>
> > def a():
> > blahblah
>
> > b()
>
> > The problem being, b() is calling the a() that's in mod, not the new
> > a() that I want to replace it.  (Both a()'s have identical function
> > headers, in case that matters.)  How can I fix this?
>
> > Thanks for any help.
>
> Since b calls mod.a, you could replace mod.a with your new a.  Like
> this:  (Warning, this could be considered bad style because it will
> confuse anyone who examines the mod module in an attempt to understand
> you code.)
>
>   import mod
>
>   def replacement_a():
> ...
>
>   mod.a = replacement_a
>
>   ...
>
> Or another option.  Define b to take, as a parameter, the "a" function
> to call.
>
> In mod:
>
>   def a():
>...
>
>   def b(fn=a):  # to set the default a to call
> ...
>
> And you main program:
>
>   from mod import *
>
>   def my_a():
> ...
>
>   b(my_a)
>
> Hope that helps
>
> Gary Herron

Thanks for the tips, but no luck.  This is for a homework assignment,
so there are a couple of requirements, namely that I can't touch
'mod', and I have to do 'from mod import *' as opposed to 'import
mod'.

So the first method you suggested won't work as written, since the mod
namespace doesn't exist.  I tried a = replacement_a, but b() is still
calling mod's version of a() for some reason.  And because I can't
touch mod, I can't use your second suggestion.

In case I somehow oversimplified, here's the actual relevant code, in
'mod' (actually called 'search').  The first fn is what I've been
calling a(), the second is b().

(lots of stuff...)

def compare_searchers(problems, header,
searchers=[breadth_first_tree_search,
  breadth_first_graph_search,
depth_first_graph_search,
  iterative_deepening_search,
depth_limited_search,
  astar_search]):
def do(searcher, problem):
p = InstrumentedProblem(problem)
searcher(p)
return p
table = [[name(s)] + [do(s, p) for p in problems] for s in
searchers]
print_table(table, header)

def compare_graph_searchers():
compare_searchers(problems=[GraphProblem('A', 'B', romania),
GraphProblem('O', 'N', romania),
GraphProblem('Q', 'WA', australia)],
header=['Searcher', 'Romania(A,B)', 'Romania(O, N)',
'Australia'])


That's the end of the 'search' file.  And here's my program, which
defines an identical compare_searchers() with an added print
statement.  That statement isn't showing up.

from search import *

def compare_searchers(problems, header,
searchers=[breadth_first_tree_search,
  breadth_first_graph_search,
depth_first_graph_search,
  iterative_deepening_search,
depth_limited_search,
  astar_search, best_first_graph_search]):
def do(searcher, problem):
p = InstrumentedProblem(problem)
searcher(p)
return p
table = [[name(s)] + [do(s, p) for p in problems] for s in
searchers]
print 'test'
print_table(table, header)

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


Re: Question on importing and function defs

2008-03-02 Thread Steve Holden
TC wrote:
> On Mar 2, 11:37 am, Gary Herron <[EMAIL PROTECTED]> wrote:
>> TC wrote:
>>> I have a problem.  Here's a simplified version of what I'm doing:
>>> I have functions a() and b() in a module called 'mod'.  b() calls a().
>>> So now, I have this program:
>>> from mod import *
>>> def a():
>>> blahblah
>>> b()
>>> The problem being, b() is calling the a() that's in mod, not the new
>>> a() that I want to replace it.  (Both a()'s have identical function
>>> headers, in case that matters.)  How can I fix this?
>>> Thanks for any help.
>> Since b calls mod.a, you could replace mod.a with your new a.  Like
>> this:  (Warning, this could be considered bad style because it will
>> confuse anyone who examines the mod module in an attempt to understand
>> you code.)
>>
>>   import mod
>>
>>   def replacement_a():
>> ...
>>
>>   mod.a = replacement_a
>>
>>   ...
>>
>> Or another option.  Define b to take, as a parameter, the "a" function
>> to call.
>>
>> In mod:
>>
>>   def a():
>>...
>>
>>   def b(fn=a):  # to set the default a to call
>> ...
>>
>> And you main program:
>>
>>   from mod import *
>>
>>   def my_a():
>> ...
>>
>>   b(my_a)
>>
>> Hope that helps
>>
>> Gary Herron
> 
> Thanks for the tips, but no luck.  This is for a homework assignment,
> so there are a couple of requirements, namely that I can't touch
> 'mod', and I have to do 'from mod import *' as opposed to 'import
> mod'.
> 
> So the first method you suggested won't work as written, since the mod
> namespace doesn't exist.  I tried a = replacement_a, but b() is still
> calling mod's version of a() for some reason.  And because I can't
> touch mod, I can't use your second suggestion.
> 
> In case I somehow oversimplified, here's the actual relevant code, in
> 'mod' (actually called 'search').  The first fn is what I've been
> calling a(), the second is b().
> 
> (lots of stuff...)
> 
> def compare_searchers(problems, header,
> searchers=[breadth_first_tree_search,
>   breadth_first_graph_search,
> depth_first_graph_search,
>   iterative_deepening_search,
> depth_limited_search,
>   astar_search]):
> def do(searcher, problem):
> p = InstrumentedProblem(problem)
> searcher(p)
> return p
> table = [[name(s)] + [do(s, p) for p in problems] for s in
> searchers]
> print_table(table, header)
> 
> def compare_graph_searchers():
> compare_searchers(problems=[GraphProblem('A', 'B', romania),
> GraphProblem('O', 'N', romania),
> GraphProblem('Q', 'WA', australia)],
> header=['Searcher', 'Romania(A,B)', 'Romania(O, N)',
> 'Australia'])
> 
> 
> That's the end of the 'search' file.  And here's my program, which
> defines an identical compare_searchers() with an added print
> statement.  That statement isn't showing up.
> 
> from search import *
> 
> def compare_searchers(problems, header,
> searchers=[breadth_first_tree_search,
>   breadth_first_graph_search,
> depth_first_graph_search,
>   iterative_deepening_search,
> depth_limited_search,
>   astar_search, best_first_graph_search]):
> def do(searcher, problem):
> p = InstrumentedProblem(problem)
> searcher(p)
> return p
> table = [[name(s)] + [do(s, p) for p in problems] for s in
> searchers]
> print 'test'
> print_table(table, header)
> 
> compare_graph_searchers()

Since you've admitted it's for homework, here are a couple of hints.

1. The b() function is *always* going to try and resolve its references 
in the namespace it was defined in;

2. The technique you need is most likely known as "monkey patching". 
When you say "I can't touch mod", that may mean "the source of mod must 
remain unchanged", which is subtly different. Google is your friend ...

Good luck with your assignment.

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: Can one get "for x in y" to work for non builtin classes?

2008-03-02 Thread Preben Randhol
On Sun, 2 Mar 2008 06:15:54 -0800 (PST)
Giles Brown <[EMAIL PROTECTED]> wrote:

> http://docs.python.org/lib/typeiter.html

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


Re: tcp

2008-03-02 Thread Steve Holden
Gif wrote:
> i would like to apologize once more. i understand that you are saying
> "what a fool he is waiting for us to solve all his problems", cause
> i've said that for other posts, when they seemed "immature". It's just
> that i couldn't find a way out of 20 lines of code and this drove me
> mad.
> 
> i end this topic here.

If you want to use the socket module, take a look at

   http://holdenweb.com/py/networking/

which contains links to some fairly explicit notes about how to write 
TCP and UDP servers in Python.

Nobody thinks you are a fool for wanting help with your problems, it's 
simply that you have to provide enough information about what' wring for 
us to get a handle on the issues.

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: Problem with the strip string method

2008-03-02 Thread Steve Holden
Colin J. Williams wrote:
> The Library Reference has
> strip( [chars])
> 
> Return a copy of the string with the 
> leading and trailing characters removed. 
> The chars argument is a string 
> specifying the set of characters to be 
> removed. If omitted or None, the chars 
> argument defaults to removing 
> whitespace. The chars argument is not a 
> prefix or suffix; rather, all 
> combinations of its values are stripped:
>  >>> '   spacious   '.strip()
>  'spacious'
>  >>> 'www.example.com'.strip('cmowz.')
>  'example'
> 
> Only the last two examples below behave 
> as expected.
> 
Adjust your expectations. The software is correct.

> Is it intended that the full range of 
> characters be handled?
> 
> Colin W.
> 
> [Dbg]>>> 'ab$%\n\rcd'.strip('%')
> 'ab$%\n\rcd'
> [Dbg]>>> 'ab$%cd'.strip('$')
> 'ab$%\n\rcd'
> [Dbg]>>> 'ab$%cd'.strip('$')
> 'ab$%cd'
> [Dbg]>>> '  ab$%cd  '.strip('$')
> '  ab$%cd  '
> [Dbg]>>> '  ab$%cd  '.strip('%')
> '  ab$%cd  '
> [Dbg]>>> '   spacious   '.strip()
> 'spacious'
> [Dbg]>>> 'www.example.com'.strip('cmowz.')
> 'example'

I suspect what you need is the .replace() method.

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: Beautiful Code in Python?

2008-03-02 Thread John DeRosa
On Mon, 3 Mar 2008 01:23:32 +0900, js <[EMAIL PROTECTED]> wrote:

>Hi,
>
>Have you ever seen Beautiful Python code?
>Zope? Django? Python standard lib? or else?
>
>Please tell me what code you think it's stunning.

Just about any Python code I look at.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuples, index method, Python's design

2008-03-02 Thread Alan Isaac
On April 12th, 2007 at 10:05 PM Alan Isaac wrote:

> The avoidance of tuples, so carefully defended in other 

> terms, is often rooted (I claim) in habits formed from 

> need for list methods like ``index`` and ``count``. 

> Indeed, I predict that Python tuples will eventually have 

> these methods and that these same people will then defend 

> *that* status quo.





http://python.org/download/releases/2.6/NEWS.txt>



- Issue #2025 :  Add tuple.count() and tuple.index() 

  methods to comply with the collections.Sequence API.



Cheers,

Alan Isaac




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


Re: Question on importing and function defs

2008-03-02 Thread castironpi
On Mar 2, 11:44 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> TC wrote:
> > On Mar 2, 11:37 am, Gary Herron <[EMAIL PROTECTED]> wrote:
> >> TC wrote:
> >>> I have a problem.  Here's a simplified version of what I'm doing:
> >>> I have functions a() and b() in a module called 'mod'.  b() calls a().
> >>> So now, I have this program:
> >>> from mod import *
> >>> def a():
> >>>     blahblah
> >>> b()
> >>> The problem being, b() is calling the a() that's in mod, not the new
> >>> a() that I want to replace it.  (Both a()'s have identical function
> >>> headers, in case that matters.)  How can I fix this?
> >>> Thanks for any help.
> >> Since b calls mod.a, you could replace mod.a with your new a.  Like
> >> this:  (Warning, this could be considered bad style because it will
> >> confuse anyone who examines the mod module in an attempt to understand
> >> you code.)
>
> >>   import mod
>
> >>   def replacement_a():
> >>     ...
>
> >>   mod.a = replacement_a
>
> >>   ...
>
> >> Or another option.  Define b to take, as a parameter, the "a" function
> >> to call.
>
> >> In mod:
>
> >>   def a():
> >>    ...
>
> >>   def b(fn=a):  # to set the default a to call
> >>     ...
>
> >> And you main program:
>
> >>   from mod import *
>
> >>   def my_a():
> >>     ...
>
> >>   b(my_a)
>
> >> Hope that helps
>
> >> Gary Herron
>
> > Thanks for the tips, but no luck.  This is for a homework assignment,
> > so there are a couple of requirements, namely that I can't touch
> > 'mod', and I have to do 'from mod import *' as opposed to 'import
> > mod'.
>
> > So the first method you suggested won't work as written, since the mod
> > namespace doesn't exist.  I tried a = replacement_a, but b() is still
> > calling mod's version of a() for some reason.  And because I can't
> > touch mod, I can't use your second suggestion.
>
> > In case I somehow oversimplified, here's the actual relevant code, in
> > 'mod' (actually called 'search').  The first fn is what I've been
> > calling a(), the second is b().
>
> > (lots of stuff...)
>
> > def compare_searchers(problems, header,
> > searchers=[breadth_first_tree_search,
> >                       breadth_first_graph_search,
> > depth_first_graph_search,
> >                       iterative_deepening_search,
> > depth_limited_search,
> >                       astar_search]):
> >     def do(searcher, problem):
> >         p = InstrumentedProblem(problem)
> >         searcher(p)
> >         return p
> >     table = [[name(s)] + [do(s, p) for p in problems] for s in
> > searchers]
> >     print_table(table, header)
>
> > def compare_graph_searchers():
> >     compare_searchers(problems=[GraphProblem('A', 'B', romania),
> >                                 GraphProblem('O', 'N', romania),
> >                                 GraphProblem('Q', 'WA', australia)],
> >             header=['Searcher', 'Romania(A,B)', 'Romania(O, N)',
> > 'Australia'])
>
> > That's the end of the 'search' file.  And here's my program, which
> > defines an identical compare_searchers() with an added print
> > statement.  That statement isn't showing up.
>
> > from search import *
>
> > def compare_searchers(problems, header,
> > searchers=[breadth_first_tree_search,
> >                       breadth_first_graph_search,
> > depth_first_graph_search,
> >                       iterative_deepening_search,
> > depth_limited_search,
> >                       astar_search, best_first_graph_search]):
> >     def do(searcher, problem):
> >         p = InstrumentedProblem(problem)
> >         searcher(p)
> >         return p
> >     table = [[name(s)] + [do(s, p) for p in problems] for s in
> > searchers]
> >     print 'test'
> >     print_table(table, header)
>
> > compare_graph_searchers()
>
> Since you've admitted it's for homework, here are a couple of hints.
>
> 1. The b() function is *always* going to try and resolve its references
> in the namespace it was defined in;
>
> 2. The technique you need is most likely known as "monkey patching".
> When you say "I can't touch mod", that may mean "the source of mod must
> remain unchanged", which is subtly different. Google is your friend ...
>
> Good luck with your assignment.
>
> regards
>   Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/- Hide quoted text -
>
> - Show quoted text -

You can use 'settrace' to intervene.  You might be able to delete the
'a'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with the strip string method

2008-03-02 Thread castironpi
On Mar 2, 11:45 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> I suspect what you need is the .replace() method.

The information's there-- the word 'contiguous' might clear it up a
bit.

> > Return a copy of the string with the
> > leading and trailing characters removed.
> > The chars argument is a string
> > specifying the set of characters to be
> > removed. If omitted or None, the chars
> > argument defaults to removing
> > whitespace. The chars argument is not a
> > prefix or suffix; rather, all
> > combinations of its values are stripped:

Return the string's substring from the first character not a member of
'chars' to the last such.

Remove contiguous leading and trailing members of 'chars'.  If omitted
or None, 'chars' defaults over to the set of whitespace set( "\n\r\t
" ). (XXX TODO: ask Steve Reg Ex Guru this).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beautiful Code in Python?

2008-03-02 Thread castironpi
On Mar 2, 12:01 pm, John DeRosa <[EMAIL PROTECTED]> wrote:
> On Mon, 3 Mar 2008 01:23:32 +0900, js <[EMAIL PROTECTED]> wrote:
> >Hi,
>
> >Have you ever seen Beautiful Python code?
> >Zope? Django? Python standard lib? or else?
>
> >Please tell me what code you think it's stunning.
>
> Just about any Python code I look at.

Decorators, with, and namedtuple.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mod_python Unable to create file

2008-03-02 Thread Sean Allen

On Mar 2, 2008, at 3:24 AM, kaush wrote:

> On Mar 1, 11:24 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> 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
>
> Thanks Marc.
> In Apache what are the ways/directives to set the rights to a folder?

none. you set permissions via the operating system.

chmod would be the command from terminal you are looking for.

or you can do get info on the folder in question via the finder and  
set perms there.

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


Re: Problem with the strip string method

2008-03-02 Thread Colin J. Williams
[EMAIL PROTECTED] wrote:
> On Mar 2, 11:45 am, Steve Holden <[EMAIL PROTECTED]> wrote:
>> I suspect what you need is the .replace() method.
> 
> The information's there-- the word 'contiguous' might clear it up a
> bit.
> 
>>> Return a copy of the string with the
>>> leading and trailing characters removed.
>>> The chars argument is a string
>>> specifying the set of characters to be
>>> removed. If omitted or None, the chars
>>> argument defaults to removing
>>> whitespace. The chars argument is not a
>>> prefix or suffix; rather, all
>>> combinations of its values are stripped:
> 
> Return the string's substring from the first character not a member of
> 'chars' to the last such.
> 
> Remove contiguous leading and trailing members of 'chars'.  If omitted
> or None, 'chars' defaults over to the set of whitespace set( "\n\r\t
> " ). (XXX TODO: ask Steve Reg Ex Guru this).

Thanks to all respondents, Steve Holden 
is right, I expected more than I should 
have.

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


RE: Escaping a triple quoted string' newbie question

2008-03-02 Thread Jules Stevenson
> > float $pos[]=particleShape1.worldPosition;
> >
> > setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0];
> >
> > setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1];
> >
> > setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2];
> > """
> > dynExpression (p, s=expRuntime, rad=1)  #generate the expression
> >
> > Then maya errors out, however if I pass maya an 'escaped' version:
> >
> > expRuntime="""
> > float $pos[]=particleShape1.worldPosition;\nsetAttr
> > (\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\nsetAttr
> > (\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\nsetAttr
> > (\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2]; """
> >
> > Then all is well. My question is, is there any way to convert the first
> > variable example to the second? It's a lot easier to type and on the
> eye.
> 
> Except for the doble-space on the first version, \n is the line separator
> on both, so I'll ignore them.
> """one
> two"""
> is the same thing as "one\ntwo" (even on Windows). The only remaining
> difference that I see is " -> \"
> 
> def mayaquote(text):
>return text.replace('"', '\\"')
> 

Thanks, this will work great. I was just wondering if there was an automatic
'string to escaped text' type function. Otherwise I'd have to build parsing
for all chars that could cause a wobbly, but these may be few, so not too
much of an issue.

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


Re: tcp

2008-03-02 Thread castironpi
On Mar 2, 11:38 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> Nobody thinks you are a fool for wanting help with your problems, it's
> simply that you have to provide enough information about what' wring for
> us to get a handle on the issues.

This worked:

import socket
from time import time

for i in range( 20 ):
HOST = ''
PORT = 80 #<
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
print( 'listen' )
s.listen(1)
conn, addr = s.accept()
print( 'connected', addr )
print( conn.recv( 4096 ) ) #<
conn.send( bytes('test %f'%time(),'ascii') )
conn.close() #<
s.close()

... and connect with a browser:  http://localhost/ if it's internet
exploder.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner's assignment question

2008-03-02 Thread Schizoid Man
Gabriel Genellina wrote:
> En Sun, 02 Mar 2008 08:25:49 -0200, Schizoid Man <[EMAIL PROTECTED]> escribi�:
> 
>> Lorenzo Gatti 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
>>
>> Thank you for the explanation. I guess my question can be simplified as:
>>
>> First step: a, b = 0, 1
>> No problem here as a and b are assigned values.
>>
>> Second step: a, b = b, a + b
>>
>> Now my question is does b become a + b after a becomes 1 or while a
>> stays at 0?
>>
>> As the assignment occurs simultaneously I suppose the answer is while a
>> stays at 0.
> 
> Read the previous response carefully and you'll answer your question. 
> The right hand side is EVALUATED in full before values are assignated to 
> the left hand side. Evaluating b, a+b results in 1, 1. The, those values 
> are assigned to a, b.

Thank you very much. It's clear now.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: cx_Freeze : LookupError: unknown encoding: ascii

2008-03-02 Thread Rakesh Kumar
On Mar 1, 3:41 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > 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


Thanks Martin.

Adding something like

./freeze --include-modules=encodings.ascii,encodings.utf_8 

fixed the issue.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-02 Thread Jeff Schwab
Paul Rubin wrote:
> 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).

Better yet, how hard would it be to define an otherwise int-like type 
that did not define a non-flooring division operator?  Are there any 
real use cases for such a type?  Maybe a division operator could be 
defined to perform a run-time check that, for an operation n/d==q, 
n==q*d; else, throw an exception.  Code written to support duck-typed 
integers should work with such a UDT "out of the box."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuples, index method, Python's design

2008-03-02 Thread Paul Boddie
On 2 Mar, 19:06, Alan Isaac <[EMAIL PROTECTED]> wrote:
> On April 12th, 2007 at 10:05 PM Alan Isaac wrote:
>
> > The avoidance of tuples, so carefully defended in other
> > terms, is often rooted (I claim) in habits formed from
> > need for list methods like ``index`` and ``count``.
> > Indeed, I predict that Python tuples will eventually have
> > these methods and that these same people will then defend
> > *that* status quo.

You were more confident about this than I was. Still, nothing happens
if no-one steps up to do something about it.

> http://python.org/download/releases/2.6/NEWS.txt>
>
> - Issue #2025 :  Add tuple.count() and tuple.index()
>
>   methods to comply with the collections.Sequence API.

Here's the tracker item that may have made it happen:

http://bugs.python.org/issue1696444

I think you need to thank Raymond Hettinger for championing the
cause. ;-)

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


Re: Network server- / client-side messaging

2008-03-02 Thread castironpi
'''
Last time, we left off at:
'''

class InterfaceClientSide( ClientSide ):
message= MessageDec()
incremental= message.incremental()
settings= AYT( .5, 3 )
user_act= message.out()
def __init__( self, image ):
self._image= image
ClientSide.__init__( self )
def on_scale( self, *args ):
change= self._whatchange(
self.on_scale, *args )
self.user_act( change )
def on_rotate( self, *args ):
change= self._whatchange(
self.on_rotate, *args )
self.user_act( change )
@incremental( 1 )
def layout_return( self, layoutchange ):
renderchange( layoutchange )
@incremental( 2 )
def layout_return( self, layoutchange ):
renderchange( layoutchange )
@message
def time_estimate( self, etc ):
report( etc )

class InterfaceServerSide( ServerSide ):
message= MessageDec()
incremental= message.incremental()
settings= AYT( .5, 3 )
time_estimate= message.out()
layout_return= incremental()
def __init__( self, image ):
self._image= image
ServerSide.__init__( self )
@message.intervene()
def user_act( self, change ):
etc= self.calculateeta( change )
self.time_estimate( etc )
preliminary= self.calculation()
preliminary_change= whatchange( preliminary )
self.layout_return( preliminary_change )
completed= self.other_calculation()
completed_change= whatchange( completed )
self.layout_return( completed_change )
self.layout_return.finish()

'''
Another use ClientSide and ServerSide should support is a peer-to-peer
chat-and-game server.  And that said, it's not clear that there's any
distinction between ServerSide and ClientSide anyway, depending on
exactly how the listen and connect methods abstract.  How much of the
implementation do they share?  Most.

You could mark 'time_estimate' as incremental( 3 ); they're separated
for illustration purposes.

One remaining question is how to intervene in user_act, if a second
change arrives before the previous complete.  You could combine the
earlier change parameter in the new call and throw an exception in the
thread handling the earlier one at its first loss of control--- and
maybe even at once with settrace!  That tends to be costly.  Not to
mention, change has already entered derived-class space.  ServerSide
should make sure it's easy enough to address the issue on one's own,
and @message.nonintervene() is available too.
'''
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First post from a Python newbiw

2008-03-02 Thread Christoph Zwerschke
Marc 'BlackJack' Rintsch schrieb:
> On Sun, 02 Mar 2008 14:15:09 +, Steve Turner wrote:
> 
>> Apart from doing something like
>> a=[0,0,0]
>> b=[0,0,0]
>> c=[0,0,0]
>> d=[a,b,c]
>>
>> is there a better way of creating d??
> 
> a = [[0] * 3 for dummy in xrange(3)]

Why not simply [[0]*3]*3 ?

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


[ANN] Python 2.3.7 and 2.4.5, release candidate 1

2008-03-02 Thread Martin v. Löwis
On behalf of the Python development team and the Python community, I'm
happy to announce the release candidates of Python 2.4.5 and 2.4.5.

Both releases include only security fixes. Python 2.5 is the latest
version of Python, we're making this release for people who are still
running Python 2.3 or 2.4.

See the release notes at the website (also available as Misc/NEWS in
the source distribution) for details of bugs fixed; most of them prevent
interpreter crashes (and now cause proper Python exceptions in cases
where the interprerter may have crashed before).

Assuming no major problems crop up, a final release of Python 2.4.4 will
follow in about a week's time.

For more information on Python 2.3.7 and 2.4.5, including download
links for various platforms, release notes, and known issues, please
see:

 http://www.python.org/2.3.7
 http://www.python.org/2.4.5

Highlights of the previous major Python releases are available
from the Python 2.4 page, at

 http://www.python.org/2.3/highlights.html
 http://www.python.org/2.4/highlights.html

Enjoy this release,
Martin

Martin v. Loewis
[EMAIL PROTECTED]
Python Release Manager
(on behalf of the entire python-dev team)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuples, index method, Python's design

2008-03-02 Thread Alan Isaac
Paul Boddie wrote:

> Here's the tracker item that may have made it happen:

> http://bugs.python.org/issue1696444 

> I think you need to thank Raymond Hettinger for championing the 

> cause. ;-)





Yes indeed!

Alan Isaac


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


Re: Altering imported modules

2008-03-02 Thread Tro
On Saturday 01 March 2008, Tro wrote:
> 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.

I guess I could just copy over the relevant tlslite file that imports asyncore 
and change the import, but that seems clumsy.

Is there no better way?

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


Re: tcp

2008-03-02 Thread Gif
thanks everybody, i've got this to work. i'm not trying to write an
actual web server, i'm just using it for some procedures like URL
rewriting.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RELEASED Python 2.6a1 and 3.0a3

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

> On 2 Mrz., 06:53, Ben Finney <[EMAIL PROTECTED]>
> wrote:
> 
> > One of the stated goals of the migration is that the '2to3'
> > program will only migrate Python 2.6 code -> Python 3.0 code.
> 
> Yes, I know. Why?
> 
> "The master said so" isn't an entirely satisfying answer.

The people putting in the work to write '2to3' said so.

-- 
 \"Courteous and efficient self-service." —Café sign, southern |
  `\France |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: First post from a Python newbiw

2008-03-02 Thread Steve Turner
Christoph Zwerschke wrote: 

: Marc 'BlackJack' Rintsch schrieb:
:: On Sun, 02 Mar 2008 14:15:09 +, Steve Turner wrote:
:: 
::: Apart from doing something like
::: a=[0,0,0]
::: b=[0,0,0]
::: c=[0,0,0]
::: d=[a,b,c]
::: 
::: is there a better way of creating d??
:: 
:: a = [[0] * 3 for dummy in xrange(3)]
: 
: Why not simply [[0]*3]*3 ?

I've just tried that and it gives the same as my earlier b=[a,a,a]

-- 
Steve

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


Run Python app at startup

2008-03-02 Thread SMALLp
Hy.
I create simple application. Yust an windows and "compile" it with
py2exe. I add registry  value
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v
MyApp /t REG_SZ /d C:\myapp.exe /f'

And it wont start. When i use console instead od window in py2exe i get
console opend but it closes.

Program:

import os
import wx

app = wx.App()
frame = wx.Frame(None, -1, "MyFrame")
frame.Show()

app.MainLoop()


Then in commang prompt:

python.exe setup.py py2exe



from distutils.core import setup
import py2exe

setup(console=['prog.py'])


Help please!


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


Re: tuples, index method, Python's design

2008-03-02 Thread Christoph Zwerschke
Paul Boddie schrieb:
> On 2 Mar, 19:06, Alan Isaac <[EMAIL PROTECTED]> wrote:
>> On April 12th, 2007 at 10:05 PM Alan Isaac wrote:
>>
>>> The avoidance of tuples, so carefully defended in other
>>> terms, is often rooted (I claim) in habits formed from
>>> need for list methods like ``index`` and ``count``.
>>> Indeed, I predict that Python tuples will eventually have
>>> these methods and that these same people will then defend
>>> *that* status quo.
> 
> You were more confident about this than I was. Still, nothing happens
> if no-one steps up to do something about it.

And nobody stepped up because it had been made very clear by Guido and 
others that they don't want tuples to grow methods.

I remember there had been ridiculously excessive threads about this, 
this probably being one of many others:
http://groups.google.de/group/comp.lang.python/browse_thread/thread/430a692bc634a04f/

I don't think this was very encouraging for people who wanted to do 
something about it.

Anyway, it's good to see this happened now. Thanks to Raymond.

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


sympy: nifty, but... (was: How about adding rational fraction to Python?)

2008-03-02 Thread Mensanator
On Mar 1, 12:29 pm, "Anand Patil" <[EMAIL PROTECTED]>
wrote:
> Not sure if this is common knowledge yet but 
> Sympy,http://code.google.com/p/sympy, has a rational type.

I hadn't heard of this before, thanks for the link.

Very nifty, lots of goodies not found in gmpy (although
it seems to lack a modular inverse function and the linear
congruence solver that can be derived from it making it
of no value to me).

Alas, it's written in Python. Who writes a math library
in Python?

Nevertheless, I thought I would try out the Rational numbers.

Once I figured out how to use them, I converted my Polynomial
Finder by Newton's Forward Difference Method program to use
sympy instead of gmpy.

I have a test case where I create 1 66 degree polynomial where
the coefficients are large rationals. The polynomial was
calculated flawlessly


## sympy
##  Term0: [66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66,
-66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66,
66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66,
-66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66,
66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, 0]
##
##Seq: [66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 66]
##
##The Polynomial:
##
##
##1
##
---
*  n**66
##
8247650592082470666723170306785496252186258551345437492922123134388955774976000
##
##
##-67
##
--
*  n**65
##
249928805820680929294641524448045340975341168222589014937034034375422902272000
##
##
##67
##
---
*  n**64
##
230703513065243934733515253336657237823391847590082167634185262500390371328

But because they are calculated using Python,
it took 175 seconds compared to 0.2 seconds
for gmpy to do the same polynomial.

So, I'll keep it around for it's neat features
that gmpy doesn't have, but it won't replace gmpy
for any serious work.


>
> 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: Book Recomendations

2008-03-02 Thread Jeff Schwab
 > Ira Solomon wrote:
 >> I am an experienced programmer (40 years) . . .
 >> I'm interested in learning Python

 > js wrote:
 >> I wonder why nobody mension Python Cookbook yet . . .
 >> and Python Standard Library

Because cookbooks are not supposed to be language introductions.  They 
are collections of non-obvious techniques, for use by people already 
familiar with a core language and its standard libraries.  Python in 
particular offers a lot for traditional programmers to wrap their minds 
around before considering cookbooks; Programming Python, for example, 
purports to help programmers think Pythonically, and probably belongs 
chronologically between the introductory books and the cookbooks.

Many programmers coming from different languages tend (at first) to 
write code that makes experienced Pythonistas cringe.  Effective use of 
the language depends on an understanding of its extremely dynamic 
nature, which can be tough to grasp for those of us coming from compiled 
language backgrounds.  It seems to me, based purely on discussions seen 
in comp.lang.python, that even folks coming from relatively dynamic 
languages like Lisp often underestimate the level of run-time 
indirection provided by Python.  One of the neat things about the 
Nutshell book is that it shows how even the process of resolving object 
attributes is potentially complicated, and how the new 'type' metaclass 
helps to at least make the process more consistent than with old-style 
objects.

Experienced programmers first have to learn that an expression like 
"a.x" means something very different in Python from what it means 
elsewhere; then, they can begin leveraging these language features to do 
the sorts of things illustrated in the cookbooks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Altering imported modules

2008-03-02 Thread Terry Reedy

"Tro" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| 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.

If your module is also 'asyncore' and comes earlier in the search path, I 
would expect the import to get yours. 



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


Re: First post from a Python newbiw

2008-03-02 Thread Marc 'BlackJack' Rintsch
On Sun, 02 Mar 2008 21:58:31 +0100, Christoph Zwerschke wrote:

> Marc 'BlackJack' Rintsch schrieb:
>> On Sun, 02 Mar 2008 14:15:09 +, Steve Turner wrote:
>> 
>>> Apart from doing something like
>>> a=[0,0,0]
>>> b=[0,0,0]
>>> c=[0,0,0]
>>> d=[a,b,c]
>>>
>>> is there a better way of creating d??
>> 
>> a = [[0] * 3 for dummy in xrange(3)]
> 
> Why not simply [[0]*3]*3 ?

Because:

In [77]: a = [[0] * 3] * 3

In [78]: a
Out[78]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

In [79]: a[0][0] = 42

In [80]: a
Out[80]: [[42, 0, 0], [42, 0, 0], [42, 0, 0]]

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


  1   2   >