Re: Namespaces/introspection: collecting sql strings for validation

2007-04-22 Thread Martin Drautzburg
George Sakkis wrote:

> Yes, there is: use an ORM to do the SQL generation for you. Check out
> SQLAlchemy, it will buy you much more than what you asked for.

Might look, though in general I don't like OR mappers much. Having SQL
generated feels as strange as having python code generated. Too much
magic, too many layers. I think it is better to simply learn SQL.

And I don't really believe in OO databases much. OO databases have been
around for several decades and still have not reached the maturity of
relational databases. My feeling is that OO and persistence to not play
together well.

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


Re: serializable object references

2007-04-22 Thread Martin Drautzburg
Gabriel Genellina wrote:

> En Sun, 22 Apr 2007 12:47:10 -0300, Martin Drautzburg
> <[EMAIL PROTECTED]> escribió:
> 
>> I was thinking that it would be nice if a web application could talk
>> to real objects. The client side does not need to know the internals
>> of an object, it acts as a "view" for server-side models. All it has
>> to be able to do is invoke methods on "its" model. So a view could
>> just store "its" object-reference in an instance variable and pass it
>> to the server, where my problem of looking it up comes in.
> 
> This is more or less what several web frameworks do. You publish
> objects; URLs are mapped to method objects; URL parameters become
> method parameters. See http://wiki.python.org/moin/WebFrameworks
> 

Okay will look. I have checked out cherrypy, but it does not seem to
support direct object references, i.e. the server-side objects are
really stateless and all calls to an object method will see the same
state unless you do something about it youself.

I have also looked at the wonderful qooxdoo javascript framework and in
the examples they have, the data I receive on a published object method
on my cherrypy server is:
dict: {
'_ScriptTransport_id': '11',
'_ScriptTransport_data': '{
"service":"qooxdoo.test",
"method":"sleep",
"id":13,
"params":["10"],
"server_data":null
}',
'nocache': '1177256001914'
}

I am not sure what all of them mean, but my impression is that none of
them denote an object in the sense of an INSTANCE, at least "service"
and "method" definitely do not. The "id" is simply incremented with
every call, so it is again not an instance.

Now I could of course add an object reference do the "params" field and
have qooxdoo.text dispatch the call to an INSTANCE of an object and
invoke sleep() there. But first it is a shame, that I have to provide
this magic myself, and second it raises again my original question: how
to I pass an object reference and look up the object in qooxdoo.test. 

I know I can do this with a dictionary, I just thought that the
__repr__() of an object could be used, as it seems the most obvious way
to do it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionaries and dot notation

2007-04-22 Thread Martin Drautzburg
Alex Martelli wrote:

> Martin Drautzburg <[EMAIL PROTECTED]> wrote:
> 
>> > mydata = data( )
>> > mydata.foo = 'foo'
>> > mydata.bar = 'bar'
>> > 
>> > print mydata.foo
>> > print mydata.bar
>> 
>> I am aware of all this.
>> Okay let me rephrase my question: is there a way of using dot
>> notation without having to create a class?
> 
> Sure, all you need to create is an *INSTANCE* of a suitable type or
> class.  For example:
> 
 d = dict(foo=23, bar=45)
 m = new.module('for_martin')
 m.__dict__.update(d)
 m.foo
> 23
 m.bar
> 45
 
> 
> A module may be appropriate, since it's little more than a "wrapper
> around a dict to access items by dot notation":-).

Thanks, I finally got it. Even your previous example actually does the
trick. I did not notice that I can use a single class (or a module) for
all my datastructures, because I can "plug in" new attributes into the
instance without the class knowing about them. 

I was mistaken to believe that I had to know about attributes at the
time of class creation. But your expample does not require that. Should
have read this more carefully.

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


Re: Select weirdness

2007-04-22 Thread Irmen de Jong
Ron Garret wrote:
> I don't understand why socketserver calling select should matter.  (And 
> BTW, there are no calls to select in SocketServer.py.  I'm using 
> Python2.5.)

You don't *need* a select at all.
Socketserver just blocks on accept() and dispatches a handler
on the new connection.


>> Anyway, try the following instead:
>>
> 
> That won't work for POST requests.
>

Why not?
Just add some more code to deal with the POST request body.
There should be a content-length header to tell you how many
bytes to read after the header section has finished.

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


Socket exceptions aren't in the standard exception hierarchy

2007-04-22 Thread John Nagle
Here are three network-related exceptions.  These
were caught by "except" with no exception type, because
none of the more specific exceptions matched.   This
is what a traceback produced:


1. File "D:\Python24\lib\socket.py", line 295, in read
data = self._sock.recv(recv_size)
timeout: timed out  

2. File "D:\Python24\lib\socket.py", line 295, in read
data = self._sock.recv(recv_size)
error: (10054, 'Connection reset by peer')

3. File "D:\Python24\lib\socket.py", line 317, in readline
data = recv(1)
IOError: [Errno socket error] timed out

For 1 and 2, those are errors that aren't in the
exception hierarchy.  Looking at the C code for "socketmodule.c",
it's clear that "socket.error" doesn't inherit from any standard
exception class.  See, in "init_socket()":

 socket_error = PyErr_NewException("socket.error", NULL, NULL);

That first NULL should be some parent exception, maybe "IOError".
As it is, "socket.error" is outside the standard exception hierarchy.
That's not too good.

Case #3, IOError, should have been caught by this:

except IOError, message:# I/O error

But it wasn't.  The "IOError" fell through, was caught by the
next outer exception block, and was logged as a generic
error.

I can't find where in the Python socket module an "IOError"
could be raised.  I would have expected "socket.timeout".

Anyway, I need to know the full set of exceptions that can
be raised by sockets.  Thanks.

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


Re: Namespaces/introspection: collecting sql strings for validation

2007-04-22 Thread Peter Otten
Martin Drautzburg wrote:

> > def SQL(sql, checked=set()):
> > if sql in checked:
> > return True
> > if not valid_sql(sql): raise ValueError
> > checked.add(sql)
> > return sql
> 
> No this does not do the trick. I will not be able to validate an sql
> statement bofore I run over the piece of code that uses it. Or I would
> have to define all my sql = SQL stuff on module level, isn't id. I
> mean, the problem is: when are those sql = SQL statement really
> ececuted?

Let's see:

>>> def SQL(sql):
... print sql
...
>>> a = SQL("module")
module # that one was obvious
>>> class A:
... b = SQL("class")
... def method(self, c=SQL("default arg")):
... d = SQL("method")
...
class # ha, class statements are executed, too...
default arg # ...as are default arguments

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


Re: python style guide inconsistencies

2007-04-22 Thread Martin v. Löwis

> I have the impression that tradition will change in 3.0 and your preference 
> realized.
> Wrong? or have you not been following?

I have not been following, so this might be the case.

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


Re: Python's handling of unicode surrogates

2007-04-22 Thread Martin v. Löwis
> The Unicode standard doesn't require that you support surrogates, or
> any other kind of character, so no you wouldn't be lying.

There is the notion of Unicode implementation levels, and each of them
does include a set of characters to support. In level 1, combining
characters need not to be supported (which is sufficient for scripts
that can be represented without combining characters, such as Latin
and Cyrillic, using precomposed characters if necessary). In level 2,
combining characters must be supported for some scripts that absolutely
need them, and in level 3, all characters must be supported.

It is probably an interpretation issue what "supported" means. Python
clearly supports Unicode level 1 (if we leave alone the issue that it
can't render all these characters out of the box, as it doesn't ship
any fonts); it could be argued that it implements level 3, as it is
capable of representing all Unicode characters (but, of course, so
does Python 1.5.2, if you put UTF-8 into byte strings).

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


Re: Support for new items in set type

2007-04-22 Thread Prateek
Oh dear god, I implemented this and it overall killed performance by
about 50% - 100%. The same script (entering 3000 items) takes between
88 - 109s (it was running in 55s earlier).

Here is the new Set implementation:
class SeaSet(set):
__slots__ = ['master', 'added', 'deleted']
def __init__(self, s=None):
if s is None: s = []
self.master = set(s)
self.added = set()
self.deleted = set()

def add(self, l):
if l not in self.master:
self.added.add(l)
try:
self.deleted.remove(l)
except KeyError:
pass

def remove(self, l):
try:
self.master.remove(l)
self.deleted.add(l)
except KeyError:
try:
self.added.remove(l)
except KeyError:
pass

def __contains__(self, l):
if l in self.deleted:
return False
elif l in self.added:
return True
else:
return l in self.master

def __len__(self):
return len(self.master) + len(self.added)

def __iter__(self):
for x in self.master:
yield x
for x in self.added:
yield x

def __or__(self, s):
return self.union(s)

def __and__(self, s):
return self.intersection(s)

def __sub__(self, s):
return self.difference(s)

def union(self, s):
"""docstring for union"""
if isinstance(s, (set, frozenset)):
return s | self.master | self.added
elif isinstance(s, SeaSet):
return self.master | self.added | s.master | s.added
else:
raise TypeError

def intersection(self, s):
"""docstring for intersection"""
if isinstance(s, (set, frozenset)):
return s & self.master & self.added
elif isinstance(s, SeaSet):
return self.master & self.added & s.master & s.added
else:
raise TypeError

def difference(self, s):
"""docstring for difference"""
if isinstance(s, (set, frozenset)):
self.deleted |= (self.master - s)
self.master -= s
self.added -= s
elif isinstance(s, SeaSet):
t = (s.master | s.deleted)
self.deleted |= self.master - t
self.master -= t
self.added -= t
else:
raise TypeError


The surprising thing is that commits *ARE* running about 50% faster
(according to the time column in the hotshot profiler). But, now, the
longest running operations seem to be the I/O operations which are
taking 10 times longer! (even if they're only reading or writing a few
bytes. Could this have something to do with the set implementation
being in Python as opposed to C?

For instance, this method:
def __readTableHeader(self, f):
hdr = f.read(sz__TABLE_HEADER_FORMAT__)
if len(hdr) < sz__TABLE_HEADER_FORMAT__:
raise EOFError
t = THF_U(hdr)
#t = unpack(__TABLE_HEADER_FORMAT__, hdr)
return t

is now taking > 13s when it was taking less than 0.8s before! (same
number of calls, nothing changed except the set implementation)

sz__TABLE_HEADER_FORMAT__ is a constant = struct.calcsize("http://mail.python.org/mailman/listinfo/python-list


Re: Python's handling of unicode surrogates

2007-04-22 Thread Martin v. Löwis
> IMHO what is really needed is a bunch of high level methods like
> .graphemes() - iterate over graphemes
> .codepoints() - iterate over codepoints
> .isword() - check if the string represents one word
> etc...

This doesn't need to come as methods, though. If anybody wants to
provide a library with such functions, they can do so today.

I'd be hesitant to add methods to the string object with no proven
applications.

IMO, the biggest challenge in Unicode support is neither storage
nor iteration, but it's output (rendering, fonts, etc.), and,
to some degree, input (input methods). As Python has no "native"
GUI library, we currently defer that main challenge to external
libraries already.

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


Re: recursion depth problem

2007-04-22 Thread proctor
On Apr 22, 8:23 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
> Steven Bethard <[EMAIL PROTECTED]> wrote:
>
>...
>
>
>
> > > import sys
> > > def ch4(item, n=0):
> > >if n < len(item):
> > >if item[n] == '0':
> > >item[n] = '1'
> > >print ''.join(item)
> > >ch4(item)
> > >elif item[n] == '1':
> > >item[n] = '0'
> > >ch4(item, n+1)
> > > ch4(list(sys.argv[1]))
>...
> > > for interest sake:  is my method unredeemable?
>
> > Let's just say that I don't currently see an obvious way of redeeming
> > it. ;-)
>
> Change the outer if into a while, and the recursive calls into proper
> assignments to n.  They're both tail-recursive calls, so this won't
> change the semantics, as it happens.
>
> Alex

really helpful!  thank you very much!

proctor.

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


Initial Release: latexmath2png

2007-04-22 Thread Kamil Kisiel
This past week I cleaned up and released some of my code for
converting LaTeX math equations in to PNG images. The current concept
is to have a useful unix-style command line utility as well as a
module that can be embedded in to other applications such as wikis,
CMSs, etc. I've released it under an MIT license. The concept is based
on an article by Kjell Fauske: http://www.fauskes.net/nb/htmleqII/ and
some old code I wrote as a result several years ago.

Currently there is only support for rendering individual equations as
in the $...$ math environment in LaTeX, but I will be adding support
for the equation and equation array environments in the future.

Project page on Google Code:
http://code.google.com/p/latexmath2png/

Some more details in my blog post:
http://kamilkisiel.blogspot.com/2007/04/presenting-latexmath2png.html

Please give it a try as I'd like to hear how it works for others. I
welcome any comments, patches, and requests.

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


Re: recursion depth problem

2007-04-22 Thread proctor
On Apr 22, 9:28 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On 22 Apr 2007 19:13:31 -0700, proctor <[EMAIL PROTECTED]> declaimed the
> following in comp.lang.python:
>
>
>
> > :-)
>
> > this is good stuff.  for learning especially!  thank you again!
>
> Took me some time to find... My 30year old BugBooks* are in storage,
> along with all the other raw comp-sci texts.
>
> What you see above is a Python implementation of a 2 1-bit input,
> 1-bit sum and 1-bit carry output, full-adder from basic AND/OR/XOR gates
> -- you can build the hardware equivalent (except for the variable
> length) using old-fashioned 74xx chips (are 74xx TTL chips still made,
> or will one need to use the 74Cxx CMOS variants ) [heck; is the
> multi-function ALU chip still made?]
>
> *   The Virginia Tech shootings were just a blip on my radar until I
> read that this was Blacksburg -- as I once had most of the Blacksburg
> BugBooks
> --
> WulfraedDennis Lee Bieber   KD6MOG
> [EMAIL PROTECTED] [EMAIL PROTECTED]
> HTTP://wlfraed.home.netcom.com/
> (Bestiaria Support Staff:   [EMAIL PROTECTED])
> HTTP://www.bestiaria.com/

well i'm going to make it a project to understand properly this
program.

proctor.

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


Re: recursion depth problem

2007-04-22 Thread [EMAIL PROTECTED]
On Apr 22, 9:13�pm, proctor <[EMAIL PROTECTED]> wrote:
> On Apr 22, 7:10 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On 22 Apr 2007 17:06:18 -0700, proctor <[EMAIL PROTECTED]> declaimed the
> > following in comp.lang.python:
>
> > > > � � else:
> > > > � � � � # only one of carry in, b1, or b2 is set
>
> > � � � � � � � � � � � � #or none is set! Missed the 0,0,0 condition 
>
> > > > � � � � return (0, b1 + b2 + c)
>
> > > thank you. �you guys are keeping me busy!
>
> > � � � � Heh... I'm sure what I scratched together could be optimized more
> > (make functions out of the input/output conversions; add some error
> > checking on input data, allow for non-list arguments in adder()...)
>
> > � � � � After all, if one wants a binary counter, one should implement a
> > binary addition operation, and basic digital has ways... Unfortunately,
> > Python now has a Boolean type, so boolean AND/OR doesn't give the
> > desired results... And using bitwise seems wasteful  However...
> > replace the badd() with the following obscure thing if you really want
> > to get close to hardware emulation...
>
> > def badd(b1, b2, ci=0):
> > � � """
> > � � � � badd(b1, b2, ci) => (co, sum)
> > � � """
> > � � (co1, hs1) = (b1 & b2, b1 ^ b2)
> > � � (co2, hs2) = (ci & hs1, ci ^ hs1)
> > � � return (co1 | co2, hs2)
>
> > � � � � A pair of "half-adders"; and the extra bit to make a "full-adder".
> > It wouldn't be efficient to do it as one long return, just due to
> > duplicated (b1 ^ b2) sub-terms
>
> > return ( (b1 & b2) | (ci & (b1 ^ b2)), (ci ^ (b1 ^ b2)))
>
> > but it does work 
> > --
> > � � � � Wulfraed � � � �Dennis Lee Bieber � � � � � � � KD6MOG
> > � � � � [EMAIL PROTECTED] � � � � � � [EMAIL PROTECTED]
> > � � � � � � � � HTTP://wlfraed.home.netcom.com/
> > � � � � (Bestiaria Support Staff: � � � � � � � [EMAIL PROTECTED])
> > � � � � � � � � HTTP://www.bestiaria.com/
>
> :-)
>
> this is good stuff. �for learning especially! �thank you again!

I once made a complete full adder in perl with strings
so that I could have unlimited precision (this is before I found
out about Big Arithmetic libraries). Since I was only doing the
Collatz Conjecture, all I needed was to multiply by 3 (shift
left by appending '0' to string and adding to original string
using the full adder), dividing by two (shift right by slicing
off rightmost character from string) and incrementing
(pre-set the carry bit to '1').

It worked perfectly.

But it was slower than snake shit.

>
> proctor

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

Re: Dictionaries and dot notation

2007-04-22 Thread Alex Martelli
Martin Drautzburg <[EMAIL PROTECTED]> wrote:

> > mydata = data( )
> > mydata.foo = 'foo'
> > mydata.bar = 'bar'
> > 
> > print mydata.foo
> > print mydata.bar
> 
> I am aware of all this.
> Okay let me rephrase my question: is there a way of using dot notation
> without having to create a class?

Sure, all you need to create is an *INSTANCE* of a suitable type or
class.  For example:

>>> d = dict(foo=23, bar=45)
>>> m = new.module('for_martin')
>>> m.__dict__.update(d)
>>> m.foo
23
>>> m.bar
45
>>> 

A module may be appropriate, since it's little more than a "wrapper
around a dict to access items by dot notation":-).


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


Re: recursion depth problem

2007-04-22 Thread Steven Bethard
Alex Martelli wrote:
> Steven Bethard <[EMAIL PROTECTED]> wrote:
>...
>>> import sys
>>> def ch4(item, n=0):
>>>if n < len(item):
>>>if item[n] == '0':
>>>item[n] = '1'
>>>print ''.join(item)
>>>ch4(item)
>>>elif item[n] == '1':
>>>item[n] = '0'
>>>ch4(item, n+1)
>>> ch4(list(sys.argv[1]))
>...
>>> for interest sake:  is my method unredeemable?
>> Let's just say that I don't currently see an obvious way of redeeming
>> it. ;-)
> 
> Change the outer if into a while, and the recursive calls into proper
> assignments to n.  They're both tail-recursive calls, so this won't
> change the semantics, as it happens.

Thanks!

 >>> def f(chars):
 ... n = 0
 ... while n < len(chars):
 ... if chars[n] == '0':
 ... chars[n] = '1'
 ... n = 0
 ... print ''.join(chars)
 ... elif chars[n] == '1':
 ... chars[n] = '0'
 ... n += 1
 ...
 >>> f(list(''))
 1000
 0100
 1100
 ...
 1011
 0111
 

Looks good.

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


Re: Dictionaries and dot notation

2007-04-22 Thread Ben Finney
Martin Drautzburg <[EMAIL PROTECTED]> writes:

> Okay let me rephrase my question: is there a way of using dot
> notation without having to create a class?

Dot notation, e.g. 'foo.bar', is parsed by the interpreter as "access
the attribute named 'bar' of the object 'foo'". Objects have
attributes either by virtue of the class having them, or the object
getting them assigned after creation.

Can you describe what you would change in the above, or can you
re-word your request based on these facts?

-- 
 \   "Our products just aren't engineered for security."  -- Brian |
  `\ Valentine, senior vice-president of Microsoft Windows |
_o__)  development |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Javascript equivalence

2007-04-22 Thread 7stud
On Apr 22, 7:00 pm, "Sam the Cat" <[EMAIL PROTECTED]> wrote:
> Hey All,
>
> I am writing some COM code in Python to control photoshop.  Several
> functions of PS require an "Array" argument.  In the examples of VBscript or
> javascript the Array type is used.  I have tried what would appear to be the
> equivalent in Python -- Lists and Tuples -- but to no avail.  Anyone have
> any insight  on what via the COM interface is equivalent to an Array in
> javascript ?
>
> Cheers
> Sam

See if the python array type works:

import array

y = array.array("i", [2,3,4])
print y



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


Re: Namespaces/introspection: collecting sql strings for validation

2007-04-22 Thread Alex Martelli
Martin Drautzburg <[EMAIL PROTECTED]> wrote:
   ...
> The problem is the first part: how can I lookup the callers module and
> the classobjs defined in there? Or finding any constant strings in the
> caller's module would also be just fine. Or is there a completely
> different way to do such a thing?

Don't do black magic in production code.

For just hacking around, see sys._getframe -- it can give you a frame
object from where you can introspect into your caller's globals -- and
the inspect module of the standard Python library.

But don't put such black magic in production.  The completely different
way is: just don't.


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


Re: Python and Javascript equivalence

2007-04-22 Thread Prateek

Try creating a dict with sequential numeric keys.

If you already have a list called my_list, you can do:

com_array = dict(zip(range(len(my_list)), my_list))

This works when you want to convert Python objects to Javascript using
JSON. It may work for you.

-Prateek

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


inspect.getblock()

2007-04-22 Thread Aaron Brady
inspect.getblock() seems to halt prematurely.  This code only prints 6 
lines of the 12 line input file.


assume it's by design, but the docs don't mention getblock.  docstring is 
"Extract the block of code at the top of the given list of lines," which 
should be "code *from* the top."


###whatiscompile2.py
import inspect

r = open('thebogusfile.txt').read()
code = compile( r, 'thebogusfile.txt', 'exec' )
exec code

print '***'
print inspect.getsource(code)

###thebogusfile.txt
def f(a, b):
print a,
print b,
c = a + b
print c,
return a + b

def g():
print 'g'

print f( 3, 4 ),
g()

###stdout
3 4 7 7 g
***
def f(a, b):
print a,
print b,
c = a + b
print c,
return a + b
def f(a, b):

print a,

print b,

c = a + b

print c,

return a + b



def g():

print 'g'



print f( 3, 4 ),

g()

import inspect



r = open('the bogus file.txt').read()

code = compile( r, 'the bogus file.txt', 'exec' )

exec code



print '***'

print inspect.getsource(code)

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

Re: pickled object, read and write..

2007-04-22 Thread Prateek
On Apr 22, 11:40 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> Hi all.
>
> I have to put together some code that reads high scores from a saved
> file, then gives the user the opportunity to add their name and score
> to the high scores list, which is then saved.
>
> Trouble is, I can't tell the program to read a file that doesn't
> exist, that generates an error.
>
> So I must have a file created, problem HERE is everytime the program
> is run, it will overwrite the current list of saved high scores.
>
> Advice would be much appreciated.

Try the following idiom:

try:
try:
fp = open("filename", 'r+')
except IOError:
fp = open("filename", 'w+')

fp.write(high_score)
finally:
fp.close()


-Prateek

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


Re: recursion depth problem

2007-04-22 Thread Alex Martelli
Steven Bethard <[EMAIL PROTECTED]> wrote:
   ...
> > import sys
> > def ch4(item, n=0):
> >if n < len(item):
> >if item[n] == '0':
> >item[n] = '1'
> >print ''.join(item)
> >ch4(item)
> >elif item[n] == '1':
> >item[n] = '0'
> >ch4(item, n+1)
> > ch4(list(sys.argv[1]))
   ...
> > for interest sake:  is my method unredeemable?
> 
> Let's just say that I don't currently see an obvious way of redeeming
> it. ;-)

Change the outer if into a while, and the recursive calls into proper
assignments to n.  They're both tail-recursive calls, so this won't
change the semantics, as it happens.


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


Re: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident ***

2007-04-22 Thread joseph2k
[EMAIL PROTECTED] wrote:

> Dr Gideon Polya published some 130 works in a 4 decade scientific
> career, most recently a huge pharmacological reference text
> "Biochemical Targets of Plant Bioactive Compounds" (Taylor & Francis,
> New York & London, 2003), and is currently editing a completed book on
> global avoidable mortality (numerous articles on this matter can be
> found by a simple Google search for "Gideon Polya" and on his
> websites:
> 
> Here is the BRILLIANT AND INCISIVE ANALYSIS:
> 
> http://countercurrents.org/polya230407.htm <--
> 
> Dr Polya, we are incredibly proud of you. God Bless you for your
> courage.
That certainly does not qualify as analysis, and clearly falls short of
brilliant or incisive let alone both together.
-- 
 JosephKK
 Gegen dummheit kampfen die Gotter Selbst, vergebens.  
  --Schiller
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: recursion depth problem

2007-04-22 Thread proctor
On Apr 22, 7:34 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
> proctor wrote:
> > On Apr 22, 2:06 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
> >> proctor wrote:
> >>> On Apr 22, 1:24 pm, Michael Bentley <[EMAIL PROTECTED]> wrote:
>  On Apr 22, 2007, at 1:49 PM, proctor wrote:
> > i have a small function which mimics binary counting.  it runs fine as
> > long as the input is not too long, but if i give it input longer than
> > 8 characters it gives
> > RuntimeError: maximum recursion depth exceeded in cmp
> > i'm not too sure what i am doing improperly.  is there really a lot of
> > recursion in this code?
> > ==
> > import sys
> > def ch4(item, n=0):
> >if n < len(item):
> >if item[n] == '0':
> >item[n] = '1'
> >print ''.join(item)
> >ch4(item)
> >elif item[n] == '1':
> >item[n] = '0'
> >ch4(item, n+1)
> > ch4(list(sys.argv[1]))
> > ==
>  Yes.  There really is *that* much recursion in that code.  502 levels
>  with input length of 8 characters, 1013 with 9 characters, 2035 with
>  10 characters...  There's a pattern there ;-)
> >>> ok, thanks michael!
> >>> is there a way to avoid it here?  how could i write this better, (if
> >>> at all)?
> >> Google for permutation-like recipies:
>
> >>  http://www.google.com/search?q=Python+permutations
>
> >> Use the code from the first hit::
>
> >>  >>> for x in xselections('01', 8):
> >>  ... print ''.join(x)
> >>  ...
> >>  
> >>  0001
> >>  0010
> >>  ...
> >>  1101
> >>  1110
> >>  
>
> >> Explaining to your teacher why your code uses generators when you
> >> haven't been taught them yet is left as an exercise to the reader. ;-)
>
> >> STeVe
>
> > this is really nice, thanks steve.  much slicker than my code.
>
> > for interest sake:  is my method unredeemable?
>
> Let's just say that I don't currently see an obvious way of redeeming
> it. ;-)
>
> STeVe

lol.  okay.

proctor.


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


Re: recursion depth problem

2007-04-22 Thread proctor
On Apr 22, 7:10 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On 22 Apr 2007 17:06:18 -0700, proctor <[EMAIL PROTECTED]> declaimed the
> following in comp.lang.python:
>
> > > else:
> > > # only one of carry in, b1, or b2 is set
>
> #or none is set! Missed the 0,0,0 condition 
>
> > > return (0, b1 + b2 + c)
>
> > thank you.  you guys are keeping me busy!
>
> Heh... I'm sure what I scratched together could be optimized more
> (make functions out of the input/output conversions; add some error
> checking on input data, allow for non-list arguments in adder()...)
>
> After all, if one wants a binary counter, one should implement a
> binary addition operation, and basic digital has ways... Unfortunately,
> Python now has a Boolean type, so boolean AND/OR doesn't give the
> desired results... And using bitwise seems wasteful  However...
> replace the badd() with the following obscure thing if you really want
> to get close to hardware emulation...
>
> def badd(b1, b2, ci=0):
> """
> badd(b1, b2, ci) => (co, sum)
> """
> (co1, hs1) = (b1 & b2, b1 ^ b2)
> (co2, hs2) = (ci & hs1, ci ^ hs1)
> return (co1 | co2, hs2)
>
> A pair of "half-adders"; and the extra bit to make a "full-adder".
> It wouldn't be efficient to do it as one long return, just due to
> duplicated (b1 ^ b2) sub-terms
>
> return ( (b1 & b2) | (ci & (b1 ^ b2)), (ci ^ (b1 ^ b2)))
>
> but it does work 
> --
> WulfraedDennis Lee Bieber   KD6MOG
> [EMAIL PROTECTED] [EMAIL PROTECTED]
> HTTP://wlfraed.home.netcom.com/
> (Bestiaria Support Staff:   [EMAIL PROTECTED])
> HTTP://www.bestiaria.com/

:-)

this is good stuff.  for learning especially!  thank you again!

proctor.

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


Re: recursion depth problem

2007-04-22 Thread Steven Bethard
proctor wrote:
> On Apr 22, 2:06 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
>> proctor wrote:
>>> On Apr 22, 1:24 pm, Michael Bentley <[EMAIL PROTECTED]> wrote:
 On Apr 22, 2007, at 1:49 PM, proctor wrote:
> i have a small function which mimics binary counting.  it runs fine as
> long as the input is not too long, but if i give it input longer than
> 8 characters it gives
> RuntimeError: maximum recursion depth exceeded in cmp
> i'm not too sure what i am doing improperly.  is there really a lot of
> recursion in this code?
> ==
> import sys
> def ch4(item, n=0):
>if n < len(item):
>if item[n] == '0':
>item[n] = '1'
>print ''.join(item)
>ch4(item)
>elif item[n] == '1':
>item[n] = '0'
>ch4(item, n+1)
> ch4(list(sys.argv[1]))
> ==
 Yes.  There really is *that* much recursion in that code.  502 levels
 with input length of 8 characters, 1013 with 9 characters, 2035 with
 10 characters...  There's a pattern there ;-)
>>> ok, thanks michael!
>>> is there a way to avoid it here?  how could i write this better, (if
>>> at all)?
>> Google for permutation-like recipies:
>>
>>  http://www.google.com/search?q=Python+permutations
>>
>> Use the code from the first hit::
>>
>>  >>> for x in xselections('01', 8):
>>  ... print ''.join(x)
>>  ...
>>  
>>  0001
>>  0010
>>  ...
>>  1101
>>  1110
>>  
>>
>> Explaining to your teacher why your code uses generators when you
>> haven't been taught them yet is left as an exercise to the reader. ;-)
>>
>> STeVe
> 
> this is really nice, thanks steve.  much slicker than my code.
> 
> for interest sake:  is my method unredeemable?

Let's just say that I don't currently see an obvious way of redeeming 
it. ;-)

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


Re: Class Not Auto-Init On Import

2007-04-22 Thread Steve Holden
Dennis Lee Bieber wrote:
> On Sat, 21 Apr 2007 11:56:05 -0400, Steve Holden <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
>> Robert Rawlins - Think Blue wrote:
> 
>>> LocationService.setIP(‘192.168.1.1’)
>>>
>> This isn't a call on a specific LocationService instance, it's a call on 
>> the SetIP method of the class (presumably you have to set the IP address 
>> of the server or whatever - typically class methods are used to invoke 
>> functions or set up conditions that must apply to all instances of the 
>> class. If you wanted to set the IP for a particular instance you would 
>> normally call a method instance, as in
>>
>   Actually, in the absence of a "from ... import *", that isn't even a
> call on the /class/.
> 
>   It's a call on a standalone setIP() located in the imported /module/

Indeed it is. Good catch.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: Can __init__ not return an object?

2007-04-22 Thread Steve Holden
Steven W. Orr wrote:
> When I go to create an object I want to be able to decide whether the 
> object is valid or not in __init__, and if not, I want the constructor to 
> return something other than an object, (like maybe None). I seem to be 
> having problems. At the end of __init__ I say (something like)
> 
>   if self.something < minvalue:
>   del self
>   return None
> 
> and it doesn't work. I first tried just the return None, then I got crafty 
> and tried the del self. Is what I'm trying to do possible in the 
> constructor or do I have to check after I return? Or would raising an 
> exception in the constructor be appropriate?
> 
> Am I even being clear?
> 
The trouble you have is that it's too late by the time you get to 
__init__. The object has been created. The reason that "del self" 
doesn't work is that all it does is remove the local name "self" from 
the namespace of the method - you will find that if __init__ returns 
anything *except* None you get an exception.

Don't think of __init__ as a constructor - that's __new__, which *is* 
expected to return a newly-created instance.

Raising an exception in __init__ is perfectly permissible, but adopting 
the new-style classes (inheriting from object) might give you a more 
efficient solution to your problem.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Python and Javascript equivalence

2007-04-22 Thread Sam the Cat
Hey All,

I am writing some COM code in Python to control photoshop.  Several 
functions of PS require an "Array" argument.  In the examples of VBscript or 
javascript the Array type is used.  I have tried what would appear to be the 
equivalent in Python -- Lists and Tuples -- but to no avail.  Anyone have 
any insight  on what via the COM interface is equivalent to an Array in 
javascript ?

Cheers
Sam 


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


Re: serializable object references

2007-04-22 Thread Gabriel Genellina
En Sun, 22 Apr 2007 12:47:10 -0300, Martin Drautzburg  
<[EMAIL PROTECTED]> escribió:

> I was thinking that it would be nice if a web application could talk to
> real objects. The client side does not need to know the internals of an
> object, it acts as a "view" for server-side models. All it has to be
> able to do is invoke methods on "its" model. So a view could just
> store "its" object-reference in an instance variable and pass it to the
> server, where my problem of looking it up comes in.

This is more or less what several web frameworks do. You publish objects;  
URLs are mapped to method objects; URL parameters become method  
parameters. See http://wiki.python.org/moin/WebFrameworks

> I am currently learning about web services but my feeling is
> that "state" is not an integral part of this concept, rather an add-on,
> but I may be mistaken here.
>
> But for any reasonable web application you have to introduce state one
> way or the other. My impression is, that this is achieved with "session
> objects", which hold all the state of a session (again I may be
> mistaken). But this would be a strange concept in an OO world. You
> might as well put "ALL" state into a global "state" state object, where
> all the class methods deposit their state and classes would hold
> behavior only and no state. This is of course nothing an OO programmer
> would want to do.

You can have a "persistent" state (stored in a backend database) and  
"transitory" state (kept in session objects).

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


Re: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident ***

2007-04-22 Thread bill . sloman
On Apr 22, 8:49 pm, Jim Thompson <[EMAIL PROTECTED]
Web-Site.com> wrote:
> Ignorant Bastard Poster
>
> On 22 Apr 2007 11:32:34 -0700, [EMAIL PROTECTED] wrote:
>
> >Dr Gideon Polya published some 130 works in a 4 decade scientific
> >career, most recently a huge pharmacological reference text
> >"Biochemical Targets of Plant Bioactive Compounds" (Taylor & Francis,
> >New York & London, 2003), and is currently editing a completed book on
> >global avoidable mortality (numerous articles on this matter can be
> >found by a simple Google search for "Gideon Polya" and on his
> >websites:
>
> >Here is the BRILLIANT AND INCISIVE ANALYSIS:
>
> >http://countercurrents.org/polya230407.htm<--
>
> >Dr Polya, we are incredibly proud of you. God Bless you for your
> >courage.

Note that Dr. Polya comes from Tasmania - the Australian state where I
was born.

Meanwhile, Jim's decline continues - he has now committed top posting.
Institutionalisation can't be far away.

--
Bill Sloman, Nijmegen

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


Re: recursion depth problem

2007-04-22 Thread proctor
On Apr 22, 5:51 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Sun, 22 Apr 2007 17:37:05 -0500, Michael Bentley
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
> > Anything that can be done with recursion can be done without
> > recursion.  If you really wanted to mimic a binary counter, why not
> > write a function that converts a number to binary?
>
> > Then you could just count up from 0, printing the return from your
> > binary conversion function...
>
> > And the binary converter would be pretty easy too: just think of it
> > as making change -- for a given number you just divide the number by
> > each of [2 ** x for x in range(len(sys.argv[1]), 0, -1)] and append
> > the string representations of the answers to a list and if the answer
> > is 1, subtract that much from the number...
>
> Or a simple lookup dictionary to convert from hex to binary, and use
> string interpolation to produce the hex...
>
> Might also make it more natural -- the original recursive loop is
> producing output with LSB on the left, most folks expect the MSB on the
> left (where, in this case, B is "bit").
>
> Of course, if I were to be masochistic, I'd write a binary adder()
> composed of bit adders with carry... Such as {I hope this was just a
> personal learning experience and not a homework project}...
>
> -=-=-=-=-=-=-
> """
> masochistic exercise in generating a binary adder
> """
> import sys
>
> def badd(b1, b2, c=0):
> """
> badd(b1, b2, c) => (carry, sum)
> """
> if b1 and b2:
> # 1 + 1 + c => carry out, and 0/1 from carry in
> return (1, c)
> elif (b1 and c) or (b2 and c):
> # either b1 or b2 is set, and carry in is set
> return (1, 0)
> else:
> # only one of carry in, b1, or b2 is set
> return (0, b1 + b2 + c)
>
> def adder(w1, w2):
> """
> adder(w1, w2) => w3
> where w1, w2, w3 are lists of 0s and 1s
> """
> #equalize list lengths
> if len(w1) > len(w2):
> w2 = [0] * (len(w1) - len(w2)) + w2
> elif len(w1) < len(w2):
> w1 = [0] * (len(w2) - len(w1)) + w1
>
> w3 = [0] * len(w1)
>
> carry = 0   #initialize
> end = len(w3) - 1
> for i in range(end + 1):
> (carry, w3[end-i]) = badd(w1[end-i], w2[end-i], carry)
>
> if carry:
> return "OVERFLOW"   #should be an exception
>
> return w3
>
> if __name__ == "__main__":
> #sloppy conversion from character to binary
> binary = [ {True:1, False:0}[c == "1"] for c in sys.argv[1] ]
>
> #simple counter
>
> while binary != "OVERFLOW":
> print "".join(["%1s" % b for b in binary])
> binary = adder(binary, [ 1 ])   #need to supply a list
>
> print "Overflow must have occurred"
>
> binary1 = [ {True:1, False:0}[c == "1"] for c in sys.argv[2] ]
> binary2 = [ {True:1, False:0}[c == "1"] for c in sys.argv[3] ]
>
> print "".join(["%1s" % b for b in adder(binary1, binary2)])
>
> -=-=-=-=-=- (watch out for line wrap on the command line
> E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>python binadd.py
>  0010 111
>
> 
> 0001
> 0010
> 0011
> 0100
> 0101
> 0110
> 0111
> 1000
> 1001
> 1010
> 1011
> 1100
> 1101
> 1110
> 
> Overflow must have occurred
> 1001
>
> E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>
> E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>python binadd.py
> 010 001 0
>
> 010
> 011
> 100
> 101
> 110
> 111
> Overflow must have occurred
> 1
>
> E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>
> E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>python binadd.py
> 00 1 1
>
> 00
> 01
> 10
> 11
> Overflow must have occurred
> OVERFLOW
>
> E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>
>
> --
> WulfraedDennis Lee Bieber   KD6MOG
> [EMAIL PROTECTED] [EMAIL PROTECTED]
> HTTP://wlfraed.home.netcom.com/
> (Bestiaria Support Staff:   [EMAIL PROTECTED])
> HTTP://www.bestiaria.com/

thank you.  you guys are keeping me busy!

ps.  no, i'm not in school.  not in the traditional sense anyway :-)
just books, practice, and forums like this.

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


Re: recursion depth problem

2007-04-22 Thread proctor
On Apr 22, 5:51 pm, Michael Bentley <[EMAIL PROTECTED]> wrote:
> Oops!  Note to self: *ALWAYS* try code before posting to a public
> forum :-(
>
> def binary(val, width):
> print '%10s = the sum of' % val
> for i in [2 ** x for x in range(width - 1, -1, -1)]:
> a = val / i
> print ' ' * 13 + '%s * (2 ** %s)' % (a, width)
> val -= i * a
> width -= 1
>
> binary(233, 8)

very cool.  thanks a lot michael.  very interesting.

proctor.

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


Re: [ANN] mlabwrap-1.0final

2007-04-22 Thread Alexander Schmolck
Stef Mientki <[EMAIL PROTECTED]> writes:

> Alexander Schmolck wrote:
> > I'm pleased to finally announce mlabwrap-1.0:
> > Project website
> 
> > ---
> > 
> > Description
> 
> > ---
> > Mlabwrap-1.0 is a high-level python to matlab(tm) bridge that makes calling
> 
> > matlab functions from python almost as convenient as using a normal python
> > library. It is available under a very liberal license (BSD/MIT) and should
> > work on all major platforms and (non-ancient) python and matlab versions and
> > either numpy or Numeric (Numeric support will be dropped in the future).
> >
> 
> 
> Probably quit a large and nice job, to embed MatLab in Python.

Actually, it's not much code -- mlabwrap.py is less than 500 lines of code.

> But, I've the idea I'm missing something ... ... coming from MatLab, a few
> months ago I tried Python, ... and at the moment I've decided to move
> completely from MatLab to Python. All new programs will be written in Python
> and the old programs will be translated.
> 
> Is my decision wrong ?

Depends on your circumstances, but in many cases just switching to a different
language and rewriting everything from scratch (possibly even at a single go,
if there are many interdependencies) isn't practical. Mlabwrap help here,
because it allows you to either migrate piecemeal or mix and match (i.e.
mostly use python, resorting to matlab libraries where necessary).
 
> What can do MatLab, that can't be done in Python (SciPy) ?
> (Ok I accept there's no SimuLink/PowerSim).

There are plenty of commercial and free libraries and environments for matlab
that have seen considerable development by domain experts don't have a
comparable python equivalent. I'm currently sitting in a cafe in Berkeley,
because researchers at the universities of Berkeley and Cambridge are
interested in doing their neuroimaging analysis in python, but still need to
interface to existing matlab packages like SPM.

> Both environments can create any program you like.

Not really.

> If MatLab is your standard / favorite why not stick to MatLab ?

Because matlab is much limited as a programming language once you stray
outside linear algebra. Many people also seem to be unhappy about licencing
issues . Finally, how often did matlab crash on you? And python?
 
> Please enlighten me.

My pleasure.

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


Re: recursion depth problem

2007-04-22 Thread Michael Bentley
Oops!  Note to self: *ALWAYS* try code before posting to a public  
forum :-(

def binary(val, width):
print '%10s = the sum of' % val
for i in [2 ** x for x in range(width - 1, -1, -1)]:
a = val / i
print ' ' * 13 + '%s * (2 ** %s)' % (a, width)
val -= i * a
width -= 1

binary(233, 8)

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


Re: recursion depth problem

2007-04-22 Thread Michael Bentley

On Apr 22, 2007, at 5:47 PM, proctor wrote:

> On Apr 22, 4:37 pm, Michael Bentley <[EMAIL PROTECTED]> wrote:
>> On Apr 22, 2007, at 4:08 PM, proctor wrote:
>>
>>
>>
>>> On Apr 22, 2:55 pm, [EMAIL PROTECTED] wrote:
 On Apr 22, 11:49 am, proctor <[EMAIL PROTECTED]> wrote:
>>
> hello,
>>
> i have a small function which mimics binary counting.  it runs
> fine as
> long as the input is not too long, but if i give it input longer
> than
> 8 characters it gives
>>
> RuntimeError: maximum recursion depth exceeded in cmp
>>
> i'm not too sure what i am doing improperly.  is there really a
> lot of
> recursion in this code?
>>
> ==
>>
> import sys
>>
> def ch4(item, n=0):
> if n < len(item):
> if item[n] == '0':
> item[n] = '1'
> print ''.join(item)
> ch4(item)
> elif item[n] == '1':
> item[n] = '0'
> ch4(item, n+1)
>>
> ch4(list(sys.argv[1]))
>>
> ==
>>
> this function expects input in the form of a string of zeros, like
> this:
>>
> python test-bin.py 
>>
> and is expected to output a list of permutations like this:
>>
> $ python test-bin.py 
> 1000
> 0100
> 1100
> 0010
> 1010
> 0110
> 1110
> 0001
> 1001
> 0101
> 1101
> 0011
> 1011
> 0111
> 
>>
> thanks for all help!
>>
> sincerely,
> proctor
>>
 If you just want to make it work as ischeck
>>
 sys.setrecursionlimit()
>>
 ~Sean
>>
>>> very nice.  thanks sean.  so is the structure of my original code
>>> unrescuable?  i cannot rearrange it to bypass the recursion?
>>
>> Anything that can be done with recursion can be done without
>> recursion.  If you really wanted to mimic a binary counter, why not
>> write a function that converts a number to binary?
>>
>> Then you could just count up from 0, printing the return from your
>> binary conversion function...
>>
>> And the binary converter would be pretty easy too: just think of it
>> as making change -- for a given number you just divide the number by
>> each of [2 ** x for x in range(len(sys.argv[1]), 0, -1)] and append
>> the string representations of the answers to a list and if the answer
>> is 1, subtract that much from the number...
>
> cool...  i'm going to have to think about this one... :-)
>

he he...  Run this snippet and see if it makes more sense:

def binary(val, width):
print '%10s = the sum of' % val
for i in [2 ** x for x in range(width, 0, -1)]:
a = val / i
print ' ' * 13 + '%s * (2 ** %s)' % (a, i)
val -= i * a

binary(333, 8)

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


Re: recursion depth problem

2007-04-22 Thread proctor
On Apr 22, 5:05 pm, tac-tics <[EMAIL PROTECTED]> wrote:
> Yes, you should use a for loop in this situation.
>
> Certain functional languages, such as Scheme and various LISP dialects
> allow for what is called "tail recursion" which effectively eliminates
> this problem by internally converting recursion to iteration. Python
> isn't really cut out for heavy recursive work, and the "Pythonic" way
> of doing things is through the lovely for loop.

hi tac-tics,

by using a for loop, do you mean in the same sense that the
"xselections" function uses a for loop on the page:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465
?

or are you referring to a different technique for this?

thanks for your help.  i really appreciate it.

proctor.

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


Re: file.read() returns an emtpy even if its currenet position is not at the end

2007-04-22 Thread js
Thank you for reply.

I've just found the bug report on this.
http://sourceforge.net/tracker/index.php?func=detail&aid=1523853&group_id=5470&atid=105470

Nobody seems to be working on this,  though.

On 22 Apr 2007 14:41:29 -0700, Alberto Valverde <[EMAIL PROTECTED]> wrote:
> On Apr 22, 6:51 pm, "js " <[EMAIL PROTECTED]> wrote:
> > Hi list.
> >
> > I'm writing a tail -f like program in python
> > and I found file.read() doesn't work as I think it should.
> >
> > Here's the code illustrating my problem.
> >
> > ###
> > #!/usr/bin/env python
> > import os, sys
> > filename = "test.out"
> >
> > f = open(filename, "w+")
> > f.write("Hello")
> > f.flush()
> >
> > f.seek(0, 2)
> >
> > statinfo = os.stat(filename)
> > print "file size: %d" % statinfo.st_size
> > print "position : %d" % f.tell()
> > line = f.read()
> > print "line : [%s]" % line
> >
> > # Writing the same file using another fd
> > f2 = open(filename, "a+")
> > f2.write("World")
> > f2.flush()
> > f2.close()
> >
> > statinfo = os.stat(filename)
> > print "file size: %d" % statinfo.st_size
> > print "position : %d" % f.tell()
> > line = f.read() # read() returns emtpy!! readlines?() works ok
> > ###
> >
> > Running the above, I got the following.
> > ###
> > file size: 5
> > position : 5
> > line : []
> > file size: 10
> > position : 5
> > ###
> >
> > So my question is
> > why the second f.read() returns an emtpy?>From tell() and its st_size I'm 
> > sure that file descriptor is not at the EOF
> >
> > and read()'s doc says
> > "An empty string is returned when EOF is encountered immediately".
> > Using readline() or readlines() instead of read() works great though.
> >
> > I'm using  Python  2.4.3 on OS X.
> >
> > Probably I'm missing something but I could't figure out.
> >
> > Thanks in advance.
>
> I've hit into the same issue recently when implementing more or less
> the same thing and found that doing f.seek(f.tell()) on the file
> object when empty strings start to come out allows you to continue
> read()ing after hitting EOF if the file grows again.
>
> I finally dropped the "hack" and used readline instead since it made
> me a little bit uneasy though...
>
> Alberto
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursion depth problem

2007-04-22 Thread tac-tics
Yes, you should use a for loop in this situation.

Certain functional languages, such as Scheme and various LISP dialects
allow for what is called "tail recursion" which effectively eliminates
this problem by internally converting recursion to iteration. Python
isn't really cut out for heavy recursive work, and the "Pythonic" way
of doing things is through the lovely for loop.

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


Re: Namespaces/introspection: collecting sql strings for validation

2007-04-22 Thread George Sakkis
On Apr 21, 4:16 pm, Martin Drautzburg <[EMAIL PROTECTED]>
wrote:
> I would like to validate sql strings, which are spread all over the
> code, i.e. I run ("prepare") them against a database to see if it happy
> with the statements. Spelling errors in sql have been a major pain for
> me.
>
> The statements will not be assembled from smaller pieces, but they will
> not neccessarily be defined at module level. I could live with class
> level, but method level would be best. And I definitely don't want to
> parse the source file, but I am willing to mark the strings so it is
> easier to tell sql from non-sql.
>
> So the code will look like this
>
> class Foo:(...):
> def aQuery(...):
> stmt = """
> -- checkSql
> select 1 from dual
> """
> executeQuery()
>
> at the end of the file I would like to write something like
> if (...):
> validateSql()
>
> The validateSql() is the problem. It would be imported from elsewhere.
> and has to do some serious magic. It would have to lookup its caller's
> module, find all the classes (and methods, if we go that far) extract
> the constants, check if any of them are an SQL statement and validate
> it.
>
> The problem is the first part: how can I lookup the callers module and
> the classobjs defined in there? Or finding any constant strings in the
> caller's module would also be just fine. Or is there a completely
> different way to do such a thing?

Yes, there is: use an ORM to do the SQL generation for you. Check out
SQLAlchemy, it will buy you much more than what you asked for.

George

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


Re: Bug in select (was: Re: Select weirdness)

2007-04-22 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:

>   Well, on WinXP, Python 2.4, with

I should have specified: I'm running 2.5 on unix.  (I've reproduced the 
problem on both Linux and OS X.)

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


Re: recursion depth problem

2007-04-22 Thread proctor
On Apr 22, 4:37 pm, Michael Bentley <[EMAIL PROTECTED]> wrote:
> On Apr 22, 2007, at 4:08 PM, proctor wrote:
>
>
>
> > On Apr 22, 2:55 pm, [EMAIL PROTECTED] wrote:
> >> On Apr 22, 11:49 am, proctor <[EMAIL PROTECTED]> wrote:
>
> >>> hello,
>
> >>> i have a small function which mimics binary counting.  it runs
> >>> fine as
> >>> long as the input is not too long, but if i give it input longer
> >>> than
> >>> 8 characters it gives
>
> >>> RuntimeError: maximum recursion depth exceeded in cmp
>
> >>> i'm not too sure what i am doing improperly.  is there really a
> >>> lot of
> >>> recursion in this code?
>
> >>> ==
>
> >>> import sys
>
> >>> def ch4(item, n=0):
> >>> if n < len(item):
> >>> if item[n] == '0':
> >>> item[n] = '1'
> >>> print ''.join(item)
> >>> ch4(item)
> >>> elif item[n] == '1':
> >>> item[n] = '0'
> >>> ch4(item, n+1)
>
> >>> ch4(list(sys.argv[1]))
>
> >>> ==
>
> >>> this function expects input in the form of a string of zeros, like
> >>> this:
>
> >>> python test-bin.py 
>
> >>> and is expected to output a list of permutations like this:
>
> >>> $ python test-bin.py 
> >>> 1000
> >>> 0100
> >>> 1100
> >>> 0010
> >>> 1010
> >>> 0110
> >>> 1110
> >>> 0001
> >>> 1001
> >>> 0101
> >>> 1101
> >>> 0011
> >>> 1011
> >>> 0111
> >>> 
>
> >>> thanks for all help!
>
> >>> sincerely,
> >>> proctor
>
> >> If you just want to make it work as ischeck
>
> >> sys.setrecursionlimit()
>
> >> ~Sean
>
> > very nice.  thanks sean.  so is the structure of my original code
> > unrescuable?  i cannot rearrange it to bypass the recursion?
>
> Anything that can be done with recursion can be done without
> recursion.  If you really wanted to mimic a binary counter, why not
> write a function that converts a number to binary?
>
> Then you could just count up from 0, printing the return from your
> binary conversion function...
>
> And the binary converter would be pretty easy too: just think of it
> as making change -- for a given number you just divide the number by
> each of [2 ** x for x in range(len(sys.argv[1]), 0, -1)] and append
> the string representations of the answers to a list and if the answer
> is 1, subtract that much from the number...

cool...  i'm going to have to think about this one... :-)

proctor

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


Re: Bug in select

2007-04-22 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 Erik Max Francis <[EMAIL PROTECTED]> wrote:

> Ron Garret wrote:
> 
> > Geez you people are picky.  Since I ran this several times I ran into 
> > the TIM_WAIT problem.  Here's the actual transcript:
> 
> It's not about being picky, it's about making it clear what your problem 
> is.  You're now describing an entirely different problem,

Nope, it's been the same problem all along.  If you don't think so then 
you have misunderstood something.

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


Re: recursion depth problem

2007-04-22 Thread Michael Bentley

On Apr 22, 2007, at 4:08 PM, proctor wrote:

> On Apr 22, 2:55 pm, [EMAIL PROTECTED] wrote:
>> On Apr 22, 11:49 am, proctor <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>>> hello,
>>
>>> i have a small function which mimics binary counting.  it runs  
>>> fine as
>>> long as the input is not too long, but if i give it input longer  
>>> than
>>> 8 characters it gives
>>
>>> RuntimeError: maximum recursion depth exceeded in cmp
>>
>>> i'm not too sure what i am doing improperly.  is there really a  
>>> lot of
>>> recursion in this code?
>>
>>> ==
>>
>>> import sys
>>
>>> def ch4(item, n=0):
>>> if n < len(item):
>>> if item[n] == '0':
>>> item[n] = '1'
>>> print ''.join(item)
>>> ch4(item)
>>> elif item[n] == '1':
>>> item[n] = '0'
>>> ch4(item, n+1)
>>
>>> ch4(list(sys.argv[1]))
>>
>>> ==
>>
>>> this function expects input in the form of a string of zeros, like
>>> this:
>>
>>> python test-bin.py 
>>
>>> and is expected to output a list of permutations like this:
>>
>>> $ python test-bin.py 
>>> 1000
>>> 0100
>>> 1100
>>> 0010
>>> 1010
>>> 0110
>>> 1110
>>> 0001
>>> 1001
>>> 0101
>>> 1101
>>> 0011
>>> 1011
>>> 0111
>>> 
>>
>>> thanks for all help!
>>
>>> sincerely,
>>> proctor
>>
>> If you just want to make it work as ischeck
>>
>> sys.setrecursionlimit()
>>
>> ~Sean
>
> very nice.  thanks sean.  so is the structure of my original code
> unrescuable?  i cannot rearrange it to bypass the recursion?
>

Anything that can be done with recursion can be done without  
recursion.  If you really wanted to mimic a binary counter, why not  
write a function that converts a number to binary?

Then you could just count up from 0, printing the return from your  
binary conversion function...

And the binary converter would be pretty easy too: just think of it  
as making change -- for a given number you just divide the number by  
each of [2 ** x for x in range(len(sys.argv[1]), 0, -1)] and append  
the string representations of the answers to a list and if the answer  
is 1, subtract that much from the number...


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


Re: Vector classes

2007-04-22 Thread Gabriel Genellina
En Sun, 22 Apr 2007 09:33:53 -0300, Mizipzor <[EMAIL PROTECTED]> escribió:

> During my coding Ive found two vector classes on the internet. Ive
> modified them both a little but the do both have advantages and
> disadvantages.
>
> vector1: http://rafb.net/p/4FVdh699.html
> vector2: http://rafb.net/p/0KShGu30.html
>
> With 1, I can typ vec.x and vec.y, very nice. With 2, I need to do
> vec.vals[0] and vec.vals[1], which makes my eyes bleed.

[2] modifies the 2nd argument to __add__ and __sub__, not a good thing...
The only advantage I can see over [1], is that it handles dimensions  
higher than 2.

> But with 2, I can create a vector by supplying a list of numbers as
> arguments.

Same with the first one:

coords = (1.2, 3.4)
v1 = vector(*coords)

There is even the "list" static method (not a good name!):

coords = (1.2, 3.4)
v1 = vector.list(coords)

Anyway I'd remove the __ne__ and __lt__ methods (if you don't require it)  
and replace __hash__ with hash((self.x,self.y))

> Is there any way to combine the two? The ultimate would be if I
> somehow could take vector2 and hook the member self.vals[0] to self.x
> or something.

You should try the other suggested classes, but if I had to choose among  
these two, I'd use the first.

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


Re: [re.finditer] Getting all occurences in one go?

2007-04-22 Thread Paul Rubin
Gilles Ganault <[EMAIL PROTECTED]> writes:
> for match in matches:
>   if mytable[item]=="":
>   mytable[item]= match.group(1)
>   else:
>   mytable[item]= mytable[item] + "," + match.group(1) #
> --- END
> ===
> 
> Can the lines between BEGIN/END be simplified so I can copy all the
> items into the mytable[] dictionary in one go, instead of getting each
> one in a row, and append them with a comma, eg.

Yes, look at the string.join method and generator expressions.  You'd
say:

  mytable[item] = ','.join(m.group(1) for m in matches)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in select

2007-04-22 Thread Erik Max Francis
Ron Garret wrote:

> Geez you people are picky.  Since I ran this several times I ran into 
> the TIM_WAIT problem.  Here's the actual transcript:

It's not about being picky, it's about making it clear what your problem 
is.  You're now describing an entirely different problem, hence why it's 
important to be clear about _precisely_ what it is you're doing and 
_precisely_ what's happening that you think that's wrong.

> Python 2.5 (r25:51908, Mar  1 2007, 10:09:05) 
> [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
 from socket import *
 from select import select
 s=socket(AF_INET, SOCK_STREAM)
 s.bind(('',8080))
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 1, in bind
> socket.error: (48, 'Address already in use')
 s.bind(('',8081))
 s.listen(5)
 f = s.accept()[0].makefile()
 f.readline()
> '123\r\n'
 select([f],[],[],1)
> ([], [], [])
 f.readline()
> '321\r\n'


-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   There are no dull subjects. There are only dull writers.
-- H.L. Mencken
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Building browser-like GET request

2007-04-22 Thread Steve Holden
Björn Keil wrote:
[...]
> 
> I hope that helped and I wasn't telling things you already new.
> As a sidenote: For the task you describe I'd rather use an actual
> sniffer - such as Wireshark (http://en.wikipedia.org/wiki/Wireshark),
> than logs of a Proxy... Not sure wether Wireshark works under Windows,
> though.

On a point of information, Wireshark wokrs very effectively under 
Windows. The only thing you shouldn't expect to be able to do is tap 
into the loopback network, and that's down to the Windows driver structure.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: python cgi problem with textarea

2007-04-22 Thread Graham Dumpleton
On Apr 22, 11:09 pm, placid <[EMAIL PROTECTED]> wrote:
> On Apr 22, 4:08 pm, Adrian Smith <[EMAIL PROTECTED]> wrote:
>
>
>
> > This may be more a cgi thing than a Python one, but I'm trying to get
> > this page:
>
> >http://adrian10.phpwebhosting.com/trial.html
>
> > consisting basically of this:
>
> > 
> > 
> > 
> > 
>
> > ...to print out the contents of the textarea with this cgi script:
>
> > #!/usr/bin/python
> > import cgi
> > print "Content-type: text/html\n"
> > form = cgi.FieldStorage()
> > print form["essay"].value
>
> > ...and I get an internal server error if I have any spaces in the
> > textarea, which is really going to limit its usefulness to me. Oddly,
> > it seems to work for a friend in the UK who's looked at it, but it
> > doesn't work for me here in Japan.
>
> i just tried it and its working. here it is
>
> http://yallara.cs.rmit.edu.au/~bevcimen/form.html
>
> maybe the internal server error is because mod_python isn't installed
> assuming your using Apache as your web server

You do not need mod_python installed to be able to run CGI scripts,
thus has nothing to do with mod_python.

Graham

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


Re: recursion depth problem

2007-04-22 Thread proctor
On Apr 22, 2:06 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
> proctor wrote:
> > On Apr 22, 1:24 pm, Michael Bentley <[EMAIL PROTECTED]> wrote:
> >> On Apr 22, 2007, at 1:49 PM, proctor wrote:
>
> >>> i have a small function which mimics binary counting.  it runs fine as
> >>> long as the input is not too long, but if i give it input longer than
> >>> 8 characters it gives
> >>> RuntimeError: maximum recursion depth exceeded in cmp
> >>> i'm not too sure what i am doing improperly.  is there really a lot of
> >>> recursion in this code?
> >>> ==
> >>> import sys
> >>> def ch4(item, n=0):
> >>>if n < len(item):
> >>>if item[n] == '0':
> >>>item[n] = '1'
> >>>print ''.join(item)
> >>>ch4(item)
> >>>elif item[n] == '1':
> >>>item[n] = '0'
> >>>ch4(item, n+1)
> >>> ch4(list(sys.argv[1]))
> >>> ==
> >> Yes.  There really is *that* much recursion in that code.  502 levels
> >> with input length of 8 characters, 1013 with 9 characters, 2035 with
> >> 10 characters...  There's a pattern there ;-)
>
> > ok, thanks michael!
>
> > is there a way to avoid it here?  how could i write this better, (if
> > at all)?
>
> Google for permutation-like recipies:
>
>  http://www.google.com/search?q=Python+permutations
>
> Use the code from the first hit::
>
>  >>> for x in xselections('01', 8):
>  ... print ''.join(x)
>  ...
>  
>  0001
>  0010
>  ...
>  1101
>  1110
>  
>
> Explaining to your teacher why your code uses generators when you
> haven't been taught them yet is left as an exercise to the reader. ;-)
>
> STeVe

this is really nice, thanks steve.  much slicker than my code.

for interest sake:  is my method unredeemable?

thanks very much!

sincerely,
proctor

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


Re: file.read() returns an emtpy even if its currenet position is not at the end

2007-04-22 Thread Alberto Valverde
On Apr 22, 6:51 pm, "js " <[EMAIL PROTECTED]> wrote:
> Hi list.
>
> I'm writing a tail -f like program in python
> and I found file.read() doesn't work as I think it should.
>
> Here's the code illustrating my problem.
>
> ###
> #!/usr/bin/env python
> import os, sys
> filename = "test.out"
>
> f = open(filename, "w+")
> f.write("Hello")
> f.flush()
>
> f.seek(0, 2)
>
> statinfo = os.stat(filename)
> print "file size: %d" % statinfo.st_size
> print "position : %d" % f.tell()
> line = f.read()
> print "line : [%s]" % line
>
> # Writing the same file using another fd
> f2 = open(filename, "a+")
> f2.write("World")
> f2.flush()
> f2.close()
>
> statinfo = os.stat(filename)
> print "file size: %d" % statinfo.st_size
> print "position : %d" % f.tell()
> line = f.read() # read() returns emtpy!! readlines?() works ok
> ###
>
> Running the above, I got the following.
> ###
> file size: 5
> position : 5
> line : []
> file size: 10
> position : 5
> ###
>
> So my question is
> why the second f.read() returns an emtpy?>From tell() and its st_size I'm 
> sure that file descriptor is not at the EOF
>
> and read()'s doc says
> "An empty string is returned when EOF is encountered immediately".
> Using readline() or readlines() instead of read() works great though.
>
> I'm using  Python  2.4.3 on OS X.
>
> Probably I'm missing something but I could't figure out.
>
> Thanks in advance.

I've hit into the same issue recently when implementing more or less
the same thing and found that doing f.seek(f.tell()) on the file
object when empty strings start to come out allows you to continue
read()ing after hitting EOF if the file grows again.

I finally dropped the "hack" and used readline instead since it made
me a little bit uneasy though...

Alberto

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


Re: python style guide inconsistencies

2007-04-22 Thread Bjoern Schliessmann
Darren Dale wrote:

> I was just searching for some guidance on how to name packages and
> modules, and discovered some inconsistencies on the
> www.python.org. http://www.python.org/doc/essays/styleguide.html
> says "Module names can be either MixedCase or lowercase." That
> page also refers to PEP 8 at
> http://www.python.org/dev/peps/pep-0008/, which says "Modules
> should have short, all-lowercase names. ... Python packages should
> also have short, all-lowercase names ...".
> 
> Which is most up to date? 

The priority is, IMHO, clear. The old style guide essay says, at the
beginning:

| This style guide has been converted to several PEPs (Python
| Enhancement Proposals): PEP 8 for the main text, PEP 257 for
| docstring conventions. See the PEP index.  

So PEP 8 is the most recent.

Regards,


Björn

-- 
BOFH excuse #216:

What office are you in? Oh, that one.  Did you know that your
building was built over the universities first nuclear research
site? And wow, aren't you the lucky one, your office is right over
where the core is buried!

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


Re: [re.finditer] Getting all occurences in one go?

2007-04-22 Thread Gilles Ganault
On Sun, 22 Apr 2007 23:28:23 +0200, Gilles Ganault <[EMAIL PROTECTED]>
wrote:
>I'd like to make sure there isn't an easier way to extract all the
>occurences found with re.finditer:

Oops, s/match/item/:

req = urllib2.Request(url, None, headers)
response = urllib2.urlopen(req).read()
matches = re.compile("(\d+).html").finditer(response)
# --- BEGIN
for item in matches:
if mytable[item]=="":
mytable[item]= match.group(1)
else:
mytable[item]= mytable[item] + "," + match.group(1) #
--- END
-- 
http://mail.python.org/mailman/listinfo/python-list


[re.finditer] Getting all occurences in one go?

2007-04-22 Thread Gilles Ganault
Hello

I'd like to make sure there isn't an easier way to extract all the
occurences found with re.finditer:

===
req = urllib2.Request(url, None, headers)
response = urllib2.urlopen(req).read()
matches = re.compile("(\d+).html").finditer(response)
# --- BEGIN
for match in matches:
if mytable[item]=="":
mytable[item]= match.group(1)
else:
mytable[item]= mytable[item] + "," + match.group(1) #
--- END
===

Can the lines between BEGIN/END be simplified so I can copy all the
items into the mytable[] dictionary in one go, instead of getting each
one in a row, and append them with a comma, eg.

# I want this : mytable[123] = 6548,8457,etc."
# DOESN' T  WORK
# mytable[item] = matches.group(0)
mytable[item] = matches.getall()

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


Re: Bug in select

2007-04-22 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 Erik Max Francis <[EMAIL PROTECTED]> wrote:

> Ron Garret wrote:
> 
> > So this is clearly a bug, but surely I'm not the first person to have 
> > encountered this?  Is there a known workaround?
> 
> It's hard to see how this demonstrates a bug in anything, since you're 
> telnetting to the wrong port in your example.

Geez you people are picky.  Since I ran this several times I ran into 
the TIM_WAIT problem.  Here's the actual transcript:

Python 2.5 (r25:51908, Mar  1 2007, 10:09:05) 
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from socket import *
>>> from select import select
>>> s=socket(AF_INET, SOCK_STREAM)
>>> s.bind(('',8080))
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in bind
socket.error: (48, 'Address already in use')
>>> s.bind(('',8081))
>>> s.listen(5)
>>> f = s.accept()[0].makefile()
>>> f.readline()
'123\r\n'
>>> select([f],[],[],1)
([], [], [])
>>> f.readline()
'321\r\n'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python style guide inconsistencies

2007-04-22 Thread Terry Reedy

""Martin v. Löwis"" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Darren Dale schrieb:
| > I was just searching for some guidance on how to name packages and 
modules,
| > and discovered some inconsistencies on the www.python.org.
| > http://www.python.org/doc/essays/styleguide.html says "Module names can 
be
| > either MixedCase or lowercase." That page also refers to PEP 8 at
| > http://www.python.org/dev/peps/pep-0008/, which says "Modules should 
have
| > short, all-lowercase names. ... Python packages should also have short,
| > all-lowercase names ...".
| >
| > Which is most up to date? Is this the right place to point out that one 
of
| > those pages needs to be updated?
|
| No - this is better discussed on python-dev.
|
| In any case, there isn't technically a contradiction. Module names
| MUST be either MixedCase or lowercase; they SHOULD be lowercase.
|
| So unfortunately, for tradition, some module names are mixed case
| (such as ConfigParser or StringIO). I can personally accept that as
| a necessary evil, although I would prefer if all modules were
| lower case.

I have the impression that tradition will change in 3.0 and your preference 
realized.
Wrong? or have you not been following?

To OP.  Follow the should rather than the may.

tjr



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

Re: Bug in select

2007-04-22 Thread Erik Max Francis
Ron Garret wrote:

> So this is clearly a bug, but surely I'm not the first person to have 
> encountered this?  Is there a known workaround?

It's hard to see how this demonstrates a bug in anything, since you're 
telnetting to the wrong port in your example.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Being in love for real / It ain't like a movie screen
-- India Arie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python "robots.txt" parser broken since 2003

2007-04-22 Thread John Nagle
Steven Bethard wrote:
> John Nagle wrote:
> 
>> Terry Reedy wrote:
>>
>>> "John Nagle" <[EMAIL PROTECTED]> wrote in message 
>>> news:[EMAIL PROTECTED]
>>> | This was reported in 2003, and a patch was uploaded in 2005, but 
>>> the patch
>>> | never made it into Python 2.4 or 2.5.
>>>
>>> If the patch is still open, perhaps you could review it.
>>>
>> I tried it on Python 2.4 and it's in our production system now.
>> But someone who regularly does check-ins should do this.
> 
> 
> If you post such a review (even just the short sentence above) to the 
> patch tracker, it often increases the chance of someone committing the 
> patch.
> 
> Steve

OK, updated the tracker comments.

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


Re: function minimization

2007-04-22 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Is anyone aware of python library that does function minimization a la
| Minuit (http://wwwasdoc.web.cern.ch/wwwasdoc/minuit/) used by CERN?

Have you checked the minimization function in scipy?



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


Re: recursion depth problem

2007-04-22 Thread proctor
On Apr 22, 2:55 pm, [EMAIL PROTECTED] wrote:
> On Apr 22, 11:49 am, proctor <[EMAIL PROTECTED]> wrote:
>
>
>
> > hello,
>
> > i have a small function which mimics binary counting.  it runs fine as
> > long as the input is not too long, but if i give it input longer than
> > 8 characters it gives
>
> > RuntimeError: maximum recursion depth exceeded in cmp
>
> > i'm not too sure what i am doing improperly.  is there really a lot of
> > recursion in this code?
>
> > ==
>
> > import sys
>
> > def ch4(item, n=0):
> > if n < len(item):
> > if item[n] == '0':
> > item[n] = '1'
> > print ''.join(item)
> > ch4(item)
> > elif item[n] == '1':
> > item[n] = '0'
> > ch4(item, n+1)
>
> > ch4(list(sys.argv[1]))
>
> > ==
>
> > this function expects input in the form of a string of zeros, like
> > this:
>
> > python test-bin.py 
>
> > and is expected to output a list of permutations like this:
>
> > $ python test-bin.py 
> > 1000
> > 0100
> > 1100
> > 0010
> > 1010
> > 0110
> > 1110
> > 0001
> > 1001
> > 0101
> > 1101
> > 0011
> > 1011
> > 0111
> > 
>
> > thanks for all help!
>
> > sincerely,
> > proctor
>
> If you just want to make it work as ischeck
>
> sys.setrecursionlimit()
>
> ~Sean

very nice.  thanks sean.  so is the structure of my original code
unrescuable?  i cannot rearrange it to bypass the recursion?

proctor.

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


Bug in select (was: Re: Select weirdness)

2007-04-22 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 Ron Garret <[EMAIL PROTECTED]> wrote:

> The answer is obvious: select is looking only at the underlying socket, 
> and not at the rfile buffers.

Here is conclusive proof that there's a bug in select:

from socket import *
from select import select
s=socket(AF_INET, SOCK_STREAM)
s.bind(('',8080))
s.listen(5)
f = s.accept()[0].makefile()
# Now telnet to port 8080 and enter two lines of random text
f.readline()
select([f],[],[],1)
f.readline()

Here's the sample input:

[EMAIL PROTECTED]:~/devel/sockets]$ telnet localhost 8081
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
123
321


And this is the result:

>>> f.readline()
'123\r\n'
>>> select([f],[],[],1)
# After one second...
([], [], [])
>>> f.readline()
'321\r\n'
>>> 


So this is clearly a bug, but surely I'm not the first person to have 
encountered this?  Is there a known workaround?

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


Re: recursion depth problem

2007-04-22 Thread half . italian
On Apr 22, 11:49 am, proctor <[EMAIL PROTECTED]> wrote:
> hello,
>
> i have a small function which mimics binary counting.  it runs fine as
> long as the input is not too long, but if i give it input longer than
> 8 characters it gives
>
> RuntimeError: maximum recursion depth exceeded in cmp
>
> i'm not too sure what i am doing improperly.  is there really a lot of
> recursion in this code?
>
> ==
>
> import sys
>
> def ch4(item, n=0):
> if n < len(item):
> if item[n] == '0':
> item[n] = '1'
> print ''.join(item)
> ch4(item)
> elif item[n] == '1':
> item[n] = '0'
> ch4(item, n+1)
>
> ch4(list(sys.argv[1]))
>
> ==
>
> this function expects input in the form of a string of zeros, like
> this:
>
> python test-bin.py 
>
> and is expected to output a list of permutations like this:
>
> $ python test-bin.py 
> 1000
> 0100
> 1100
> 0010
> 1010
> 0110
> 1110
> 0001
> 1001
> 0101
> 1101
> 0011
> 1011
> 0111
> 
>
> thanks for all help!
>
> sincerely,
> proctor

If you just want to make it work as ischeck

sys.setrecursionlimit()

~Sean

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


Re: Vector classes

2007-04-22 Thread Erik Max Francis
Mizipzor wrote:

> During my coding Ive found two vector classes on the internet. Ive
> modified them both a little but the do both have advantages and
> disadvantages.
> 
> vector1: http://rafb.net/p/4FVdh699.html
> vector2: http://rafb.net/p/0KShGu30.html
> 
> With 1, I can typ vec.x and vec.y, very nice. With 2, I need to do
> vec.vals[0] and vec.vals[1], which makes my eyes bleed.
> 
> But with 2, I can create a vector by supplying a list of numbers as
> arguments. And I can also do maths with numbers (ints/floats) and not
> just vectors (something 1 forces me to do).
> 
> Is there any way to combine the two? The ultimate would be if I
> somehow could take vector2 and hook the member self.vals[0] to self.x
> or something.

There are also full-featured Vector and Matrix classes in the la.py 
module of ZOE:

http://www.alcyone.com/software/zoe/

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Stretch a bow to the very full, / And you will wish you had stopped
in time. -- Laotse, ca. 6th C. BC
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's handling of unicode surrogates

2007-04-22 Thread Ross Ridge
Rhamphoryncus  <[EMAIL PROTECTED]> wrote:
>I wish to write software that supports Unicode.  Like it or not,
>Unicode goes beyond the BMP, so I'd be lying if I said I supported
>Unicode if I only handled the BMP.

The Unicode standard doesn't require that you support surrogates, or
any other kind of character, so no you wouldn't be lying.

Also since few Python programs claim to support Unicode, why do you
think it's acceptable to break them if they don't support surrogates?

Ross Ridge

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


Re: pickled object, read and write..

2007-04-22 Thread hg
[EMAIL PROTECTED] wrote:

> Hi all.
> 
> I have to put together some code that reads high scores from a saved
> file, then gives the user the opportunity to add their name and score
> to the high scores list, which is then saved.
> 
> Trouble is, I can't tell the program to read a file that doesn't
> exist, that generates an error.
> 
> So I must have a file created, problem HERE is everytime the program
> is run, it will overwrite the current list of saved high scores.
> 
> Advice would be much appreciated.


You can run this small script a few times to see that the file does not get
deleted

hg

import shelve


class Grades:
def __init__(self):
self.GRADES = 'GRADES'
self.m_gdb = shelve.open('MYGRADES.dat')

try:
self.m_grades = self.m_gdb[self.GRADES]
except:
self.m_grades = []
self.m_gdb[self.GRADES] = self.m_grades

self.m_gdb.close()

def Add(self, p_grade):
self.m_gdb = shelve.open('MYGRADES.dat')
self.m_grades.append(p_grade)
self.m_gdb[self.GRADES] = self.m_grades
self.m_gdb.close()

def Grades(self):
return self.m_grades

l_o = Grades()
print l_o.Grades()
l_o.Add(10)
print l_o.Grades()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pickled object, read and write..

2007-04-22 Thread phreaki
On Apr 22, 2:40 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> Hi all.
>
> I have to put together some code that reads high scores from a saved
> file, then gives the user the opportunity to add their name and score
> to the high scores list, which is then saved.
>
> Trouble is, I can't tell the program to read a file that doesn't
> exist, that generates an error.
>
> So I must have a file created, problem HERE is everytime the program
> is run, it will overwrite the current list of saved high scores.
>
> Advice would be much appreciated.

What did adding the standard try statement do?

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


Re: recursion depth problem

2007-04-22 Thread Steven Bethard
proctor wrote:
> On Apr 22, 1:24 pm, Michael Bentley <[EMAIL PROTECTED]> wrote:
>> On Apr 22, 2007, at 1:49 PM, proctor wrote:
>>
>>
>>
>>> i have a small function which mimics binary counting.  it runs fine as
>>> long as the input is not too long, but if i give it input longer than
>>> 8 characters it gives
>>> RuntimeError: maximum recursion depth exceeded in cmp
>>> i'm not too sure what i am doing improperly.  is there really a lot of
>>> recursion in this code?
>>> ==
>>> import sys
>>> def ch4(item, n=0):
>>>if n < len(item):
>>>if item[n] == '0':
>>>item[n] = '1'
>>>print ''.join(item)
>>>ch4(item)
>>>elif item[n] == '1':
>>>item[n] = '0'
>>>ch4(item, n+1)
>>> ch4(list(sys.argv[1]))
>>> ==
>> Yes.  There really is *that* much recursion in that code.  502 levels
>> with input length of 8 characters, 1013 with 9 characters, 2035 with
>> 10 characters...  There's a pattern there ;-)
> 
> ok, thanks michael!
> 
> is there a way to avoid it here?  how could i write this better, (if
> at all)?

Google for permutation-like recipies:

 http://www.google.com/search?q=Python+permutations

Use the code from the first hit::

 >>> for x in xselections('01', 8):
 ... print ''.join(x)
 ...
 
 0001
 0010
 ...
 1101
 1110
 

Explaining to your teacher why your code uses generators when you 
haven't been taught them yet is left as an exercise to the reader. ;-)

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


Re: python style guide inconsistencies

2007-04-22 Thread Martin v. Löwis
Darren Dale schrieb:
> I was just searching for some guidance on how to name packages and modules,
> and discovered some inconsistencies on the www.python.org.
> http://www.python.org/doc/essays/styleguide.html says "Module names can be
> either MixedCase or lowercase." That page also refers to PEP 8 at
> http://www.python.org/dev/peps/pep-0008/, which says "Modules should have
> short, all-lowercase names. ... Python packages should also have short,
> all-lowercase names ...".
> 
> Which is most up to date? Is this the right place to point out that one of
> those pages needs to be updated?

No - this is better discussed on python-dev.

In any case, there isn't technically a contradiction. Module names
MUST be either MixedCase or lowercase; they SHOULD be lowercase.

So unfortunately, for tradition, some module names are mixed case
(such as ConfigParser or StringIO). I can personally accept that as
a necessary evil, although I would prefer if all modules were
lower case.

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


Re: Vector classes

2007-04-22 Thread Will McGugan
Mizipzor wrote:
> During my coding Ive found two vector classes on the internet. Ive
> modified them both a little but the do both have advantages and
> disadvantages.
> 
I'm working on a vector class at the moment, in my 'gameobjects' 
library. It's not really ready for public consumption, but feel free to 
take a look...

http://www.willmcgugan.com/game-objects/

--
blog: http://www.willmcgugan.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursion depth problem

2007-04-22 Thread proctor
On Apr 22, 1:24 pm, Michael Bentley <[EMAIL PROTECTED]> wrote:
> On Apr 22, 2007, at 1:49 PM, proctor wrote:
>
>
>
> > i have a small function which mimics binary counting.  it runs fine as
> > long as the input is not too long, but if i give it input longer than
> > 8 characters it gives
>
> > RuntimeError: maximum recursion depth exceeded in cmp
>
> > i'm not too sure what i am doing improperly.  is there really a lot of
> > recursion in this code?
>
> > ==
>
> > import sys
>
> > def ch4(item, n=0):
> >if n < len(item):
> >if item[n] == '0':
> >item[n] = '1'
> >print ''.join(item)
> >ch4(item)
> >elif item[n] == '1':
> >item[n] = '0'
> >ch4(item, n+1)
>
> > ch4(list(sys.argv[1]))
>
> > ==
>
> Yes.  There really is *that* much recursion in that code.  502 levels
> with input length of 8 characters, 1013 with 9 characters, 2035 with
> 10 characters...  There's a pattern there ;-)

ok, thanks michael!

is there a way to avoid it here?  how could i write this better, (if
at all)?

proctor.

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


Re: Python's handling of unicode surrogates

2007-04-22 Thread Leo Kislov
On Apr 20, 7:34 pm, Rhamphoryncus <[EMAIL PROTECTED]> wrote:
> On Apr 20, 6:21 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > If you absolutely think support for non-BMP characters is necessary
> > in every program, suggesting that Python use UCS-4 by default on
> > all systems has a higher chance of finding acceptance (in comparison).
>
> I wish to write software that supports Unicode.  Like it or not,
> Unicode goes beyond the BMP, so I'd be lying if I said I supported
> Unicode if I only handled the BMP.

Having ability to iterate over code points doesn't mean you support
Unicode. For example if you want to determine if a string is one word
and you iterate over code points and call isalpha you'll get incorrect
result in some cases in some languages (just to backup this
claim this isn't going to work at least in Russian. Russian language
uses U+0301 combining acute accent which is not part of the alphabet
but it's an element of the Russian writing system).

IMHO what is really needed is a bunch of high level methods like
.graphemes() - iterate over graphemes
.codepoints() - iterate over codepoints
.isword() - check if the string represents one word
etc...

Then you can actually support all unicode characters in utf-16 build
of Python. Just make all existing unicode methods (except
unicode.__iter__) iterate over code points. Changing __iter__
to iterate over code points will make indexing wierd. When the
programmer is *ready* to support unicode he/she will explicitly
call .codepoints() or .graphemes(). As they say: You can lead
a horse to water, but you can't make it drink.

  -- Leo

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


[ANN] Pythonutils 0.3.0

2007-04-22 Thread Fuzzyman
There is a new (and long overdue) release of the `Pythonutils module
`_.
This is version **0.3.0**.

* `Quick Download: Pythonutils 0.3.0.zip `_


What is Pythonutils?
===

Pythonutils is a collection of general utility modules that simplify
common programming tasks in Python.


The modules included are :

* `ConfigObj `_
4.4.0   - Easy config file reading/writing
* `validate `_
0.2.3   - Validation and type conversion system
* `StandOut `_
3.0.0   - Simple logging and output control object
* `pathutils `_
0.2.5   - For working with paths and files
* `cgiutils `_
0.3.5   - {acro;CGI} helpers
* `urlpath `_
0.1.0   - Functions for handling URLs
* `odict `_
0.2.2   - Ordered Dictionary Class


For more details, visit the `Pythonutils Homepage `_.


What is New in 0.3.0?


Several of the modules have been updated. The major changes are:

* Removed the `listquote `_ module
* ConfigObj updated to 4.4.0
* StandOut updated to 3.0.0 (*Not* backwards compatible, but much
improved)

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


Re: Select weirdness

2007-04-22 Thread Jean-Paul Calderone
On Sun, 22 Apr 2007 11:42:10 -0700, Ron Garret <[EMAIL PROTECTED]> wrote:
>I think I've figured out what's going on.
>
> [snip]
>
>As you can see, the select call shows input available for a while (five
>lines) and then shows no input available despite the fact that there is
>manifestly still input available.
>
>The answer is obvious: select is looking only at the underlying socket,
>and not at the rfile buffers.
>
>So... is this a bug in select?  Or a bug in my code?

In your code, unfortunately.  select() is for file descriptors, not arbitrary
buffering Python file objects.  You shouldn't use readline if you want select
to work right, and vice versa.  Use read() and do your own line buffering
(it's trivial) or don't use select (which I believe has been suggested, and I
can't tell from your code why you want to use select in the first place).

Or avoid the low-level networking entirely and use a high-level HTTP library
that takes care of these details for you.

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


Re: Dictionaries and dot notation

2007-04-22 Thread Martin Drautzburg
Daniel Nogradi wrote:


>> > What if I want to create a datastructure that can be used in dot
>> > notation without having to create a class, i.e. because those
>> > objects have no behavior at all?
>>
>> A class inheriting from dict and implementing __getattr__ and
>> __setattr__ should do the trick...
> 
> 
> It can do the trick but one has to be careful with attributes that are
> used by dict such as update, keys, pop, etc. Actually it's noted in a
> comment at
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668 why the
> whole idea (attribute access of dictionaries) is a bad idea and I tend
> to agree.

Oh thank you. So all I have to do is have my object's class implement
__setattr__ and __getattr__, or derive it from a class that does so?
And I could save my "attributes" anywhere within my instance variables.
So I could even add a dictionary whose name does not conflict with what
python uses and whose key/value pairs hold the attributes I want to
access with dot notation and delegate all the python attributes to
their native positions? Oh I see, thats tricky. I still need to be
aware of the builtin stuff one way or the other.

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


python style guide inconsistencies

2007-04-22 Thread Darren Dale
I was just searching for some guidance on how to name packages and modules,
and discovered some inconsistencies on the www.python.org.
http://www.python.org/doc/essays/styleguide.html says "Module names can be
either MixedCase or lowercase." That page also refers to PEP 8 at
http://www.python.org/dev/peps/pep-0008/, which says "Modules should have
short, all-lowercase names. ... Python packages should also have short,
all-lowercase names ...".

Which is most up to date? Is this the right place to point out that one of
those pages needs to be updated?

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


Re: recursion depth problem

2007-04-22 Thread Michael Bentley

On Apr 22, 2007, at 1:49 PM, proctor wrote:

> i have a small function which mimics binary counting.  it runs fine as
> long as the input is not too long, but if i give it input longer than
> 8 characters it gives
>
> RuntimeError: maximum recursion depth exceeded in cmp
>
> i'm not too sure what i am doing improperly.  is there really a lot of
> recursion in this code?
>
> ==
>
> import sys
>
> def ch4(item, n=0):
>   if n < len(item):
>   if item[n] == '0':
>   item[n] = '1'
>   print ''.join(item)
>   ch4(item)
>   elif item[n] == '1':
>   item[n] = '0'
>   ch4(item, n+1)
>
> ch4(list(sys.argv[1]))
>
> ==


Yes.  There really is *that* much recursion in that code.  502 levels  
with input length of 8 characters, 1013 with 9 characters, 2035 with  
10 characters...  There's a pattern there ;-)

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


Re: Namespaces/introspection: collecting sql strings for validation

2007-04-22 Thread Scott David Daniels
Martin Drautzburg wrote:
> I would like to validate sql strings, which are spread all over the
> code,  The statements will not be assembled from smaller pieces,
> but they will not neccessarily be defined at module level. I could
> live with class level, 
> parse the source file, but I am willing to mark the strings so it is
> easier to tell sql from non-sql.
> 
> ... Or is there a completely different way to do such a thing?

How about using some variation of:
 class _Dummy: pass
 OLD_STYLE = type(_Dummy)


 def generate_strings(module):
 '''Generatetriples for a module'''
 for top_level_name in dir(module):
 top_level_value = getattr(module, top_level_name)
 if isinstance(top_level_value, basestring): # strings
 yield None, top_level_name, top_level_value
 elif isinstance(top_level_value, type): # new-style class
 for name in dir(top_level_value):
 value = getattr(top_level_value, name)
 if isinstance(value, basestring):
 yield top_level_name, name, value


 def sometest(somestring):
 '''Your criteria for "is an SQL string and has misspellings".'''
 return len(somestring) > 20 and '


 def investigate(module):
 for modname in sys.argv[1:]:
 for class_, name, text in generate_strings(
  __import__(modname)):
  if remarkable(text):
  if class_ is None:
   print 'Look at %s's top-level string %s.' % (
modname, name)
  else:
   print "Look at %s, class %s, string %s.' %
modname, class_, name)


 if __name__ == '__main__':
 import sys
 for modname in sys.argv[1: ]:
 investigate(modname, sometest)

-- 
--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


sharon stone paris hilton

2007-04-22 Thread S S
sharon  stone paris hilton 



www.alphasearch.at
www.alphasearch.be 
www.alphasearch.it
www.alphasearch.info
www.alphasearch.gr 
www.alphasearch.es 
www.alphasearch.se
www.alphasearch.dk -- 
http://mail.python.org/mailman/listinfo/python-list

recursion depth problem

2007-04-22 Thread proctor
hello,

i have a small function which mimics binary counting.  it runs fine as
long as the input is not too long, but if i give it input longer than
8 characters it gives

RuntimeError: maximum recursion depth exceeded in cmp

i'm not too sure what i am doing improperly.  is there really a lot of
recursion in this code?

==

import sys

def ch4(item, n=0):
if n < len(item):
if item[n] == '0':
item[n] = '1'
print ''.join(item)
ch4(item)
elif item[n] == '1':
item[n] = '0'
ch4(item, n+1)

ch4(list(sys.argv[1]))

==

this function expects input in the form of a string of zeros, like
this:

python test-bin.py 

and is expected to output a list of permutations like this:

$ python test-bin.py 
1000
0100
1100
0010
1010
0110
1110
0001
1001
0101
1101
0011
1011
0111


thanks for all help!

sincerely,
proctor

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


Re: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident ***

2007-04-22 Thread Jim Thompson
Ignorant Bastard Poster

On 22 Apr 2007 11:32:34 -0700, [EMAIL PROTECTED] wrote:

>Dr Gideon Polya published some 130 works in a 4 decade scientific
>career, most recently a huge pharmacological reference text
>"Biochemical Targets of Plant Bioactive Compounds" (Taylor & Francis,
>New York & London, 2003), and is currently editing a completed book on
>global avoidable mortality (numerous articles on this matter can be
>found by a simple Google search for "Gideon Polya" and on his
>websites:
>
>Here is the BRILLIANT AND INCISIVE ANALYSIS:
>
>http://countercurrents.org/polya230407.htm <--
>
>Dr Polya, we are incredibly proud of you. God Bless you for your
>courage.


...Jim Thompson
-- 
|  James E.Thompson, P.E.   |mens |
|  Analog Innovations, Inc. | et  |
|  Analog/Mixed-Signal ASIC's and Discrete Systems  |manus|
|  Phoenix, ArizonaVoice:(480)460-2350  | |
|  E-mail Address at Website Fax:(480)460-2142  |  Brass Rat  |
|   http://www.analog-innovations.com   |1962 |
 
 America: Land of the Free, Because of the Brave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Select weirdness

2007-04-22 Thread Ron Garret
I think I've figured out what's going on.

First, here's the smoking gun: I changed the code as follows:

class myHandler(StreamRequestHandler):
  def handle(self):
print '>>>'
while 1:
  sl = select([self.rfile],[],[],1)[0]
  print sl
  l = self.rfile.readline()
  if len(l)<3: break
  print l,
  pass

(Rest of code is unchanged.)

In other words, I select on the rfile object and added a timeout.

Here's the result when I cut-and-paste an HTTP request:

>>>
[]
GET /foo/baz HTTP/1.1
[]
Accept: */*
[]
Accept-Language: en
[]
Accept-Encoding: gzip, deflate
[]
Cookie: c1=18:19:55.042196; c2=18:19:55.042508
[]
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en) 
AppleWebKit/419 (KHTM
[]
L, like Gecko) Safari/419.3
[]
Connection: keep-alive
[]
Host: localhost:8081
[]


As you can see, the select call shows input available for a while (five 
lines) and then shows no input available despite the fact that there is 
manifestly still input available.

The answer is obvious: select is looking only at the underlying socket, 
and not at the rfile buffers.

So... is this a bug in select?  Or a bug in my code?

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


pickled object, read and write..

2007-04-22 Thread [EMAIL PROTECTED]
Hi all.

I have to put together some code that reads high scores from a saved
file, then gives the user the opportunity to add their name and score
to the high scores list, which is then saved.

Trouble is, I can't tell the program to read a file that doesn't
exist, that generates an error.

So I must have a file created, problem HERE is everytime the program
is run, it will overwrite the current list of saved high scores.

Advice would be much appreciated.

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


*** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident ***

2007-04-22 Thread thermate
Dr Gideon Polya published some 130 works in a 4 decade scientific
career, most recently a huge pharmacological reference text
"Biochemical Targets of Plant Bioactive Compounds" (Taylor & Francis,
New York & London, 2003), and is currently editing a completed book on
global avoidable mortality (numerous articles on this matter can be
found by a simple Google search for "Gideon Polya" and on his
websites:

Here is the BRILLIANT AND INCISIVE ANALYSIS:

http://countercurrents.org/polya230407.htm <--

Dr Polya, we are incredibly proud of you. God Bless you for your
courage.

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


Re: Namespaces/introspection: collecting sql strings for validation

2007-04-22 Thread Martin Drautzburg
Peter Otten wrote:

> Martin Drautzburg wrote:
> 
>> I would like to validate sql strings, which are spread all over the
>> code, i.e. I run ("prepare") them against a database to see if it
>> happy with the statements. Spelling errors in sql have been a major
>> pain for me.

> 
> def validateSQL(filename=None):
> if filename is None:
> # by default operate on the calling module
> filename = sys._getframe(1).f_globals["__file__"]
> for s in strings(filename):
> print "validating", repr(s)

This involves parsing the file. I can see that it would even work on a
pyc file and it actually does solve the problem. Still (for the glory
of the human mind) I would like to do this without parsing a file, but
just the python internal memory. 

> Another option would be to mark SQL statements similar to gettext by
> enclosing them in a function call
> 
> sql = SQL("select * from...")
> 
> and then defining SQL() as either a no-op in production or an actual
> validation while you are debugging. Even simpler and safer would be to
> always validate once:
> 
> def SQL(sql, checked=set()):
> if sql in checked:
> return True
> if not valid_sql(sql): raise ValueError
> checked.add(sql)
> return sql

No this does not do the trick. I will not be able to validate an sql
statement bofore I run over the piece of code that uses it. Or I would
have to define all my sql = SQL stuff on module level, isn't id. I
mean, the problem is: when are those sql = SQL statement really
ececuted?

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


Re: Dictionaries and dot notation

2007-04-22 Thread Martin Drautzburg

> mydata = data( )
> mydata.foo = 'foo'
> mydata.bar = 'bar'
> 
> print mydata.foo
> print mydata.bar

I am aware of all this.
Okay let me rephrase my question: is there a way of using dot notation
without having to create a class?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Select weirdness

2007-04-22 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 Ron Garret <[EMAIL PROTECTED]> wrote:

> Here's my code.  It's a teeny weeny little HTTP server.  (I'm not really 
> trying to reinvent the wheel here.  What I'm really doing is writing a 
> dispatching proxy server, but this is the shortest way to illustrate the 
> problem I'm having):
> 
> from SocketServer import *
> from socket import *
> from select import select
> 
> class myHandler(StreamRequestHandler):
>   def handle(self):
> print '>>>'
> while 1:
>   sl = select([self.rfile],[],[])[0]
>   if sl:
> l = self.rfile.readline()
> if len(l)<3: break
> print l,
> pass
>   pass
> print>>self.wfile, 'HTTP/1.0 200 OK'
> print>>self.wfile, 'Content-type: text/plain'
> print>>self.wfile
> print>>self.wfile, 'foo'
> self.rfile.close()
> self.wfile.close()
> print ''
> pass
>   pass
> 
> def main():
>   server = TCPServer(('',8080), myHandler)
>   server.serve_forever()
>   pass
> 
> if __name__ == '__main__': main()
> 
> 
> If I telnet into this server and type in an HTTP request manually it 
> works fine.  But when I try to access this with a browser (I've tried 
> Firefox and Safari -- both do the same thing) it hangs immediately after 
> reading the first line in the request (i.e. before reading the first 
> header).
> 
> When I click the "stop" button in the browser it breaks the logjam and 
> the server reads the headers (but then of course it dies trying to write 
> the response to a now-closed socket).
> 
> The only difference I can discern is that the browser send \r\n for 
> end-of-line while telnet just sends \n.  But I don't see why that should 
> make any difference.  So I'm stumped.  Any clues would be much 
> appreciated.

I have reproduced the problem using Telnet, so that proves it's not an 
EOL issue.  The problem seems to be timing-related.  If I type the 
request in manually it works.  If I paste it in all at once, it hangs.  
It's actually even weirder than that: if I pipe the request into a 
telnet client then it hangs after the request line, just with a browser 
(or wget).  But if I literally paste the request into a window running a 
telnet client, it gets past the request line and four out of seven 
headers before it hangs.

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


Re: Convert from/to struct_time

2007-04-22 Thread Diez B. Roggisch
Florian Lindner schrieb:
> Hello,
> I have a struct_time and a datetime object and need compare them. Is there
> any function that converts either of these two to another?


datetime.datetime(*time.localtime()[:6])

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


Convert from/to struct_time

2007-04-22 Thread Florian Lindner
Hello,
I have a struct_time and a datetime object and need compare them. Is there
any function that converts either of these two to another?

Thanks,

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


file.read() returns an emtpy even if its currenet position is not at the end

2007-04-22 Thread js
Hi list.

I'm writing a tail -f like program in python
and I found file.read() doesn't work as I think it should.

Here's the code illustrating my problem.

###
#!/usr/bin/env python
import os, sys
filename = "test.out"

f = open(filename, "w+")
f.write("Hello")
f.flush()

f.seek(0, 2)

statinfo = os.stat(filename)
print "file size: %d" % statinfo.st_size
print "position : %d" % f.tell()
line = f.read()
print "line : [%s]" % line

# Writing the same file using another fd
f2 = open(filename, "a+")
f2.write("World")
f2.flush()
f2.close()

statinfo = os.stat(filename)
print "file size: %d" % statinfo.st_size
print "position : %d" % f.tell()
line = f.read() # read() returns emtpy!! readlines?() works ok
###

Running the above, I got the following.
###
file size: 5
position : 5
line : []
file size: 10
position : 5
###

So my question is
why the second f.read() returns an emtpy?
>From tell() and its st_size I'm sure that file descriptor is not at the EOF
and read()'s doc says
"An empty string is returned when EOF is encountered immediately".
Using readline() or readlines() instead of read() works great though.

I'm using  Python  2.4.3 on OS X.

Probably I'm missing something but I could't figure out.

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


Re: Flat DB seeking speed

2007-04-22 Thread Aahz
In article <[EMAIL PROTECTED]>,
Jia Lu  <[EMAIL PROTECTED]> wrote:
>
> I see there are lots of flat db or db-like modules in the standard
>python modules.
> What about the keywords seeking speed of them ?
>
> (I want to put about 1 articles with 1 IDs, and I can do
>searching keywords with them)
>
> The db-like modules are :
> dbm, gdbm, dbhash,anydbm,
> pickle(cPickle), shelve, marshal

Another option would be to use a real database, such as SQLite.  Then you
could easily create an inverted index with your keywords.  This is a good
alternative to full-text indexing when you otherwise want DB capabilities
(such as for storing other information with your articles).
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

Help a hearing-impaired person: http://rule6.info/hearing.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No speedup on multi-processor machine?

2007-04-22 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
John Nagle  <[EMAIL PROTECTED]> wrote:
>Caleb Hattingh wrote:
>> On Apr 21, 11:02 pm, [EMAIL PROTECTED] wrote:
>> 
>>>Hi,
>>>I am using Python Thread library for my parallel processing course
>>>project. I am doing matrix convolution on a multi-processor machine
>>>running Solaris. I just found out that no speed-up is obtained with
>>>threading. It is probably because of something called GIL in Python.
>>>How can I get around
>>>that GIL and get speed-up?
>>>Thanks in advance.
>>>Daniel
>
>If you're actually doing the convolution in Python, you need
>optimization before you need more CPUs.  There's a numerics library
>for Python called NumPy, but it doesn't have a convolution function,
>although it has an FFT, which may be useful.
>
>But this is just homework.  Do something reasonable and turn it
>in.  A high performance solution to this problem is probably more
>work than it's worth.
>
>   John Nagle

Along with the excellent advice given by Dennis, John, and the
rest, please be aware that *process*-level parallelization of
a problem sometimes is a benefit.  As already recommended, http://wiki.python.org/moin/ParallelProcessing > touches on most
of the pertinent concepts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Support for new items in set type

2007-04-22 Thread Aahz
In article <[EMAIL PROTECTED]>,
Prateek  <[EMAIL PROTECTED]> wrote:
>
>Thanks Alex, but we're actually implementing a (non-relational)
>database engine. 

Why are you reinventing the wheel?  Why not just implement your
functionality on top of an existing database as your backing store?
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

Help a hearing-impaired person: http://rule6.info/hearing.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionaries and dot notation

2007-04-22 Thread Bruno Desthuilliers
Martin Drautzburg a écrit :
> This may be pretty obvious for most of you:
> 
> When I have an object (an instance of a class "Foo") I can access
> attributes via dot notation:
> 
> aFoo.bar
> 
> however when I have a dictionary 
> 
> aDict = {"bar":"something"}
> 
> I have to write
> 
> aDict["bar"]
> 
> What if I want to create a datastructure that can be used in dot
> notation without having to create a class, i.e. because those objects
> have no behavior at all?

A class inheriting from dict and implementing __getattr__ and 
__setattr__ should do the trick...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python cgi problem with textarea

2007-04-22 Thread Adrian Smith
On Apr 22, 10:09 pm, placid <[EMAIL PROTECTED]> wrote:

> i just tried it and its working. here it is
>
> http://yallara.cs.rmit.edu.au/~bevcimen/form.html
>
> maybe the internal server error is because mod_python isn't installed
> assuming your using Apache as your web server

Yeah, but it wouldn't work *at all* in that case, would it? ATM it
seems to work as long as the textarea input has no spaces.

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


Re: python cgi problem with textarea

2007-04-22 Thread Jim
On Apr 22, 2:08 am, Adrian Smith <[EMAIL PROTECTED]> wrote:
> ...and I get an internal server error if I have any spaces in the
> textarea,
And what error appears in the server error log?

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


Re: Select weirdness

2007-04-22 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 Irmen de Jong <[EMAIL PROTECTED]> wrote:

> Ron Garret wrote:
> > Here's my code.  It's a teeny weeny little HTTP server.  (I'm not really 
> > trying to reinvent the wheel here.  What I'm really doing is writing a 
> > dispatching proxy server, but this is the shortest way to illustrate the 
> > problem I'm having):
> > 
> > from SocketServer import *
> > from socket import *
> > from select import select
> > 
> > class myHandler(StreamRequestHandler):
> >   def handle(self):
> > print '>>>'
> > while 1:
> >   sl = select([self.rfile],[],[])[0]
> >   if sl:
> > l = self.rfile.readline()
> > if len(l)<3: break
> > print l,
> > pass
> >   pass
> > print>>self.wfile, 'HTTP/1.0 200 OK'
> > print>>self.wfile, 'Content-type: text/plain'
> > print>>self.wfile
> > print>>self.wfile, 'foo'
> > self.rfile.close()
> > self.wfile.close()
> > print ''
> > pass
> >   pass
> 
> 
> You shouldn't use a select() of your own inside the handle method.
> The socketserver takes care of that for you.

I don't understand why socketserver calling select should matter.  (And 
BTW, there are no calls to select in SocketServer.py.  I'm using 
Python2.5.)

> What you need to do is read the input from the socket until you've reached
> the end-of-input marker. That marker is an empty line containing just "\r\n"
> when dealing with HTTP GET requests.
>
> Any reason don't want to use the BasicHTTPServer that comes with Python?

Yes, but it's a long story.  What I'm really doing is writing a 
dispatching proxy.  It reads the HTTP request and then redirects it to a 
number of different servers depending on the URL.  The servers are all 
local and served off of unix sockets, not TCP sockets (which is why I 
can't just configure Apache to do this).

The reason I'm running this weird configuration (in case you're 
wondering) is because this is a development machine and multiple copies 
of the same website run on it simultaneously.  Each copy of the site 
runs a customized server to handle AJAX requests efficiently.

> 
> Anyway, try the following instead:
> 

That won't work for POST requests.

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


Re: serializable object references

2007-04-22 Thread Martin Drautzburg
Gabriel Genellina wrote:

> En Sun, 22 Apr 2007 08:07:27 -0300, Martin Drautzburg
> <[EMAIL PROTECTED]> escribió:
> 
>> Is it possible to convert an object into a string that identifies the
>> object in a way, so it can later be looked up by this string.
>> Technically this should be possible, because things like
>>
>> <__main__.Foo instance at 0xb7cfb6ac>
>>
>> say everything about an object. But how can I look up the real
>> object, when I only have this string?
>>
>> I know such a thing can be achieved with a dictionary that holds
>> reference-object pairs. Is there another way?
> 
> Without further information, this would be the way.
> What do you want to achieve? Maybe you are looking for the pickle
> module.
> 

I was thinking that it would be nice if a web application could talk to
real objects. The client side does not need to know the internals of an
object, it acts as a "view" for server-side models. All it has to be
able to do is invoke methods on "its" model. So a view could just
store "its" object-reference in an instance variable and pass it to the
server, where my problem of looking it up comes in.

I am currently learning about web services but my feeling is
that "state" is not an integral part of this concept, rather an add-on,
but I may be mistaken here.

But for any reasonable web application you have to introduce state one
way or the other. My impression is, that this is achieved with "session
objects", which hold all the state of a session (again I may be
mistaken). But this would be a strange concept in an OO world. You
might as well put "ALL" state into a global "state" state object, where
all the class methods deposit their state and classes would hold
behavior only and no state. This is of course nothing an OO programmer
would want to do. 




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


Re: No speedup on multi-processor machine?

2007-04-22 Thread danfan1981
Thanks guys. But I think IronPython only works on Windows machine, but
I am using a Sun machine. I was suggested to use Jython, which can run
on Sun. But I need to use Numpy for matrix operations, which is only
available to CPython.

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


Re: Python "robots.txt" parser broken since 2003

2007-04-22 Thread Steven Bethard
John Nagle wrote:
> Terry Reedy wrote:
>> "John Nagle" <[EMAIL PROTECTED]> wrote in message 
>> news:[EMAIL PROTECTED]
>> | This was reported in 2003, and a patch was uploaded in 2005, but the 
>> patch
>> | never made it into Python 2.4 or 2.5.
>>
>> If the patch is still open, perhaps you could review it.
>>
> I tried it on Python 2.4 and it's in our production system now.
> But someone who regularly does check-ins should do this.

If you post such a review (even just the short sentence above) to the 
patch tracker, it often increases the chance of someone committing the 
patch.

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


  1   2   >