Re: Lookuperror : unknown encoding : utf-8

2006-10-29 Thread thebjorn
Sachin Punjabi wrote:
> I wanted to read a file encoded in utf-8 and and using the following
> syntax in my source which throws me an error specifying Lookuperror :
> unknown encoding : utf-8. Also I am working on Python version 2.4.1.

You shouldn't have to do anything to have the utf-8 encoding available.
Check in your lib/encodings directory for a file name utf_8.py and the
code in __init__.py in the same directory should take care of the
mapping. This has been this way since at least Python 2.2 (which is the
oldest version I have on this machine).

If that doesn't give you a clue as to what is going on in your setup,
try

  u'foo'.encode('utf-8')

at the prompt and post the complete traceback.

> import codecs
> fileObj = codecs.open( "data.txt", "r", "utf-8" )

That should work fine, although I prefer to explicitly set the mode to
"rb" (it will be set to binary mode behind your back regardless ;-)

hth,
-- bjorn

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


Re: Lookuperror : unknown encoding : utf-8

2006-10-29 Thread Leo Kislov

Sachin Punjabi wrote:
> Hi,
>
> I wanted to read a file encoded in utf-8 and and using the following
> syntax in my source which throws me an error specifying Lookuperror :
> unknown encoding : utf-8. Also I am working on Python version 2.4.1.
>
> import codecs
> fileObj = codecs.open( "data.txt", "r", "utf-8" )
>
> Can anyone please guide me how do I get utf-8 activated in my codecs or
> any setting needs to be done for the same before using codecs.

What OS? Where did you get your python distribution? Anyway, I believe
utf-8 codec was in the python.org distribution since the introduction
of unicode (around python 2.0). If you can't use utf-8 codec right out
of the box, something is really wrong with your setup.

  -- Leo

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


Re: subprocess decoding?

2006-10-29 Thread Leo Kislov

MC wrote:
> Hi!
>
> On win-XP (french), when I read subprocess (stdout), I must use
> differents decoding (cp1252,cp850,cp437, or no decoding), depending of
> the "launch mode" of the same Python's script:
>   - from command-line
>   - from start+run
>   - from icon
>   - by Python-COM-server
>   - etc.
>
> (.py & .pyw can also contribute)
>
>
> How to know, on the fly, the encoding used by subprocess?

You can't. Consider a Windows equivalent of UNIX "cat" program. It just
dump content of a file to stdout. So the problem of finding out the
encoding of stdout is equal to finding out encoding of any file. It's
just impossible to do in general. Now, you maybe talking about
conventions. AFAIK since Windows doesn't have strong command line
culture, it doesn't such conventions.

  -- Leo

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


Lookuperror : unknown encoding : utf-8

2006-10-29 Thread Sachin Punjabi
Hi,

I wanted to read a file encoded in utf-8 and and using the following
syntax in my source which throws me an error specifying Lookuperror :
unknown encoding : utf-8. Also I am working on Python version 2.4.1.

import codecs
fileObj = codecs.open( "data.txt", "r", "utf-8" )

Can anyone please guide me how do I get utf-8 activated in my codecs or
any setting needs to be done for the same before using codecs.

Regards
Sachin Punjabi.

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


Re: Is there a way to get utf-8 out of a Unicode string?

2006-10-29 Thread Gerrit Holl
Hei,

On 2006-10-30 08:25:41 +0100, thebjorn wrote:
>   def unfk(s):
>   return eval(repr(s)[1:]).decode('utf-8')
> 
> i.e. chopping off the u in the repr of a unicode string, and relying on
> eval to interpret the \xHH sequences.
> 
> Is there a less hack'ish way to do this?

Slightly lack hackish:

return ''.join(chr(ord(c)) for c in s)

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


Re: Is there a way to get utf-8 out of a Unicode string?

2006-10-29 Thread Fredrik Lundh
thebjorn wrote:

> I've got a database (ms sqlserver) that's (way) out of my control,
> where someone has stored utf-8 encoded Unicode data in regular varchar
> fields, so that e.g. the string 'Blåbærsyltetøy' is in the database
> as 'Bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y' :-/
> 
> Then I read the data out using adodbapi (which returns all strings as
> Unicode) and I get u'Bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y'. I couldn't
> find any way to get back to the original short of:
> 
>   def unfk(s):
>   return eval(repr(s)[1:]).decode('utf-8')
> 
> i.e. chopping off the u in the repr of a unicode string, and relying on
> eval to interpret the \xHH sequences.
> 
> Is there a less hack'ish way to do this?

first, check if you can get your database adapter to understand that the 
database contains UTF-8 and not ISO-8859-1.  if that's not possible, you 
can roundtrip via ISO-8859-1 yourself:

 >>> u = u'Bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y'
 >>> u
u'Bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y'
 >>> u.encode("iso-8859-1")
'Bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y'
 >>> u.encode("iso-8859-1").decode("utf-8")
u'Bl\xe5b\xe6rsyltet\xf8y'
 >>> print u.encode("iso-8859-1").decode("utf-8")
Blåbærsyltetøy



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


Re: Event driven server that wastes CPU when threaded doesn't

2006-10-29 Thread Fredrik Lundh
Bjoern Schliessmann wrote:

>> If that is not an option, then you are faced with a problem of
>> connecting a threaded programming model with an event based model
>> (twisted and and such).
> 
> I don't really see how threads could avoid a problem with delays in
> one connection ...

by running the database queries in one or more separate threads, you can 
still serve requests that don't hit the database (either because they're 
entirely self-contained, or because they only rely on cached data).



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


Is there a way to get utf-8 out of a Unicode string?

2006-10-29 Thread thebjorn
I've got a database (ms sqlserver) that's (way) out of my control,
where someone has stored utf-8 encoded Unicode data in regular varchar
fields, so that e.g. the string 'Blåbærsyltetøy' is in the database
as 'Bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y' :-/

Then I read the data out using adodbapi (which returns all strings as
Unicode) and I get u'Bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y'. I couldn't
find any way to get back to the original short of:

  def unfk(s):
  return eval(repr(s)[1:]).decode('utf-8')

i.e. chopping off the u in the repr of a unicode string, and relying on
eval to interpret the \xHH sequences.

Is there a less hack'ish way to do this?

-- bjorn

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


Re: Is it possible to use python to unit test C++ code?

2006-10-29 Thread Fredrik Lundh
Liu HuaDong-E6754C wrote:

> Did any one used python to do C++ unit test?
> If u did, could u give some actions how to do unit test by using python.

use a standard tool to generate a binding for the relevant C++ libraries:

http://www.effbot.org/pyfaq/how-do-i-interface-to-c-objects-from-python.htm

and then write Python code to do the tests, preferably using an 
available Python testing framework.  this page mentions some of them:

http://www.effbot.org/pyfaq/how-do-i-test-a-python-program-or-component.htm

http://docs.python.org/lib/module-doctest.html
http://docs.python.org/lib/module-unittest.html



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


Re: Event driven server that wastes CPU when threaded doesn't

2006-10-29 Thread Bjoern Schliessmann
Nick Vatamaniuc wrote:

> If that is not an option, then you are faced with a problem of
> connecting a threaded programming model with an event based model
> (twisted and and such).

I don't really see how threads could avoid a problem with delays in
one connection ...

Regards,


Björn

-- 
BOFH excuse #175:

OS swapped to disk

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


Re: beginner's refcount questions

2006-10-29 Thread Fredrik Lundh
Jens Theisen wrote:

> Thus, the following code
> 
> class Foo:
> def __del__(self):
> print "deled!"
> 
> def foo():
> f = Foo()
> 
> foo()
> print "done!"
> 
> prints
> 
> deled!
> done!
> 
> and not the other way round.

the behaviour you see in this simple program is not guaranteed by the 
language specification, and even trivial modifications to your program 
may cause trouble even under a reference-counting implementation of 
Python.  for example,

class Foo:
 def __del__(self):
 print "deled!"

def foo():
 f = Foo()
 i = open("file.txt")
 return i.readline()

try:
 foo()
except IOError:
 pass
print "done!"

prints

done!
deled!

> In c++, this is a central technique used for all sorts of tasks,
> whereas in garbage collected languages it's usually not available.

Python is not C++.  if you want to do controlled resource management, 
you need to use "try/finally" or "with".

> Is there a reason not to rely on this in Python? For example, are
> there alternative Python implementations that behave differently?  Or
> some other subtle problems?

http://www.effbot.org/pyfaq/how-does-python-manage-memory.htm
http://www.effbot.org/pyfaq/my-class-defines-del-but-it-is-not-called-when-i-delete-the-object.htm



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


Re: Very simple request about argument setting.

2006-10-29 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> ArdPy wrote:
>> There is an error in the syntax the star must prefix the variable name
>> not suffix it.
>> Then the items variable will accept the parameter value as a tuple.
> 
> Hmm, tuples are immutable, right? I need something mutable so that when
> the player picks up an item, it's no longer in the room.

the *args syntax is used to capture extra positional arguments, so you 
can deal with them later.  consider the following code:

 def func(*args):
 args.append(4)

 func(1, 2, 3)

where do you expect the "4" to go?

if you want to *store* the items in an *instance* variable, you can 
trivially convert it to a list by passing it to the list() function:

 class Room:
   def __init__(self, name, *items):
 self.name = name
 self.items = list(items)

 r = Room("hall", "old shoe", "kitten", "vegetables")
 r.items.append("a wallclock round in metal")

> Besides which, I've been playing with this whole thing in the
> interactive interpreter:
> 
 def shuf(x,*foo, **bar):
> ...   return x, foo
> ...
 x,foo,bar = shuf(1,2,3,4,5,6,7,8)
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: need more than 2 values to unpack

if you compare the return statement inside the function with the 
assignment, do you see any notable differences?

> I remember that two stars is for the second tuple

if you're an expert on tutorials, surely you should be able to find one 
and look this up in no time at all?

(the **bar syntax captures extra *keyword* arguments)

> So what I am doing wrong?

programming by trial and error?



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


Is it possible to use python to unit test C++ code?

2006-10-29 Thread Liu HuaDong-E6754C



 
 
Did any one used python to 
do C++ unit test?
If u did, could u give some 
actions how to do unit test by using python.
 
 
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to access file last modified dates on each file in a directory

2006-10-29 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I am attempting to view all files in a directory and if those files
> have not been modified within the last couple days I will remove them.
> In order to do this I need to look at the file date modied and check
> the date. I know how to look at each file name and I know how to remove
> the file. I just can't figure out how to get access to the date last
> modifed filed. Below is how I intend to access the file names in the
> directory.
> 
 import os,time,sys
 cachedirectory="c:\\informatica\\cache\\"
 v_filename_array=os.listdir(cachedirectory)

since listdir only returns the last part of the full file path, it's 
often easier to use glob.

 for file in glob.glob("c:/informatics/cache/*"):
 ...

otherwise, you need to do os.path.join(cachedirectory, file) for each 
file in the filename list, to get a full path.

to get the age of a file, use os.path.getmtime(filename).  this returns 
the modification time as seconds since a reference time (usually called 
the "epoch".  if you subtract this time from the current time, you get 
the age (in seconds):

 import glob, os, time

 now = time.time()

 for file in glob.glob("c:/informatics/cache/*"):
 age = os.path.gettime(file) - now
 print file, "is", age / 3600, "hours old"

adding code to remove old files should be straightforward.



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


[wxPython] wxFrame don't have Bind attribute ??

2006-10-29 Thread Jia Lu
Hi all
 I am using wxPy 2.6.3.2-2, But when run an application with self.Bind
, I got an error that there is no Bind.

 How can I fix it. thanx

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


Re: Very simple request about argument setting.

2006-10-29 Thread [EMAIL PROTECTED]
Thank you very much for your information.

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


Re: Very simple request about argument setting.

2006-10-29 Thread ArdPy

[EMAIL PROTECTED] wrote:
> ArdPy wrote:
> > There is an error in the syntax the star must prefix the variable name
> > not suffix it.
> > Then the items variable will accept the parameter value as a tuple.
>
> Hmm, tuples are immutable, right? I need something mutable so that when
> the player picks up an item, it's no longer in the room.
>
> Besides which, I've been playing with this whole thing in the
> interactive interpreter:
>
> >>> def shuf(x,*foo, **bar):
> ...   return x, foo
> ...
> >>> x,foo,bar = shuf(1,2,3,4,5,6,7,8)
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: need more than 2 values to unpack
>
> I remember that two stars is for the second tuple, but how do I
> distinguish between what var is for which tuple? I've tried using
> brackets, braces, prenthisies, nothing seems to work. So what I am
> doing wrong?
The thing is that the parameter 'bar' is actually a dictionary object
so the right way of calling shuf is then
x,foo,bar = shuf(1,2,3,4,5,a=6,b=7,c=8)

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


Re: How to Split Chinese Character with backslash representation?

2006-10-29 Thread jim-on-linux
On Friday 27 October 2006 17:21, jim-on-linux 
wrote:
> On Thursday 26 October 2006 23:43, you wrote:
> > Hi all,
> >
> > I was trying to split a string that
> >
> > represent chinese characters below:
> > >>> str = '\xc5\xeb\xc7\xd5\xbc'
> > >>> print str2,
> >
> > ???
> >
> > >>> fields2 = split(r'\\',str)
> > >>> print fields2,
> >
> > ['\xc5\xeb\xc7\xd5\xbc']
> >
> > But why the split function here doesn't seem
> > to do the job for obtaining the desired
> > result:
>
 The character '\' is an escape character. It
 won't show just like '\n' won't shoe at the end 
of a line.

 To show it must be preceeded by another '\'
 like this '\\'

Try this:

x ='\xc5\xeb\xc7\xd5\xbc'

y = []
z = []
for n in x :
y.append( '\\'+n+'\\')
print y, '## y line 5\n'


for bs in y:
  bs = str.strip(bs, '\\')
  z.append(bs)
print z, '## z line 10\n'
 
The results will be 
['\xc5','\xeb','\xc7','\xd5','\xbc']


 jim-on-linux
 http://www.inqvista.com
>
> > ['\xc5','\xeb','\xc7','\xd5','\xbc']
> >
> >
> >
> > Regards,
> > -- Edward WIJAYA
> > SINGAPORE
> >
> >
> >
> >  Institute For Infocomm Research
> > - Disclaimer - This email is
> > confidential and may be privileged.  If you
> > are not the intended recipient, please delete
> > it and notify us immediately. Please do not
> > copy or use it for any purpose, or disclose
> > its contents to any other person. Thank you.
> > -
> >-- -
-- 
http://mail.python.org/mailman/listinfo/python-list


Open Source?

2006-10-29 Thread Nick Vatamaniuc
You can always start with  open source.  Find a project that you really
like based on Python, and get involved -- look at the source, create
add-ons, fix bugs. This way you get to learn, and you get to contribute
and help others out as well. After a while you will have under your
belt and perhaps it will be easier to find a job.

Mind you, a lot of place are still looking for C/C++, Java and, oh the
horror... COBOL!  Sadly Python is still mostly on the "it's nice to
know but not required category"...

-Nick V.


ArdPy wrote:
> Hi there, these days I am desperately searching everywhere on the
> Internet for part time python jobs. The reason is I want to get
> actively involved with python programming and get some practical
> exposure. Please help me in whatever way you can.

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


Re: How to access file last modified dates on each file in a directory

2006-10-29 Thread Jia Lu

[EMAIL PROTECTED] wrote:
> Greetings,
>
> I am attempting to view all files in a directory and if those files
> have not been modified within the last couple days I will remove them.
> In order to do this I need to look at the file date modied and check
> the date. I know how to look at each file name and I know how to remove
> the file. I just can't figure out how to get access to the date last
> modifed filed.

For this you have some solutions.

1,
import os
import time
time.ctime(os.stat(r"L:\MyDoc\EBook\Python").st_mtime)

2,
os.path.getmtime()

3, in Win32
win32file.GetFileTime
int = GetFileTime(handle, creationTime , accessTime , writeTime )

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


Re: looping through two list simultenously

2006-10-29 Thread Paul McGuire
"CSUIDL PROGRAMMEr" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> folks
> I have two lists
>
> i am trying to loop thorough them simultenously.
>
> Here is the code i am using
>
> f1 = os.popen('ls  chatlog*.out')
> data1=f1.readlines()
> f1.close()
>
> data1=[x.strip() for x in data1]
> f1 = os.popen('ls  chatlog*.txt')
> data=f1.readlines()
> f1.close()
> for eachline in data1 and line in data:

Change:
for eachline in data1 and line in data:

to:
for eachline, line in zip(data1,data):


-- Paul 


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


Re: Very simple request about argument setting.

2006-10-29 Thread [EMAIL PROTECTED]

ArdPy wrote:
> There is an error in the syntax the star must prefix the variable name
> not suffix it.
> Then the items variable will accept the parameter value as a tuple.

Hmm, tuples are immutable, right? I need something mutable so that when
the player picks up an item, it's no longer in the room.

Besides which, I've been playing with this whole thing in the
interactive interpreter:

>>> def shuf(x,*foo, **bar):
... return x, foo
...
>>> x,foo,bar = shuf(1,2,3,4,5,6,7,8)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: need more than 2 values to unpack

I remember that two stars is for the second tuple, but how do I
distinguish between what var is for which tuple? I've tried using
brackets, braces, prenthisies, nothing seems to work. So what I am
doing wrong?

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


Re: How to access file last modified dates on each file in a directory

2006-10-29 Thread Praveen
I hope this sample code helps

def getfileinfo(filename):
print 'Filename : %s' % filename
stats = os.stat(filename)
size = stats[stat.ST_SIZE]
print 'File Size is %d bytes' % size

accessed = stats[stat.ST_ATIME]
modified = stats[stat.ST_MTIME]

print 'Last accessed: ' + time.ctime(accessed)
print 'Last modified: ' + time.ctime(modified)

Regards,
Praveen

On Oct 30, 8:00 am, [EMAIL PROTECTED] wrote:
> Greetings,
>
> I am attempting to view all files in a directory and if those files
> have not been modified within the last couple days I will remove them.
> In order to do this I need to look at the file date modied and check
> the date. I know how to look at each file name and I know how to remove
> the file. I just can't figure out how to get access to the date last
> modifed filed. Below is how I intend to access the file names in the
> directory.
>
> >>> import os,time,sys
> >>> cachedirectory="c:\\informatica\\cache\\"
> >>> v_filename_array=os.listdir(cachedirectory)
> >>> x_len=len(v_filename_array)v_filename_array[0] = first file name
> v_filename_array[1] - second file name
> 
> Thanks'
> Rich

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


I want to work on Python

2006-10-29 Thread ArdPy
Hi there, these days I am desperately searching everywhere on the
Internet for part time python jobs. The reason is I want to get
actively involved with python programming and get some practical
exposure. Please help me in whatever way you can.

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


Re: importing class

2006-10-29 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Thanks, I got that part. The problem I'm still having is that it's not
> seeing things like text_1, which are defined in the program. How can I
> make it see that?
> 
Your module is intended to work with many different main programs, so it 
shouldn't make any assumptions about the names that the main program 
uses for things. That would be rather bad programming style ("rigind 
coupling" is something to be avoided where possible). I wouldn't call 
that class App just because it's misleading: maybe you could change the 
name to YesNo, or Choice, or something more indicative of its function?

You could pass text_1 and text_2 as arguments to the class's __init__ 
method - that way you could just use them directly.

> Another question I should ask is whether I should even bother doing
> this. That is, it seems that the elegant and approved way of doing this
> kind of thing may be to put a class in a module and then just use the
> module over and over again in programs. I'm making a few GUIs which
> present two options and ask the user to chose one, so I thought I could
> just do it this way. Of course I could very easily just copy and paste
> the class into each file, but that seems silly. I haven't had any
> trouble using modules for functions, but for classes it is not working
> right so far, and I'm having trouble finding examples to follow.
> 
Seems like parameterization is the thing you are missing. Change the 
__init__ method declaration to

 def __init__(self, master, text_1="OK", text_2="Cancel"):
 ...

leaving the rest of the code the same. (Though I note your module also 
fails to define a "command1" and "command2" function, this may just be 
because you are only quoting partial code).

Then in your main program create the object with

 myDialog = YesNo(master, "Yes", "No")

Looks like you are new to Python - perseverre and you will pick it up 
quite quickly!

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

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


wxPython for web development?

2006-10-29 Thread walterbyrd
I assume that wxWidgets can not be used if all you have is mod-python?

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


Re: Very simple request about argument setting.

2006-10-29 Thread ArdPy

[EMAIL PROTECTED] wrote:
> I have the argument items in my class room.
>
> class room:
>   def __init__(self, name, description, items*):
>
> I thought I remembered from a tutorial I read once, and I've read so
> many I feel like an expert of them, that putting a little star* above
> an item makes it accept the argument as a list. But when I tried this,
> I got an invalid syntax error message.
>
There is an error in the syntax the star must prefix the variable name
not suffix it.
Then the items variable will accept the parameter value as a tuple.
> So:
> Question 1: How can I create an argument that accepts a list of
> variable?
It is not clear whether you want to accept a list variable or an
arbitrary number of values as parameter
to the function. So I will explain each case.
def ex(name,*items):
Here name, description and items can all accept lists as arguments.
Additionally items can accept arbitrary
number of arguments even of different types.
Ex:
ex([10,12],12,13.3,'Python')
>
> Question 2: How do I signify to accept each item as one list? (my bet's
> on using another set of parens)
I have answered this already.
>
> Question 3: Or am I going about this all wrong and should always create
> a list before the fuction call and use the list in the function call?
No need u can pass a list directly into the call.

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


How to access file last modified dates on each file in a directory

2006-10-29 Thread RAMohrmann
Greetings,

I am attempting to view all files in a directory and if those files
have not been modified within the last couple days I will remove them.
In order to do this I need to look at the file date modied and check
the date. I know how to look at each file name and I know how to remove
the file. I just can't figure out how to get access to the date last
modifed filed. Below is how I intend to access the file names in the
directory.

>>> import os,time,sys
>>> cachedirectory="c:\\informatica\\cache\\"
>>> v_filename_array=os.listdir(cachedirectory)
>>> x_len=len(v_filename_array)

v_filename_array[0] = first file name
v_filename_array[1] - second file name

Thanks'
Rich

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


Re: beginner's refcount questions

2006-10-29 Thread Terry Reedy

"Jens Theisen" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> python uses gc only where refcounts alone haven't yet done the
> job.

/python/The CPython implementation/

> And some other minor question: Is there a way to query the use count
> of an object? This would be useful for debugging and testing.

sys.getrefcount I believe

thr



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


wxPython changed ??

2006-10-29 Thread Jia Lu
Hi all.
 I'm using wxPython 2.6.3.2-2 on FC 6.
 I wrote a demo used 'self.Bind(xx)' but I got an error says:
   " MyFrame instance has no attribute 'Bind' "

 I did that when I used FC 5 and it worked.

 Is new wxPy changed about the Bind method??

thanx

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


Very simple request about argument setting.

2006-10-29 Thread [EMAIL PROTECTED]
I have the argument items in my class room.

class room:
def __init__(self, name, description, items*):

I thought I remembered from a tutorial I read once, and I've read so
many I feel like an expert of them, that putting a little star* above
an item makes it accept the argument as a list. But when I tried this,
I got an invalid syntax error message.

So:
Question 1: How can I create an argument that accepts a list of
variable?

Question 2: How do I signify to accept each item as one list? (my bet's
on using another set of parens)

Question 3: Or am I going about this all wrong and should always create
a list before the fuction call and use the list in the function call?

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


Re: beginner's refcount questions

2006-10-29 Thread Jean-Paul Calderone
On 30 Oct 2006 00:30:53 +, Jens Theisen <[EMAIL PROTECTED]> wrote:
>Hello,
>
>python uses gc only where refcounts alone haven't yet done the
>job. Thus, the following code
>
>class Foo:
>def __del__(self):
>print "deled!"
>
>def foo():
>f = Foo()
>
>foo()
>print "done!"
>
>prints
>
>deled!
>done!
>
>and not the other way round.
>
>In c++, this is a central technique used for all sorts of tasks,
>whereas in garbage collected languages it's usually not available.
>
>Is there a reason not to rely on this in Python? For example, are
>there alternative Python implementations that behave differently?  Or
>some other subtle problems?

Among the numerous other reasons, there's this one:

Python 2.4.3 (#2, Oct  6 2006, 07:52:30) 
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
... def __del__(self):
... print 'collected'
... 
>>> def foo():
... f = Foo()
... 1/0
... 
>>> foo()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in foo
ZeroDivisionError: integer division or modulo by zero
>>> print 'done!'
done!
>>> raise ValueError
collected
Traceback (most recent call last):
  File "", line 1, in ?
ValueError
>>> 

>
>And some other minor question: Is there a way to query the use count
>of an object? This would be useful for debugging and testing.

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


Re: simple oop question (hopefully)

2006-10-29 Thread [EMAIL PROTECTED]
I am tagging this so I can find it again (google groups) www.dexrow.com
[EMAIL PROTECTED] wrote:
> I am just trying to acess a function in wordgrid (savefile) to a button
> that is defined in TestFrame.  I can't seem to make it work I either
> get an error that my variable isn't global or it makes other
> complaints.  thanks in advance..  sorry for the simple question..
>
>
>
>
> import wx
> import wx.grid as gridlib
> import sys
>
>
>
> #---
>
> class WordGrid(gridlib.Grid):
>
> def __init__(self, parent, log):
> gridlib.Grid.__init__(self, parent, -1)
> self.loadFile()
>
> self.CreateGrid(len(self.rows), self.widestRow)
>
> for r, row in enumerate(self.rows):
> for c, col in enumerate(row):
> self.SetCellValue(r, c, col)
> self.SetColSize(c, 10*self.widestCol)
>
> for c, label in enumerate(self.header):
> self.SetColLabelValue(c, label)
>
> def loadFile(self):
>#from_file
>infile = open(sys.argv[1], 'r') #The first argument passed in is
> the file name
>foundHeader = False
>self.rows = []
>for line in infile:
>if sys.argv[2] in line: #look for the second argument and
> make that the header
>#removefirst = line.split(' ')
>self.header = line.split()
>#foundHeader = 'true'
>continue # we don't want to process this line any
> further
>else:
>self.rows.append(line.split())
>
>self.widestRow = max([len(r) for r in self.rows])
>self.widestCol = max([len(c) for c in [r for r in self.rows]])
> def savefile(self):
> outfile = open(sys.argv[1], 'w') #open the file defined in the
> output line for writing
> for row in self.rows:
> outfile.write(row)
>
> print('this is a test to see if I can Crash it')
>
>
>
> class TestFrame(wx.Frame):
> def __init__(self, parent, log):
>
> wx.Frame.__init__(self, parent, -1, "Dex Tracker Sco Editor",
> size=(640,480))
> p = wx.Panel(self, -1, style=0)
> grid = WordGrid(p, log)
> #grid = CustTableGrid(p, log)
> b = wx.Button(p, -1, "Save Grid")
> b.SetDefault()
> self.Bind(wx.EVT_BUTTON, self.OnButton, b)
> b.Bind(wx.EVT_SET_FOCUS, self.OnButtonFocus)
> bs = wx.BoxSizer(wx.VERTICAL)
> bs.Add(grid, 1, wx.GROW|wx.ALL, 5)
> bs.Add(b)
> p.SetSizer(bs)
>
> def OnButton(self, evt):
> print "button selected"
> grid = WordGrid(self, log).savefile()
> #self.WordGrid.savefile(self)
>
> def OnButtonFocus(self, evt):
> print "button focus"
>
> #---
> #def main():
>
> def main(From_File, find_string):
> """This is the entire editor for .sco files..  It doesn't realy
> care if it is music or not.  Any file that you lay out with even rows
> and collums
> can be displayed  The first argument passed to main is the file to
> be used and the second if the string to be used as the command to set
> up the header of the grid.
> The sting you wish to use to identify the header should be placed
> last so it doesn't show up in the grid.
> """
>
> import sys
>
> app = wx.PySimpleApp()
> frame = TestFrame(None, sys.stdout)
> frame.Show(True)
> app.MainLoop()
> pass
>
> if __name__ == '__main__':
> import sys
> #try: 
> main(sys.argv[1], sys.argv[2])

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


Re: Observation on "Core Python Programming"

2006-10-29 Thread David Lees
John Coleman wrote:
> Greetings,
>My copy of the second edition of Chun's "Core Python Programming"
> just arrived from Amazon on Friday. What really jumped out at me is an
> interesting feature about how it sequences its topics, namely,
> (user-defined) functions are not introduced until chapter 11, fully 400
> pages into the book. This contrasts strongly with a traditional


Pages 48-50 is a section titled: 'Functions' and he gives both a top 
level description and example.  True he does not have a chapter devoted 
to functions still page 400, but he does give examples of usage along 
the way.

david lees

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


simple oop question (hopefully)

2006-10-29 Thread [EMAIL PROTECTED]
I am just trying to acess a function in wordgrid (savefile) to a button
that is defined in TestFrame.  I can't seem to make it work I either
get an error that my variable isn't global or it makes other
complaints.  thanks in advance..  sorry for the simple question..




import wx
import wx.grid as gridlib
import sys



#---

class WordGrid(gridlib.Grid):

def __init__(self, parent, log):
gridlib.Grid.__init__(self, parent, -1)
self.loadFile()

self.CreateGrid(len(self.rows), self.widestRow)

for r, row in enumerate(self.rows):
for c, col in enumerate(row):
self.SetCellValue(r, c, col)
self.SetColSize(c, 10*self.widestCol)

for c, label in enumerate(self.header):
self.SetColLabelValue(c, label)

def loadFile(self):
   #from_file
   infile = open(sys.argv[1], 'r') #The first argument passed in is
the file name
   foundHeader = False
   self.rows = []
   for line in infile:
   if sys.argv[2] in line: #look for the second argument and
make that the header
   #removefirst = line.split(' ')
   self.header = line.split()
   #foundHeader = 'true'
   continue # we don't want to process this line any
further
   else:
   self.rows.append(line.split())

   self.widestRow = max([len(r) for r in self.rows])
   self.widestCol = max([len(c) for c in [r for r in self.rows]])
def savefile(self):
outfile = open(sys.argv[1], 'w') #open the file defined in the
output line for writing
for row in self.rows:
outfile.write(row)

print('this is a test to see if I can Crash it')



class TestFrame(wx.Frame):
def __init__(self, parent, log):

wx.Frame.__init__(self, parent, -1, "Dex Tracker Sco Editor",
size=(640,480))
p = wx.Panel(self, -1, style=0)
grid = WordGrid(p, log)
#grid = CustTableGrid(p, log)
b = wx.Button(p, -1, "Save Grid")
b.SetDefault()
self.Bind(wx.EVT_BUTTON, self.OnButton, b)
b.Bind(wx.EVT_SET_FOCUS, self.OnButtonFocus)
bs = wx.BoxSizer(wx.VERTICAL)
bs.Add(grid, 1, wx.GROW|wx.ALL, 5)
bs.Add(b)
p.SetSizer(bs)

def OnButton(self, evt):
print "button selected"
grid = WordGrid(self, log).savefile()
#self.WordGrid.savefile(self)

def OnButtonFocus(self, evt):
print "button focus"

#---
#def main():

def main(From_File, find_string):
"""This is the entire editor for .sco files..  It doesn't realy
care if it is music or not.  Any file that you lay out with even rows
and collums
can be displayed  The first argument passed to main is the file to
be used and the second if the string to be used as the command to set
up the header of the grid.
The sting you wish to use to identify the header should be placed
last so it doesn't show up in the grid.
"""

import sys

app = wx.PySimpleApp()
frame = TestFrame(None, sys.stdout)
frame.Show(True)
app.MainLoop()
pass

if __name__ == '__main__':
import sys
#try: 
main(sys.argv[1], sys.argv[2])

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


Re: Reverse function python? How to use?

2006-10-29 Thread [EMAIL PROTECTED]
If you wanted to keep the original list intact, you could do...

[code]
foo = [x1,x2,x3,x4,x5]
bar = [math.sqrt(math.fabs(x))+5*math.pow(x,3) for x in foo]
bar_reversed = reversed(bar)
[/code]

On Oct 29, 4:23 pm, "Murali" <[EMAIL PROTECTED]> wrote:
> Something like this?
>
> [code]
> foo = [x1,x2,x3,x4,x5]
> bar = [math.sqrt(math.fabs(x))+5*math.pow(x,3) for x in foo]
> bar.reverse()
> print bar
> [/code]
>
> frankie_85 wrote:
> > Ok I'm really lost (I'm new to python) how to use the reverse function.
>
> > I made a little program which basically the a, b, c, d, e which I have
> > listed below and basically I want it th result to be printed reverse so
> > instead doing "print e, d, c, b, a", I'd like to use the reverse
> > function
>
> > Can someone give pointersguidelines / on how to do it?
>
> > [code]
> > a = str(math.sqrt(math.fabs(x1)) + 5*((math.pow(x1,3
> > b = str(math.sqrt(math.fabs(x2)) + 5*((math.pow(x2,3
> > c = str(math.sqrt(math.fabs(x3)) + 5*((math.pow(x3,3
> > d = str(math.sqrt(math.fabs(x4)) + 5*((math.pow(x4,3
> > e = str(math.sqrt(math.fabs(x5)) + 5*((math.pow(x5,3
> > [/code]
> 
> >  Thanks in advance

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


beginner's refcount questions

2006-10-29 Thread Jens Theisen
Hello,

python uses gc only where refcounts alone haven't yet done the
job. Thus, the following code

class Foo:
def __del__(self):
print "deled!"

def foo():
f = Foo()

foo()
print "done!"

prints

deled!
done!

and not the other way round.

In c++, this is a central technique used for all sorts of tasks,
whereas in garbage collected languages it's usually not available.

Is there a reason not to rely on this in Python? For example, are
there alternative Python implementations that behave differently?  Or
some other subtle problems?

And some other minor question: Is there a way to query the use count
of an object? This would be useful for debugging and testing.

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


Re: Observation on "Core Python Programming"

2006-10-29 Thread UrsusMaximus
I must say I find Wesley Chun's explanations to be most understandable.
I cant' exactly figure out why yet, but he has a way of explaining
something, like, say, decorators, that in minimal words elucidates for
me the intent behind why they are useful. That helps me understand how
they work. I just finished reading the chapter on Functions for the
book, I guess I was partly prompted by this thread on the newsgroup. it
was a *very* quick read, I could scan quickly but gain a better
understanding of the whole topic of functions in Python, including
inner functions, closures, decorators, continuations, and coroutines.
Talk about bang for the buck, that half hour to 45 minutes of reading
new chapter in Wesley Chun's new book was the best investment of time i
have made in quite a while.

I really like this book. I really, really, really like it.

Ron Stephens

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


Re: enumerate improvement proposal

2006-10-29 Thread James Stroud
Fredrik Lundh wrote:
> James Stroud wrote:
> 
>> The code is for an economist. She is insistent on starting with the 
>> first bin as 1.
> 
> 
> leaky abstractions in reverse, in other words?  that's not a good design 
> approach.
> 
> 
> 

Okay, I've googled "leaky abstractions" (as was probably your intended
affect with your silence), read the famous essay, and still
don't know what you mean and how it applies to what I have described.

Do you plan to justify your statement or emptily accuse people of violating
esoteric principles?

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Re: looping through two list simultenously

2006-10-29 Thread jim-on-linux
On Sunday 29 October 2006 15:28, CSUIDL PROGRAMMEr 
wrote:
> folks
> I have two lists
>
>  i am trying to loop thorough them
> simultenously.
>

Try something like this.

 for eachline in data1:
 print eachline
 for line in data::
 print line

You might also think about a while loop.

jim-on-linux

http://www.inqvista.com



> Here is the code i am using
>
> f1 = os.popen('ls  chatlog*.out')
> data1=f1.readlines()
> f1.close()
>
> data1=[x.strip() for x in data1]
> f1 = os.popen('ls  chatlog*.txt')
> data=f1.readlines()
> f1.close()
> for eachline in data1 and line in data:
>
> filename='/root/Desktop/project/'+ eachline
> print filename
> outfile=open(filename,'r')
> filename1='/root/Desktop/project/' + line
> print filename1
>
> I get the error that line is not defined.
> Traceback (most recent call last):
>   File "list.py", line 16, in ?
> for eachline in data1 and line in data:
> NameError: name 'line' is not defined
>
> Is there any efficient doing this
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lossless transformation of jpeg images

2006-10-29 Thread jim-on-linux
On Sunday 29 October 2006 15:17, Daniel Nogradi 
wrote:
> > Hi all,
> >
> > Last time I checked PIL was not able to apply
> > lossless transformations to jpeg images so
> > I've created Python bindings (or is it a
> > wrapper? I never knew the difference :)) for
> > the jpegtran utility of the Independent Jpeg
> > Group.


Why not use Tkinter for jpeg ??


jim-on-linux

http://www.inqvista.com




> >
> > The jpegtran utility is written in C and is
> > very efficient, fast and robust. It can
> > rotate, flip, transpose and transverse jpeg
> > images in a lossless way, see www.ijg.org for
> > more details.
> >
> > The bindings allow you to use all jpegtran
> > features from Python.
> >
> > Downloads are here:
> > http://ebiznisz.hu/python-jpegtran/
> >
> > Any feedback is very welcome, especially if
> > you are able to compile it on non-standard
> > platforms. It has been tested on Linux and
> > Python 2.3.
> >
> > Usage example:
> >
> > import jpegtran
> >
> > transformer = jpegtran.transformer( )
> >
> > transformer.rotate( 90, 'pic.jpg',
> > 'pic_rotated.jpg' ) transformer.flip(
> > 'horizontal', 'pic.jpg', 'pic_flipped.jpg' )
> > transformer.transpose( 'pic.jpg',
> > 'pic_transposed.jpg' )
> > transformer.transverse( 'pic.jpg',
> > 'pic_transversed.jpg' ) transformer.gray(
> > 'pic.jpg', 'pic_gray.jpg' )
>
> Oh, I forgot to mention that this is a very
> preliminary release, there is no support for
> distutils or any other intelligent packaging
> tool, it uses 'make' so probably will only work
> on Unix flavours. Although it should compile on
> Windows as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: enumerate improvement proposal

2006-10-29 Thread Ben Finney
Ben Finney <[EMAIL PROTECTED]> writes:

> >>> print enumerate("ABCDE")
> 
> >>> print list(enumerate("ABCDE"))
> [(0, 'A'), (1, 'B'), (2, 'C'), (3, 'D'), (4, 'E')]
>
> >> def obstinate_economist_enumerate(items):
> ... seq = [(i+1, x) for (i, x) in enumerate(items)]
> ... return iter(seq)
> ...
> >>> print obstinate_economist_enumerate("ABCDE")
> 
> >>> print list(obstinate_economist_enumerate("ABCDE"))
> [(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D'), (5, 'E')]

An improvement: using a generator so as not to unnecessarily create an
intermediate list from the initial enumerator:

>>> def obstinate_economist_enumerate(items):
... enum_iter = iter((i+1, x) for (i, x) in enumerate(items))
... return enum_iter
...
>>> print obstinate_economist_enumerate("ABCDE")

>>> print list(obstinate_economist_enumerate("ABCDE"))
[(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D'), (5, 'E')]

-- 
 \  "If sharing a thing in no way diminishes it, it is not rightly |
  `\   owned if it is not shared."  -- Saint Augustine |
_o__)  |
Ben Finney

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


Re: enumerate improvement proposal

2006-10-29 Thread Ben Finney
James Stroud <[EMAIL PROTECTED]> writes:

> Fredrik Lundh wrote:
> > why is it this function's job to add an offset to the actual
> > sequence index?
>
> The code is for an economist. She is insistent on starting with the
> first bin as 1.

Note that 'enumerate' is actually a built-in type, and 'enumerate()'
is the constructor returning a new object of that type.

A special case isn't special enough to change the built-in type.

>>> print enumerate("ABCDE")

>>> print list(enumerate("ABCDE"))
[(0, 'A'), (1, 'B'), (2, 'C'), (3, 'D'), (4, 'E')]

>> def obstinate_economist_enumerate(items):
... seq = [(i+1, x) for (i, x) in enumerate(items)]
... return iter(seq)
...
>>> print obstinate_economist_enumerate("ABCDE")

>>> print list(obstinate_economist_enumerate("ABCDE"))
[(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D'), (5, 'E')]

This doesn't produce an 'enumerate' object; if you really want that,
you could subclass 'enumerate', but it seems the above function does
what you want.

-- 
 \"I installed a skylight in my apartment. The people who live |
  `\  above me are furious!"  -- Steven Wright |
_o__)  |
Ben Finney

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


Re: Event driven server that wastes CPU when threaded doesn't

2006-10-29 Thread Nick Vatamaniuc
Good point. enterprise.adbapi is designed to solve the problem. The
other interface was deprecated.

Thanks,
Nick Vatamaniuc


Jean-Paul Calderone wrote:
> On 29 Oct 2006 13:13:32 -0800, Nick Vatamaniuc <[EMAIL PROTECTED]> wrote:
> >Snor wrote:
> >> I'm attempting to create a lobby & game server for a multiplayer game,
> >> and have hit a problem early on with the server design. I am stuck
> >> between using a threaded server, and using an event driven server. I've
> >> been told time and time again that I should use an event driven server
> >> design (that is, use twisted).
> >>
> >> There is a lot of interaction between the clients and they would often
> >> need to write to the same list of values, which of course becomes a
> >> problem with a threaded server - so event driven solves that problem,
> >> and I assumed it would solve all my problems. However some requests
> >> from clients would require that the server goes on to query a mySQL
> >> server (separate machine from the server). As this occurs, there is a
> >> small amount of lag while the communication with the mySQL server takes
> >> place, and there could be another 100 clients waiting to make a request
> >> at this point, meanwhile the server is idling while waiting for a
> >> response from the mySQL server - obviously not a good server model.
> >>
> >> I will want the server to support as many users as is possible on any
> >> given machine - and so wasted CPU cycles is something I am trying to
> >> avoid.
> >>
> >> Is the only solution to use a threaded server to let my clients make
> >> their requests and receive a response in the fastest possible time?
> >Snor,
> >
> >The simplest solution is to change your system and put the DB on the
> >same machine thus greatly reducing the time it takes for each DB query
> >to complete (avoid the TCP stack completely).  This way you might not
> >have to change your application logic.
> >
> >If that is not an option, then you are faced with a problem of
> >connecting a threaded programming model with an event based model
> >(twisted and and such). So your job is to interface the two. In other
> >words make the event based model see the threaded DB access as event
> >based. And the DB driver to see the event-based system as threaded. So
> >in your event dispatcher you could add events like db_request_finished
> >then when a connection is requested to the DB, a callback will be
> >supplied. The connection will take place in its own thread, then when
> >it is finished it will put the db_request_finished and the respective
> >callback function on the event queue. I am not sure how to integrate
> >that into the Twisted event dispatcher... perhaps this class is the
> >answer?:
> >http://twistedmatrix.com/documents/current/api/twisted.python.dispatch.EventDispatcher.html
>
> Note, however:
>
> >>> from twisted.python import dispatch
> __main__:1: DeprecationWarning: Create your own event dispatching mechanism, 
> twisted.python.dispatch will soon be no more.
>
> Take a look at 
> .
> 
> Jean-Paul

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


Re: Event driven server that wastes CPU when threaded doesn't

2006-10-29 Thread Nick Vatamaniuc
Try the --skip-networking option for mysqld

Paul Rubin wrote:
> "Nick Vatamaniuc" <[EMAIL PROTECTED]> writes:
> > The simplest solution is to change your system and put the DB on the
> > same machine thus greatly reducing the time it takes for each DB query
> > to complete (avoid the TCP stack completely).
>
> Since when do any db's let you avoid the TCP stack, even on the same
> machine?

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


Re: Reverse function python? How to use?

2006-10-29 Thread Ben Finney
"frankie_85" <[EMAIL PROTECTED]> writes:

> I made a little program which basically the a, b, c, d, e which I
> have listed below and basically I want it th result to be printed
> reverse so instead doing "print e, d, c, b, a", I'd like to use the
> reverse function

As was pointed out before, your assignment requires you to use a
list. You're using completely distinct names instead of storing these
sequences in a container. Read your course notes again, paying
attention to "containers" and especially "lists".

-- 
 \ "For of those to whom much is given, much is required."  -- |
  `\   John F. Kennedy |
_o__)  |
Ben Finney

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


Re: looping through two list simultenously

2006-10-29 Thread [EMAIL PROTECTED]

CSUIDL PROGRAMMEr wrote:
> folks
> I have two lists
>
>  i am trying to loop thorough them simultenously.
>
> Here is the code i am using
>
> f1 = os.popen('ls  chatlog*.out')
You can replace this by
py> import glob
py> f1 = glob.glob('chatlog*.out')
it will return a list of filenames in f1, so you can skip next two
lines in your code
> data1=f1.readlines()
> f1.close()
>
If you use the glob this step can be skipped too, as glob returns the
filenames, without any whitespace added
> data1=[x.strip() for x in data1]

> f1 = os.popen('ls  chatlog*.txt')
> data=f1.readlines()
> f1.close()
> for eachline in data1 and line in data:
>
> filename='/root/Desktop/project/'+ eachline
> print filename
> outfile=open(filename,'r')
> filename1='/root/Desktop/project/' + line
> print filename1
>
now you do the zip as suggested by the other people, but be aware that
it only returns the tuples as long as the shortest list is, so it might
be a good idea to add a test on equality of the number of .log and .txt
files
py> import glob
py> f1 = glob.glob('chatlog*.out')
py> f2 = glob.glob('chatlog*.txt')
py> if len(f1) != len(f2):
py> print "number of .out files doesn't match number of .txt files"
py> f3 = zip(f1, f2)
now f3 will be somethine like [('chatlog1.out',
'chatlog1.txt'),('chatlog2.out', 'chatlog2.txt')], then you can
continue with your iteration loops


> I get the error that line is not defined.
> Traceback (most recent call last):
>   File "list.py", line 16, in ?
> for eachline in data1 and line in data:
> NameError: name 'line' is not defined
> 
> Is there any efficient doing this

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


Re: Event driven server that wastes CPU when threaded doesn't

2006-10-29 Thread Felipe Almeida Lessa
29 Oct 2006 14:18:02 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid>:
> "Nick Vatamaniuc" <[EMAIL PROTECTED]> writes:
> > The simplest solution is to change your system and put the DB on the
> > same machine thus greatly reducing the time it takes for each DB query
> > to complete (avoid the TCP stack completely).
>
> Since when do any db's let you avoid the TCP stack, even on the same
> machine?

Since there are Unix sockets? A quick google:

http://dev.mysql.com/doc/refman/5.0/en/multiple-unix-servers.html
http://archives.postgresql.org/pgsql-hackers/1997-10/msg00568.php


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


Re: Observation on "Core Python Programming"

2006-10-29 Thread Nick Vatamaniuc
...Skimmed through the previous edition.

I don't normally read programming books -- just use the chapters that I
need when I need them, unless of course there is a clever plot twist
coming up ahead (for ex.:  "Next: The revenge of lambdas. Will they
stay or will they go?"  ;-)

Why? Have you read it from beginning  to end. What did you think about
functions being introduced later than files and exceptions?

-Nick V.

Fredrik Lundh wrote:
> Nick Vatamaniuc wrote:
>
> > I would consider that an omission. Functions are very important in
> > Python. I think the user/reader should see the _def_ and _class_
> > statement fairly soon in the introduction.  The name of the book is
> > thus somewhat misleading, because functions are at the "core" of
> > Python.
> 
> have you read the book?
> 
> 

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


Re: Event driven server that wastes CPU when threaded doesn't

2006-10-29 Thread Paul Rubin
"Nick Vatamaniuc" <[EMAIL PROTECTED]> writes:
> The simplest solution is to change your system and put the DB on the
> same machine thus greatly reducing the time it takes for each DB query
> to complete (avoid the TCP stack completely).

Since when do any db's let you avoid the TCP stack, even on the same
machine?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Event driven server that wastes CPU when threaded doesn't

2006-10-29 Thread Carl Banks
Snor wrote:
> As this occurs, there is a
> small amount of lag while the communication with the mySQL server takes
> place, and there could be another 100 clients waiting to make a request
> at this point, meanwhile the server is idling while waiting for a
> response from the mySQL server - obviously not a good server model.

Isn't it possible to use asynchronous communication to talk to the SQL
server as well?

I don't know a lot about Twisted, but I'd think you could create some
sort of connection with the SQL server and have TwistedMatrix manage
and react to the SQL server events the same as it does with your
clients.  Being that SQL is so common, I bet someone's already written
higher-level protocol handlers.


Carl Banks

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


Re: Observation on "Core Python Programming"

2006-10-29 Thread Nick Vatamaniuc
I meant "omitted" not as complete omission but as not being there
sooner...

John Coleman wrote:
> A is not ommitted from DBECAFG - it just appears in a non-standard
> order. If the book simply ommitted functions then it would be a
> shocking ommission. As it is, it is just a curious way of sequencing
> topics. Functions are in chapter 11 out of 23 chapters - sounds like
> the "core" of the book to me.
>
> Chun does emphasize the first-class status of functions in Python -
> something which is fairly important to me since I have dabbled on and
> off with functional programming the last few years (mostly SML) and am
> interested in seeing the extend to which Python is genuinely
> "multi-paradigm" - able to blend the functional and imperative (and OO)
> paradigms together.
>
> -John Coleman
>
> Nick Vatamaniuc wrote:
> > I would consider that an omission. Functions are very important in
> > Python. I think the user/reader should see the _def_ and _class_
> > statement fairly soon in the introduction.  The name of the book is
> > thus somewhat misleading, because functions are at the "core" of
> > Python.
> >
> > Functions should be right there with the integers, strings, files,
> > lists and dictionaries. Another important point to stress, in my
> > opinion,  is that functions are first-class objects. In other words
> > functions can be passes around just like strings and numbers!
> >
> > -Nick Vatamaniuc
> >
> >
> > John Coleman wrote:
> > > Greetings,
> > >My copy of the second edition of Chun's "Core Python Programming"
> > > just arrived from Amazon on Friday. What really jumped out at me is an
> > > interesting feature about how it sequences its topics, namely,
> > > (user-defined) functions are not introduced until chapter 11, fully 400
> > > pages into the book. This contrasts strongly with a traditional
> > > "Introduction to language X" book which has a chapter sequence roughy
> > > like:
> > >
> > > Chapter 1) Intro - Hello World
> > > Chapter 2) Variables
> > > Chapter 3) If, if-else
> > > Chapter 4) Loops
> > > Chapter 5) Functions and/or subroutines
> > >
> > > The exact details vary from book to book and language to language of
> > > course, but usually the above topics are covered in the first 100-150
> > > pages since it is hard to do anything interesting until all of these
> > > tools are under your belt. Chun's book by contrast is able, on the
> > > strength of Python's built-in functions, to cover a fair amount of
> > > relatively interesting things (dictionaries, file IO, exception
> > > handling, etc.) before introducing user-defined functions.
> > >
> > > I don't want to read too much into this, but the mere fact that it is
> > > possible to write a Python book in this fashion seems to confirm the
> > > "batteries are included" philosophy of Python. Perhaps there is less
> > > need to learn how to roll your own batteries as soon as possible.
> > > 
> > > -John Coleman

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


Re: Event driven server that wastes CPU when threaded doesn't

2006-10-29 Thread Jean-Paul Calderone
On 29 Oct 2006 13:13:32 -0800, Nick Vatamaniuc <[EMAIL PROTECTED]> wrote:
>Snor wrote:
>> I'm attempting to create a lobby & game server for a multiplayer game,
>> and have hit a problem early on with the server design. I am stuck
>> between using a threaded server, and using an event driven server. I've
>> been told time and time again that I should use an event driven server
>> design (that is, use twisted).
>>
>> There is a lot of interaction between the clients and they would often
>> need to write to the same list of values, which of course becomes a
>> problem with a threaded server - so event driven solves that problem,
>> and I assumed it would solve all my problems. However some requests
>> from clients would require that the server goes on to query a mySQL
>> server (separate machine from the server). As this occurs, there is a
>> small amount of lag while the communication with the mySQL server takes
>> place, and there could be another 100 clients waiting to make a request
>> at this point, meanwhile the server is idling while waiting for a
>> response from the mySQL server - obviously not a good server model.
>>
>> I will want the server to support as many users as is possible on any
>> given machine - and so wasted CPU cycles is something I am trying to
>> avoid.
>>
>> Is the only solution to use a threaded server to let my clients make
>> their requests and receive a response in the fastest possible time?
>Snor,
>
>The simplest solution is to change your system and put the DB on the
>same machine thus greatly reducing the time it takes for each DB query
>to complete (avoid the TCP stack completely).  This way you might not
>have to change your application logic.
>
>If that is not an option, then you are faced with a problem of
>connecting a threaded programming model with an event based model
>(twisted and and such). So your job is to interface the two. In other
>words make the event based model see the threaded DB access as event
>based. And the DB driver to see the event-based system as threaded. So
>in your event dispatcher you could add events like db_request_finished
>then when a connection is requested to the DB, a callback will be
>supplied. The connection will take place in its own thread, then when
>it is finished it will put the db_request_finished and the respective
>callback function on the event queue. I am not sure how to integrate
>that into the Twisted event dispatcher... perhaps this class is the
>answer?:
>http://twistedmatrix.com/documents/current/api/twisted.python.dispatch.EventDispatcher.html

Note, however:

>>> from twisted.python import dispatch
__main__:1: DeprecationWarning: Create your own event dispatching mechanism, 
twisted.python.dispatch will soon be no more.

Take a look at 
.

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


Re: Get pexpect to work

2006-10-29 Thread drake

Jurian Sluiman wrote:
> Ok, somebody helped my and found with "help(child.sendline)" that the
> number (7) is the number of characters from my password.
>
> Still there doesn't seem to be that anything strange is happening. With
> the logfile printed out, I found that child.expect places a 0 behind the
> next rule. Is this always what's happening? And is that 0 causing all my
> troubles?
>
> I'm a newbie with python, so I don't know much about it. This is (again)
> the output, but with a sys.stdout line between it:
>
> >>> child = pexpect.spawn("vpnc-connect tudelft\ nopass.conf")
> >>> child.logfile = sys.stdout
> >>> child.expect(".* password .*: ")
> Enter password for [EMAIL PROTECTED]: 0
> >>> child.sendline("[my_password]")
> 7
>
> Any help is really appreciated! I can search on the Internet, but with no
> clue to search for and which keywords to use, all results don't help me.
>
> Thanks,
> Jurian
>
> PS. Sorry for my bad English, I hope you can understand it.

I use a slightly different approach for starting vpnc-connect if that
will help:
1. have your script create a temporary vpnc configuration file
(including your password):
f1=open('/tmp/vpn.conf', 'w')
f1.write('IPSec gateway ' + vpnAddress + '\n')
f1.write('IPSec ID ' + vpnGroup + '\n')etc.
2. create a temporary results file, such as f2 =
open('/tmp/vpncResults.txt', 'w')
3. start the vpn client: p = subprocess.Popen('/usr/sbin/vpnc-connect
/tmp/vpn.conf', shell=True, stdout=f2).stdout
4. poll the results file to determine whether or not the connection
succeeded
5. delete the temporary configuration file

Creating a temporary configuration file keeps my password out of clear
text other than for the few seconds the configuration file lives on my
hard drive. In reality, my program runs within the Twisted event-driven
framework, so I just create a deferred object when invoking
vpnc-connect and wait for the callback to see if the connection was
successful, but an earlier incarnation of my program worked with the
above code.

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


Re: Reverse function python? How to use?

2006-10-29 Thread Murali
Something like this?

[code]
foo = [x1,x2,x3,x4,x5]
bar = [math.sqrt(math.fabs(x))+5*math.pow(x,3) for x in foo]
bar.reverse()
print bar
[/code]

frankie_85 wrote:
> Ok I'm really lost (I'm new to python) how to use the reverse function.
>
>
> I made a little program which basically the a, b, c, d, e which I have
> listed below and basically I want it th result to be printed reverse so
> instead doing "print e, d, c, b, a", I'd like to use the reverse
> function
>
> Can someone give pointersguidelines / on how to do it?
>
> [code]
> a = str(math.sqrt(math.fabs(x1)) + 5*((math.pow(x1,3
> b = str(math.sqrt(math.fabs(x2)) + 5*((math.pow(x2,3
> c = str(math.sqrt(math.fabs(x3)) + 5*((math.pow(x3,3
> d = str(math.sqrt(math.fabs(x4)) + 5*((math.pow(x4,3
> e = str(math.sqrt(math.fabs(x5)) + 5*((math.pow(x5,3
> [/code]
> 
>  Thanks in advance

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


Re: Observation on "Core Python Programming"

2006-10-29 Thread John Coleman
A is not ommitted from DBECAFG - it just appears in a non-standard
order. If the book simply ommitted functions then it would be a
shocking ommission. As it is, it is just a curious way of sequencing
topics. Functions are in chapter 11 out of 23 chapters - sounds like
the "core" of the book to me.

Chun does emphasize the first-class status of functions in Python -
something which is fairly important to me since I have dabbled on and
off with functional programming the last few years (mostly SML) and am
interested in seeing the extend to which Python is genuinely
"multi-paradigm" - able to blend the functional and imperative (and OO)
paradigms together.

-John Coleman

Nick Vatamaniuc wrote:
> I would consider that an omission. Functions are very important in
> Python. I think the user/reader should see the _def_ and _class_
> statement fairly soon in the introduction.  The name of the book is
> thus somewhat misleading, because functions are at the "core" of
> Python.
>
> Functions should be right there with the integers, strings, files,
> lists and dictionaries. Another important point to stress, in my
> opinion,  is that functions are first-class objects. In other words
> functions can be passes around just like strings and numbers!
>
> -Nick Vatamaniuc
>
>
> John Coleman wrote:
> > Greetings,
> >My copy of the second edition of Chun's "Core Python Programming"
> > just arrived from Amazon on Friday. What really jumped out at me is an
> > interesting feature about how it sequences its topics, namely,
> > (user-defined) functions are not introduced until chapter 11, fully 400
> > pages into the book. This contrasts strongly with a traditional
> > "Introduction to language X" book which has a chapter sequence roughy
> > like:
> >
> > Chapter 1) Intro - Hello World
> > Chapter 2) Variables
> > Chapter 3) If, if-else
> > Chapter 4) Loops
> > Chapter 5) Functions and/or subroutines
> >
> > The exact details vary from book to book and language to language of
> > course, but usually the above topics are covered in the first 100-150
> > pages since it is hard to do anything interesting until all of these
> > tools are under your belt. Chun's book by contrast is able, on the
> > strength of Python's built-in functions, to cover a fair amount of
> > relatively interesting things (dictionaries, file IO, exception
> > handling, etc.) before introducing user-defined functions.
> >
> > I don't want to read too much into this, but the mere fact that it is
> > possible to write a Python book in this fashion seems to confirm the
> > "batteries are included" philosophy of Python. Perhaps there is less
> > need to learn how to roll your own batteries as soon as possible.
> > 
> > -John Coleman

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


Re: Event driven server that wastes CPU when threaded doesn't

2006-10-29 Thread Nick Vatamaniuc
Snor,

The simplest solution is to change your system and put the DB on the
same machine thus greatly reducing the time it takes for each DB query
to complete (avoid the TCP stack completely).  This way you might not
have to change your application logic.

If that is not an option, then you are faced with a problem of
connecting a threaded programming model with an event based model
(twisted and and such). So your job is to interface the two. In other
words make the event based model see the threaded DB access as event
based. And the DB driver to see the event-based system as threaded. So
in your event dispatcher you could add events like db_request_finished
then when a connection is requested to the DB, a callback will be
supplied. The connection will take place in its own thread, then when
it is finished it will put the db_request_finished and the respective
callback function on the event queue. I am not sure how to integrate
that into the Twisted event dispatcher... perhaps this class is the
answer?:
http://twistedmatrix.com/documents/current/api/twisted.python.dispatch.EventDispatcher.html

Hope this helps,
Nick V.



Snor wrote:
> I'm attempting to create a lobby & game server for a multiplayer game,
> and have hit a problem early on with the server design. I am stuck
> between using a threaded server, and using an event driven server. I've
> been told time and time again that I should use an event driven server
> design (that is, use twisted).
>
> There is a lot of interaction between the clients and they would often
> need to write to the same list of values, which of course becomes a
> problem with a threaded server - so event driven solves that problem,
> and I assumed it would solve all my problems. However some requests
> from clients would require that the server goes on to query a mySQL
> server (separate machine from the server). As this occurs, there is a
> small amount of lag while the communication with the mySQL server takes
> place, and there could be another 100 clients waiting to make a request
> at this point, meanwhile the server is idling while waiting for a
> response from the mySQL server - obviously not a good server model.
>
> I will want the server to support as many users as is possible on any
> given machine - and so wasted CPU cycles is something I am trying to
> avoid.
>
> Is the only solution to use a threaded server to let my clients make
> their requests and receive a response in the fastest possible time?

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


Re: Get pexpect to work

2006-10-29 Thread Jurian Sluiman
Ok, somebody helped my and found with "help(child.sendline)" that the
number (7) is the number of characters from my password.

Still there doesn't seem to be that anything strange is happening. With
the logfile printed out, I found that child.expect places a 0 behind the
next rule. Is this always what's happening? And is that 0 causing all my
troubles?

I'm a newbie with python, so I don't know much about it. This is (again)
the output, but with a sys.stdout line between it:

>>> child = pexpect.spawn("vpnc-connect tudelft\ nopass.conf")
>>> child.logfile = sys.stdout
>>> child.expect(".* password .*: ")
Enter password for [EMAIL PROTECTED]: 0
>>> child.sendline("[my_password]")
7

Any help is really appreciated! I can search on the Internet, but with no
clue to search for and which keywords to use, all results don't help me.

Thanks,
Jurian

PS. Sorry for my bad English, I hope you can understand it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "from module import *" and modifying module's top-level vars

2006-10-29 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> Hi everyone,
> 
> I define some vars and functions in a "support" module which gets
> called from my
> main app module. Using Python 2.5.
> 
> I import all symbols in the support module at the top of the main
> module through:
> 
> from support import *
> 
> Is there a way for me to modify a top-level ("global"?) variable
> defined in module
> support from the code in the main module and still have those changes
> visible to
> code in the support module?

No. The from foo import * will create local bindings of the 
module-globals in the importing module, and there is no implicit link to 
the module's names.

This is the main reason why the "from foo import *"-form is frowned 
upon, and you should refrain from using it.

Use e.g.

import support as s

instead, to get a shorter name for referencing the support module.

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


Re: Observation on "Core Python Programming"

2006-10-29 Thread Fredrik Lundh
Nick Vatamaniuc wrote:

> I would consider that an omission. Functions are very important in
> Python. I think the user/reader should see the _def_ and _class_
> statement fairly soon in the introduction.  The name of the book is
> thus somewhat misleading, because functions are at the "core" of
> Python.

have you read the book?



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


Re: looping through two list simultenously

2006-10-29 Thread Daniel Nogradi
> folks
> I have two lists
>
>  i am trying to loop thorough them simultenously.
>
> Here is the code i am using

[...]

> Is there any efficient doing this
>

Try the zip function:

>>> list1 = [ 'a', 'b', 'c' ]
>>> list2 = [ 'A', 'B', 'C' ]
>>> for i, j in zip( list1, list2 ):
... print i, j
...
a A
b B
c C
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping through two list simultenously

2006-10-29 Thread Michael S
What if you do it in 2 separate threads?

--- CSUIDL PROGRAMMEr <[EMAIL PROTECTED]> wrote:

> folks
> I have two lists
> 
>  i am trying to loop thorough them simultenously.
> 
> Here is the code i am using
> 
> f1 = os.popen('ls  chatlog*.out')
> data1=f1.readlines()
> f1.close()
> 
> data1=[x.strip() for x in data1]
> f1 = os.popen('ls  chatlog*.txt')
> data=f1.readlines()
> f1.close()
> for eachline in data1 and line in data:
> 
> filename='/root/Desktop/project/'+ eachline
> print filename
> outfile=open(filename,'r')
> filename1='/root/Desktop/project/' + line
> print filename1
> 
> I get the error that line is not defined.
> Traceback (most recent call last):
>   File "list.py", line 16, in ?
> for eachline in data1 and line in data:
> NameError: name 'line' is not defined
> 
> Is there any efficient doing this
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

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


Re: looping through two list simultenously

2006-10-29 Thread Björn Lindström
"CSUIDL PROGRAMMEr" <[EMAIL PROTECTED]>:

> folks I have two lists
>
>  i am trying to loop thorough them simultenously.
>
> Is there any efficient doing this

Try the built-in function zip.

>>> zip(['a', 'b', 'c'], [1, 2, 3])
[('a', 1), ('b', 2), ('c', 3)]

-- 
Björn Lindström <[EMAIL PROTECTED]>
Student of computational linguistics, Uppsala University, Sweden
-- 
http://mail.python.org/mailman/listinfo/python-list

looping through two list simultenously

2006-10-29 Thread CSUIDL PROGRAMMEr
folks
I have two lists

 i am trying to loop thorough them simultenously.

Here is the code i am using

f1 = os.popen('ls  chatlog*.out')
data1=f1.readlines()
f1.close()

data1=[x.strip() for x in data1]
f1 = os.popen('ls  chatlog*.txt')
data=f1.readlines()
f1.close()
for eachline in data1 and line in data:

filename='/root/Desktop/project/'+ eachline
print filename
outfile=open(filename,'r')
filename1='/root/Desktop/project/' + line
print filename1

I get the error that line is not defined.
Traceback (most recent call last):
  File "list.py", line 16, in ?
for eachline in data1 and line in data:
NameError: name 'line' is not defined

Is there any efficient doing this

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


"from module import *" and modifying module's top-level vars

2006-10-29 Thread lemke_juergen
Hi everyone,

I define some vars and functions in a "support" module which gets
called from my
main app module. Using Python 2.5.

I import all symbols in the support module at the top of the main
module through:

from support import *

Is there a way for me to modify a top-level ("global"?) variable
defined in module
support from the code in the main module and still have those changes
visible to
code in the support module?

Consider the following example:

# support.py

globvar = "old"

def fun():
print "fun(): globvar==" + globvar

# main.py

from support import *
global globvar # had hoped this would do the trick (as it does when
placed inside a function call)
glob = "new"

print "top level(): glob==" +glob

fun() # defined inside support

Calling main.py outputs

top level(): glob==new
fun(): glob==old

How can I get the assignment to globvar performed inside module main.py
to be
felt by the code in support.py?

Thanks in advance!

Best

Juergen Lemke

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


Re: lossless transformation of jpeg images

2006-10-29 Thread Daniel Nogradi
> Hi all,
>
> Last time I checked PIL was not able to apply lossless transformations
> to jpeg images so I've created Python bindings (or is it a wrapper? I
> never knew the difference :)) for the jpegtran utility of the
> Independent Jpeg Group.
>
> The jpegtran utility is written in C and is very efficient, fast and
> robust. It can rotate, flip, transpose and transverse jpeg images in a
> lossless way, see www.ijg.org for more details.
>
> The bindings allow you to use all jpegtran features from Python.
>
> Downloads are here: http://ebiznisz.hu/python-jpegtran/
>
> Any feedback is very welcome, especially if you are able to compile it
> on non-standard platforms. It has been tested on Linux and Python 2.3.
>
> Usage example:
>
> import jpegtran
>
> transformer = jpegtran.transformer( )
>
> transformer.rotate( 90, 'pic.jpg', 'pic_rotated.jpg' )
> transformer.flip( 'horizontal', 'pic.jpg', 'pic_flipped.jpg' )
> transformer.transpose( 'pic.jpg', 'pic_transposed.jpg' )
> transformer.transverse( 'pic.jpg', 'pic_transversed.jpg' )
> transformer.gray( 'pic.jpg', 'pic_gray.jpg' )


Oh, I forgot to mention that this is a very preliminary release, there
is no support for distutils or any other intelligent packaging tool,
it uses 'make' so probably will only work on Unix flavours. Although
it should compile on Windows as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Observation on "Core Python Programming"

2006-10-29 Thread Nick Vatamaniuc
I would consider that an omission. Functions are very important in
Python. I think the user/reader should see the _def_ and _class_
statement fairly soon in the introduction.  The name of the book is
thus somewhat misleading, because functions are at the "core" of
Python.

Functions should be right there with the integers, strings, files,
lists and dictionaries. Another important point to stress, in my
opinion,  is that functions are first-class objects. In other words
functions can be passes around just like strings and numbers!

-Nick Vatamaniuc


John Coleman wrote:
> Greetings,
>My copy of the second edition of Chun's "Core Python Programming"
> just arrived from Amazon on Friday. What really jumped out at me is an
> interesting feature about how it sequences its topics, namely,
> (user-defined) functions are not introduced until chapter 11, fully 400
> pages into the book. This contrasts strongly with a traditional
> "Introduction to language X" book which has a chapter sequence roughy
> like:
>
> Chapter 1) Intro - Hello World
> Chapter 2) Variables
> Chapter 3) If, if-else
> Chapter 4) Loops
> Chapter 5) Functions and/or subroutines
>
> The exact details vary from book to book and language to language of
> course, but usually the above topics are covered in the first 100-150
> pages since it is hard to do anything interesting until all of these
> tools are under your belt. Chun's book by contrast is able, on the
> strength of Python's built-in functions, to cover a fair amount of
> relatively interesting things (dictionaries, file IO, exception
> handling, etc.) before introducing user-defined functions.
>
> I don't want to read too much into this, but the mere fact that it is
> possible to write a Python book in this fashion seems to confirm the
> "batteries are included" philosophy of Python. Perhaps there is less
> need to learn how to roll your own batteries as soon as possible.
> 
> -John Coleman

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


Re: Reverse function python? How to use?

2006-10-29 Thread Nick Vatamaniuc
Use the list's reverse() function. The only thing to keep in mind is
that it will reverse in-place.
Here is an example:

In [1]: l=[1,2,3]

In [2]: l.reverse()

In [3]: l
Out[3]: [3, 2, 1]

So you could accumulate your results in a list then apply reverse() on
it.

Hope this helps,
Nick Vatamaniuc


frankie_85 wrote:
> Ok I'm really lost (I'm new to python) how to use the reverse function.
>
>
> I made a little program which basically the a, b, c, d, e which I have
> listed below and basically I want it th result to be printed reverse so
> instead doing "print e, d, c, b, a", I'd like to use the reverse
> function
>
> Can someone give pointersguidelines / on how to do it?
>
> [code]
> a = str(math.sqrt(math.fabs(x1)) + 5*((math.pow(x1,3
> b = str(math.sqrt(math.fabs(x2)) + 5*((math.pow(x2,3
> c = str(math.sqrt(math.fabs(x3)) + 5*((math.pow(x3,3
> d = str(math.sqrt(math.fabs(x4)) + 5*((math.pow(x4,3
> e = str(math.sqrt(math.fabs(x5)) + 5*((math.pow(x5,3
> [/code]
> 
>  Thanks in advance

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


Re: logo design - BZZZT! OT!

2006-10-29 Thread Gerard Flanagan

John Bokma wrote:
> Xah Lee is a well-known spammer, almost all his messages contain at least
> one link to his site in the body.
>
> Somehow this time he limited his post to 3 groups instead of the usual 5.
> Maybe talking with the right people does work. It did with Dreamhost. And
> I am sure his current hosting provider is listening ;-)
> 

 Charybdis...

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


Re: question about True values

2006-10-29 Thread Carl Banks
Steven D'Aprano wrote:
> It isn't often that I make an appeal to authority, but this is one of
> them. No offense, but when it comes to language design its a brave or
> foolish programmer who bucks the language idioms that Guido chose.

Well, it's pretty clear you consider some abstact notion of unity of
style more important than practical considerations of how your data is
used.

In that case you might as well just go with what the authority tells
you to.

(And hope that your users don't do much numerical stuff.)


Carl Banks

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


Reverse function python? How to use?

2006-10-29 Thread frankie_85
Ok I'm really lost (I'm new to python) how to use the reverse function.


I made a little program which basically the a, b, c, d, e which I have
listed below and basically I want it th result to be printed reverse so
instead doing "print e, d, c, b, a", I'd like to use the reverse
function

Can someone give pointersguidelines / on how to do it?

[code]
a = str(math.sqrt(math.fabs(x1)) + 5*((math.pow(x1,3
b = str(math.sqrt(math.fabs(x2)) + 5*((math.pow(x2,3
c = str(math.sqrt(math.fabs(x3)) + 5*((math.pow(x3,3
d = str(math.sqrt(math.fabs(x4)) + 5*((math.pow(x4,3
e = str(math.sqrt(math.fabs(x5)) + 5*((math.pow(x5,3
[/code]

 Thanks in advance

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


Re: logo design - BZZZT! OT!

2006-10-29 Thread John Bokma
"Paul McGuire" <[EMAIL PROTECTED]> wrote:
 
> Does the "power-that-be of lispers" spend much time on c.l.py?  Even
> though Python is mentioned in passing in this post, it really doesn't
> need to be cross-posted here.

Xah Lee is a well-known spammer, almost all his messages contain at least 
one link to his site in the body.

Somehow this time he limited his post to 3 groups instead of the usual 5. 
Maybe talking with the right people does work. It did with Dreamhost. And 
I am sure his current hosting provider is listening ;-)

-- 
John   MexIT: http://johnbokma.com/mexit/
   personal page:   http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
-- 
http://mail.python.org/mailman/listinfo/python-list


lossless transformation of jpeg images

2006-10-29 Thread Daniel Nogradi
Hi all,

Last time I checked PIL was not able to apply lossless transformations
to jpeg images so I've created Python bindings (or is it a wrapper? I
never knew the difference :)) for the jpegtran utility of the
Independent Jpeg Group.

The jpegtran utility is written in C and is very efficient, fast and
robust. It can rotate, flip, transpose and transverse jpeg images in a
lossless way, see www.ijg.org for more details.

The bindings allow you to use all jpegtran features from Python.

Downloads are here: http://ebiznisz.hu/python-jpegtran/

Any feedback is very welcome, especially if you are able to compile it
on non-standard platforms. It has been tested on Linux and Python 2.3.

Usage example:

import jpegtran

transformer = jpegtran.transformer( )

transformer.rotate( 90, 'pic.jpg', 'pic_rotated.jpg' )
transformer.flip( 'horizontal', 'pic.jpg', 'pic_flipped.jpg' )
transformer.transpose( 'pic.jpg', 'pic_transposed.jpg' )
transformer.transverse( 'pic.jpg', 'pic_transversed.jpg' )
transformer.gray( 'pic.jpg', 'pic_gray.jpg' )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: logo design - BZZZT! OT!

2006-10-29 Thread Paul McGuire
"Xah Lee" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
...
Again: the primary purpose of this message, is to beseach that the
power-that-be of lispers, seriously think about getting themselves a
official logo. Thanks.


Does the "power-that-be of lispers" spend much time on c.l.py?  Even though 
Python is mentioned in passing in this post, it really doesn't need to be 
cross-posted here.

-- Paul


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


Re: ANN: Leo 4.4.2.1 final released

2006-10-29 Thread John Henry
I downloaded the Windows exe, ran it and a small blank message window
poped up and that was it.

I am still running 2.3.

Edward K. Ream wrote:
> Leo 4.4.2.1 final is now available at:
> http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106
>
> Leo 4.4.2.1 final fixes a recent bug that caused Leo not to create the
> .leoRecentFiles.txt file properly in some situations. There are no known
> significant bugs in this version of Leo.
>
> Leo 4.4.2 final fixes a few bugs and adds support for pymacs.
>
> Leo is a text editor, data organizer, project manager and much more. See:
> http://webpages.charter.net/edreamleo/intro.html
>
> The highlights of Leo 4.4.2:
> 
> - You can now store settings in myLeoSettings.leo without fear of those
> settings
>   being changed by cvs updates or in future versions of Leo.
> - Leo's vnode and tnode classes are now completely independent of the rest
> of Leo.
>   Some api's have been changed.  This 'big reorg' and may affect scripts and
> plugins.
> - Leo's vnode and tnode classes can optionally be compatible with ZODB
> databases,
>   i.e., they can optionally derive from ZODB.Persistence.Persistent.
>   See Chapter 17: Using ZODB with Leo for details.
> - The leoOPML plugin defines commands to read and write OPML files.
> - The slideshow plugin allows Leo to run slideshows defined by @slideshow
> and @slide nodes.
> - The leo_to_rtf and leo_to_html plugins create rtf and html files from Leo
> outlines.
> - Much faster navigation through the outline.
> - When focus is in the outline pane, you can move to headlines by typing the
> first letter of headlines.
> - The find command now optionally closes nodes not needed to show the node
> containing the present match.
> - Numerous changes that make Leo easier to use without using a mouse,
> including new commands and options.
> - Many new minibuffer commands now appear in the Cmds menu.
> - A sax parser can now optionally read .leo files.
>
> Links:
> --
> Leo:http://webpages.charter.net/edreamleo/front.html
> What's new: http://webpages.charter.net/edreamleo/new-4-4-2.html
> Home:   http://sourceforge.net/projects/leo/
> Download:   http://sourceforge.net/project/showfiles.php?group_id=3458
> CVS:http://leo.tigris.org/source/browse/leo/
> Leo's Wiki: http://leo.zwiki.org/FrontPage
> Wikipedia:  http://en.wikipedia.org/wiki/Leo_%28text_editor%29
> Quotes: http://webpages.charter.net/edreamleo/testimonials.html
>
> 
> Edward K. Ream   email:  [EMAIL PROTECTED]
> Leo: http://webpages.charter.net/edreamleo/front.html
> 

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


wx.EVT_TOOL_RCLICKED

2006-10-29 Thread g.franzkowiak
Hi everybody,

I want use wx.EVT_TOOL_RCLICKED for an toolbar, but I've got no 
responcses under Linux.

The following part works under MSW, but under Linux..., the
"wx.EVT_TOOL_RCLICKED" generate nothing:

tb.AddTool(TB_ID, './*.png',isToggle=True)
self.Bind(wx.EVT_TOOL,  self.OnToolLeftClick,  id=TB_ID)
self.Bind(wx.EVT_TOOL_RCLICKED, self.OnToolRightClick, id=TB_ID)


Can somebody help ?

gerd


PS:

System parts:

wxPython 2.6.3.2
(wxGTK, unicode, gtk2, wx-assertions-off, SWIG-1.3.27)
Running on Python 2.3.5

AND

wxPython 2.6.1.2pre
(wxGTK, unicode, gtk2, wx-assertions-off)
Running on Python 2.4.3

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


Re: Regular Expression help for parsing html tables

2006-10-29 Thread Paddy

[EMAIL PROTECTED] wrote:
> Hello,
>
> I am having some difficulty creating a regular expression for the
> following string situation in html. I want to find a table that has
> specific text in it and then extract the html just for that immediate
> table.
>
> the string would look something like this:
>
> ...stuff here...
> 
> ...stuff here...
> 
> ...stuff here...
> 
> ...
> text i'm searching for
> ...
> 
> ...stuff here...
> 
> ...stuff here...
> 
> ...stuff here...
>
>
> My question:  is there a way in RE to say:   "when I find this text I'm
> looking for, search backwards and find the immediate instance of the
> string ""  and then search forwards and find the immediate
> instance of the string "".  " ?
>
> any help is appreciated.
>
> Steve.

Might searching the output of BeautifulSoup(html).prettify() make
things easier?

http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing%20HTML

- Paddy

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


Printing out the objects stack

2006-10-29 Thread Fabiano Sidler
Hi folks!

For getting a plan how a stack-based VM like Python works, I added a
function that prints out the current object stack. Unfortunately, it
crashes the VM. Could someone here take a look at it? What's wrong with
it?:

--- snip ---
static PyObject *
sys_stack(PyObject *self)
{
PyFrameObject *f = PyThreadState_GET()->frame;
PyObject
**i,
**begin = f->f_localsplus,
**end = f->f_valuestack;

end += f->f_code->co_stacksize;
flog(   "co_name: %s\n"
"co_stacksize: %d\n"
"localsplus: %d\n"
"valuestack: %d\n",
PyString_AsString(f->f_code->co_name), f->f_code->co_stacksize,
f->f_localsplus, f->f_valuestack);
flog("locals:\n");
{
PyObject *list = f->f_code->co_names;
int len,i;

len = PyList_Size(list);
for (i=0; if_valuestack - (int)i)/4;
PyObject *obi;
char *strval;

if (*i == NULL) {
flog("NULL\n");
break; }
if ((obi=PyObject_Str(*i)) != NULL) {
if ((strval=PyString_AsString(obi)) != NULL) {
flog("[%3d] %s\n", o, strval);
}
}
}
finished:
Py_INCREF(Py_None);
return Py_None;
}
--- snap ---

flog(fmt, ...) is my function to log to a file, sys_stack I've made available
to Python as sys.stack and PyFrame_New I modified so that it nulls the memory
allocated for the objects stack. Now the following Python code crashes...

--- snip ---
def f(foo,bar,boo,far):
foobar='foobar'
print foobar
sys.stack()

f('foo','bar','boo','far') # CRASH
--- snap ---

...and in my "logfile" I have...

--- snip ---
co_name: f
co_stacksize: 1
localsplus: 136139316
valuestack: 136139336
locals:
end of locals
[  5] foo
[  4] bar
[  3] boo
[  2] far
[  1] foobar
[  0] 
--- snap ---

Now the following things are not clear to me:
-Why does the VM crash? Did I use the wrong stack boundaries?
-Why are no locales printed?
-Why is the function "stack" not right before or after "foo"
 on the stack? When I disassemble the code of f with dis.dis,
 it reveals that sys.stack and foo are pushed onto the stack
 successively.

Greetings,
Fips
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: importing class

2006-10-29 Thread gmarkowsky
Thanks, I got that part. The problem I'm still having is that it's not
seeing things like text_1, which are defined in the program. How can I
make it see that?

Another question I should ask is whether I should even bother doing
this. That is, it seems that the elegant and approved way of doing this
kind of thing may be to put a class in a module and then just use the
module over and over again in programs. I'm making a few GUIs which
present two options and ask the user to chose one, so I thought I could
just do it this way. Of course I could very easily just copy and paste
the class into each file, but that seems silly. I haven't had any
trouble using modules for functions, but for classes it is not working
right so far, and I'm having trouble finding examples to follow.

Greg

Marc 'BlackJack' Rintsch wrote:
> In <[EMAIL PROTECTED]>, gmarkowsky
> wrote:
>
> > Hi all,
> >
> > I'm trying to import a class from a module. The class looks like this:
> > class App:
> >
> > def __init__(self, master):
> >
> > frame = Frame(master)
> > frame.pack()
> >
> > self.button = Button(frame, text=text_1, command= self.comm_1)
> > self.button.pack(side=LEFT)
> >
> > self.hi_there = Button(frame, text=text_2, command=self.comm_2)
> > self.hi_there.pack(side=LEFT)
> >
> > def comm_1(self):
> > command1()
> > root.quit()
> >
> > def comm_2(self):
> > command2()
> > root.quit()
> >
> > It's supposed to just make a Tkinter window with two choices. The
> > problem is that when I import it from a module, I get the following
> > error:
> >
> > NameError: global name 'Frame' is not defined
> >
> > But when I copy and paste it into the file, it works. Can anyone tell
> > me what's wrong?
>
> Yes, the global name `Frame` is not defined.  `Frame` is a name in the
> `Tkinter` module and you have to import it to reference it.  Add the
> following import statement to your file:
>
> from Tkinter import Frame, Button
>
> You use `Button` too and this also lives in the `Tkinter` module.
> 
> Ciao,
>   Marc 'BlackJack' Rintsch

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


Re: Computer locks up when running valid stand alone Tkinter file.

2006-10-29 Thread jim-on-linux

Thanks for responding,

For those who care.
The solution to the problem was;

First, I did not give a parent to the Yview 
scrollbar.

Next, I used the pack geometry for this class and 
everything else is grid geometry.

When run stand alone it ran fine because the Yview 
scrollbar attached itself to the default parent, 
but when run from another module, it locked up.

The difficulty is really in the fact that 
scrollbar Yview without a parent tried to attach 
itself to the root Tk, already built and running 
with grid geometry.

Pack and grid in the same Frame don't get along 
(computer lockup).

Give Yview a parent, problem solved. 
Changed pack to grid anyway.


jim-on-linux

http://www.inqvista.com




On Wednesday 25 October 2006 23:05, you wrote:
> > But, when I call it from another module it
> > locks
>
> methinks this "other module" has the answer.
>
> jim-on-linux wrote:
> > py help,
> >
> > The file below will run as a stand alone
> > file. It works fine as it is.
> >
> > But, when I call it from another module it
> > locks my computer, The off switch is the only
> > salvation.
> >
> > This module when run as a stand alone, it
> > will open a jpeg image and add a vertical and
> > horizontal scrollbar to the canvass. That's
> > all it does.
> >
> > Replace the img9.jpg file with one of your
> > own, put the image in the current working
> > dir., and run.
> >
> > If you think you can help, I would appreciate
> > it.
> >
> >
> > jim-on-linux
> >
> >
> >
> >
> >
> > 
> >
> > #!/usr/bin/env python
> >
> > """
> > #
> > import Tkinter as Tk
> >
> > Do not do
> > ( from Tkinter import * )
> > because of  name space conflict with
> > Image.open
> >
> > #
> >#
> >
> > below imports  Image and ImageTk are
> > from Imaging-1.1.5, PIL  in Python
> >
> > """
> >
> >
> > import Image
> > import  ImageTk
> > import Tkinter as Tk
> > import os
> >
> > vpath = os.getcwd()+os.sep+'img9.jpg'
> >
> >
> >
> > class Kshow_0 :
> >
> > def __init__(self ) :
> > self.Fimgshow0()
> >
> > def Fimgshow0(self ) :
> > window = Tk.Tk()# used for stamd
> > alone
> >
> >#  window = Tk.Toplevel()
> >  # Above Toplevel call used when
> > running # from another file
> >
> >
> >
> > window.title(' Image Location '+vpath
> > ) window.protocol('WM_DELETE_WINDOW',
> > window.destroy)
> >
> > vcanvas = Tk.Canvas(window, width =
> > 375, height=375, borderwidth = 1, bg=
> > 'white')
> >
> > sbarY=Tk.Scrollbar()
> > sbarX = Tk.Scrollbar(
> > orient='horizontal') sbarY.config(command=
> > vcanvas.yview) sbarX.config(command=
> > vcanvas.xview)
> >
> >
> > vcanvas.config(yscrollcommand=sbarY.set)
> > vcanvas.config(xscrollcommand=sbarX.set)
> >
> > sbarY.pack(side='right', fill='y')
> > sbarX.pack(side='bottom', fill='x')
> > vcanvas.pack(expand='yes', 
> > fill='both')
> >
> > im= Image.open( vpath)
> > tkim = ImageTk.PhotoImage(im)
> >
> > imgW = tkim.width()
> > print imgW, '## imgW, jpg 58\n'
> >
> > imgH = tkim.height()
> > print imgH, '## imgH, jpg 61\n'
> >
> > # Draw the image on the canvas
> > vcanvas.create_image(0, 0, 
> > image=tkim, anchor = 'nw'  )
> >
> > vcanvas.config(scrollregion= (0, 0,
> > imgW, imgH)) window.mainloop ()
> >
> >
> > if __name__ == '__main__' :
> >
> > Kshow_0()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: importing class

2006-10-29 Thread gmarkowsky
Yep, that fixed it. Many thanks.

Greg

Dennis Lee Bieber wrote:
> On 27 Oct 2006 09:22:00 -0700, [EMAIL PROTECTED] declaimed the
> following in comp.lang.python:
>
> > It's supposed to just make a Tkinter window with two choices. The
> > problem is that when I import it from a module, I get the following
> > error:
> >
> > NameError: global name 'Frame' is not defined
> >
> > But when I copy and paste it into the file, it works. Can anyone tell
> > me what's wrong?
> >
>   Probably the simple fact that your "file" likely has all the imports
> for Tkinter defined. The module that you are importing needs to have
> those imports inside it -- imported modules do not have visibility of
> names defined in the importING file.
> --
>   WulfraedDennis Lee Bieber   KD6MOG
>   [EMAIL PROTECTED]   [EMAIL PROTECTED]
>   HTTP://wlfraed.home.netcom.com/
>   (Bestiaria Support Staff:   [EMAIL PROTECTED])
>   HTTP://www.bestiaria.com/

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


Observation on "Core Python Programming"

2006-10-29 Thread John Coleman
Greetings,
   My copy of the second edition of Chun's "Core Python Programming"
just arrived from Amazon on Friday. What really jumped out at me is an
interesting feature about how it sequences its topics, namely,
(user-defined) functions are not introduced until chapter 11, fully 400
pages into the book. This contrasts strongly with a traditional
"Introduction to language X" book which has a chapter sequence roughy
like:

Chapter 1) Intro - Hello World
Chapter 2) Variables
Chapter 3) If, if-else
Chapter 4) Loops
Chapter 5) Functions and/or subroutines

The exact details vary from book to book and language to language of
course, but usually the above topics are covered in the first 100-150
pages since it is hard to do anything interesting until all of these
tools are under your belt. Chun's book by contrast is able, on the
strength of Python's built-in functions, to cover a fair amount of
relatively interesting things (dictionaries, file IO, exception
handling, etc.) before introducing user-defined functions.

I don't want to read too much into this, but the mere fact that it is
possible to write a Python book in this fashion seems to confirm the
"batteries are included" philosophy of Python. Perhaps there is less
need to learn how to roll your own batteries as soon as possible.

-John Coleman

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


ANN: Leo 4.4.2.1 final released

2006-10-29 Thread Edward K. Ream
Leo 4.4.2.1 final is now available at:
http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106

Leo 4.4.2.1 final fixes a recent bug that caused Leo not to create the
.leoRecentFiles.txt file properly in some situations. There are no known
significant bugs in this version of Leo.

Leo 4.4.2 final fixes a few bugs and adds support for pymacs.

Leo is a text editor, data organizer, project manager and much more. See:
http://webpages.charter.net/edreamleo/intro.html

The highlights of Leo 4.4.2:

- You can now store settings in myLeoSettings.leo without fear of those 
settings
  being changed by cvs updates or in future versions of Leo.
- Leo's vnode and tnode classes are now completely independent of the rest 
of Leo.
  Some api's have been changed.  This 'big reorg' and may affect scripts and 
plugins.
- Leo's vnode and tnode classes can optionally be compatible with ZODB 
databases,
  i.e., they can optionally derive from ZODB.Persistence.Persistent.
  See Chapter 17: Using ZODB with Leo for details.
- The leoOPML plugin defines commands to read and write OPML files.
- The slideshow plugin allows Leo to run slideshows defined by @slideshow 
and @slide nodes.
- The leo_to_rtf and leo_to_html plugins create rtf and html files from Leo 
outlines.
- Much faster navigation through the outline.
- When focus is in the outline pane, you can move to headlines by typing the 
first letter of headlines.
- The find command now optionally closes nodes not needed to show the node 
containing the present match.
- Numerous changes that make Leo easier to use without using a mouse, 
including new commands and options.
- Many new minibuffer commands now appear in the Cmds menu.
- A sax parser can now optionally read .leo files.

Links:
--
Leo:http://webpages.charter.net/edreamleo/front.html
What's new: http://webpages.charter.net/edreamleo/new-4-4-2.html
Home:   http://sourceforge.net/projects/leo/
Download:   http://sourceforge.net/project/showfiles.php?group_id=3458
CVS:http://leo.tigris.org/source/browse/leo/
Leo's Wiki: http://leo.zwiki.org/FrontPage
Wikipedia:  http://en.wikipedia.org/wiki/Leo_%28text_editor%29
Quotes: http://webpages.charter.net/edreamleo/testimonials.html


Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html



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


Re: enumerate improvement proposal

2006-10-29 Thread Georg Brandl
James Stroud wrote:
> I think that it would be handy for enumerate to behave as such:
> 
> def enumerate(itrbl, start=0, step=1):
>i = start
>for it in itrbl:
>  yield (i, it)
>  i += step
> 
> This allows much more flexibility than in the current enumerate, 
> tightens up code in many cases, and seems that it would break no 
> existing code. Yes, I have needed this behavior with enumerate, like 
> tonight and the current example. I put the "step" parameter in for 
> conceptual symmetry with slicing.
> 
> Here is a case use (or is it use case?):

Incidentally, I yesterday wrote a patch giving enumerate() a start parameter
(and, more importantly, changing it so that it doesn't wraparound at 
sys.maxint). It can be found here:

https://sourceforge.net/tracker/?func=detail&atid=305470&aid=1586315&group_id=5470

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


Re: enumerate improvement proposal

2006-10-29 Thread Peter Otten
James Stroud wrote:

> I think that it would be handy for enumerate to behave as such:
> 
> def enumerate(itrbl, start=0, step=1):
>i = start
>for it in itrbl:
>  yield (i, it)
>  i += step
> 
> This allows much more flexibility than in the current enumerate,
> tightens up code in many cases, and seems that it would break no
> existing code. Yes, I have needed this behavior with enumerate, like
> tonight and the current example. I put the "step" parameter in for
> conceptual symmetry with slicing.
> 
> Here is a case use (or is it use case?):

I don' think you have a use case here:

# untested
def find_interval(value, bounds, funny_offset=0, reverse=False):
bounds = sorted(bounds)
if reverse:
index = len(bounds) - bisect.bisect_left(bounds, value)
else:
index = bisect.bisect_right(bounds, value)
return index + funny_offset

You can tell by its name which of the arguments I would have omitted :-)

> Of course, I haven't used step here. 

That seems to be typical. The only use case I've ever come across is start=1
for output aimed at a human reader.

> Even in this trivial example the 
> proposed enumerate cleans the code and logic, eliminating a couple of
> plus signs. For this real-world example, the practical requirement for
> reversing the bins obfuscates somewhat the de-obfuscation provided by
> the proposed enumerate. But I think that it might be obvious that the
> proposed enumerate could help significantly in cases a bit more
> complicated than this one.

Of course you get these claimed advantages from a self-written function,
too.

> Any thoughts?

You have my support for adding a start parameter to enumerate(). I fear it
won't make a difference.

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


PyCon: proposals due by Tuesday 10/31

2006-10-29 Thread A.M. Kuchling
Final reminder: if you want to submit a proposal to PyCon, you should
do it by end of Tuesday, October 31st.

 for more info

The deadline for tutorials is November 15th:

http://us.pycon.org/TX2007/CallForTutorials

PyCon is the Python community conference, held next February 23-25
near Dallas; a tutorial day will be on February 22.  See
http://us.pycon.org/ for more info.

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


Re: Where do nested functions live?

2006-10-29 Thread Frederic Rentsch
Fredrik Lundh wrote:
> Frederic Rentsch wrote:
>
>   
>> At some later point I need to increment my units some more and probably 
>> will again a number of times. Clearly this has to go into a function.
>> 
>
> since Python is an object-based language, clearly you could make your 
> counter into a self-contained object instead of writing endless amounts 
> of code and wasting CPU cycles by storing what's really a *single* state 
> in a whole bunch of separate variables.
>   
This is surely a good point I'll have to think about.
> in your specific example, you can even use an existing object:
>   
Of course. But my example wasn't about time. It was about the situation
> t = datetime.datetime.now()
>
> # increment
> t += datetime.timedelta(milliseconds=msec)
>
> print t.timetuple() # get the contents
>
> if you're doing this so much that it's worth streamlining the timedelta 
> addition, you can wrap the datetime instance in a trivial class, and do
>
> t += 1500 # milliseconds
>
> when you need to increment the counter.
>
>  > This is a little like a shop where the mechanics have to get their
>  > tools and work pieces from the manager and hand them back to him when 
>  > they're done.
>
> that could of course be because when he was free to use whatever tool he 
> wanted, he always used a crowbar, because he hadn't really gotten around 
> to read that "tool kit for dummies" book.
>   
No mechanic always uses a crowbar. He'd use it just once--with the same 
employer.
> 
>
>   


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


Re: enumerate improvement proposal

2006-10-29 Thread James Stroud
Fredrik Lundh wrote:
> James Stroud wrote:
> 
>> The code is for an economist. She is insistent on starting with the 
>> first bin as 1.
> 
> leaky abstractions in reverse, in other words?  that's not a good design 
> approach.
> 
> 
>

I'm not sure I understand what "leaky abstractions" means.

I am helping someone with dubious programming skills make sense of a 
pile of code they wrote--code which getting a little unwieldy to debug. 
I think "design approach" can't really apply here. The idea is to make 
it comprehensible at some level.

I'm still curious what you mean by "leaky abstractions". Please explain.

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


Re: enumerate improvement proposal

2006-10-29 Thread Fredrik Lundh
James Stroud wrote:

> The code is for an economist. She is insistent on starting with the 
> first bin as 1.

leaky abstractions in reverse, in other words?  that's not a good design 
approach.



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


Re: enumerate improvement proposal

2006-10-29 Thread James Stroud
Fredrik Lundh wrote:
> James Stroud wrote:
> 
>> def enumerate(itrbl, start=0, step=1):
>>i = start
>>for it in itrbl:
>>  yield (i, it)
>>  i += step
> 
> that's spelled
> 
> izip(count(start), sequence)
> 
> in today's Python.
> 
>  > def in_interval(test, bounds, first=1, reverse=False):
> 
> why is it this function's job to add an offset to the actual sequence 
> index?
> 
> 
> 

BTW, thank you for your tip.

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


Re: enumerate improvement proposal

2006-10-29 Thread James Stroud
Fredrik Lundh wrote:
> why is it this function's job to add an offset to the actual sequence 
> index?
> 
> 

The code is for an economist. She is insistent on starting with the 
first bin as 1. I'm guessing, practically, binning linerizes data and 
the bin number may potentially become a divisor or perhaps the operand 
in a logarithm.

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


Re: unescape HTML entities

2006-10-29 Thread Frederic Rentsch
Rares Vernica wrote:
> Hi,
>
> How can I unescape HTML entities like " "?
>
> I know about xml.sax.saxutils.unescape() but it only deals with "&", 
> "<", and ">".
>
> Also, I know about htmlentitydefs.entitydefs, but not only this 
> dictionary is the opposite of what I need, it does not have " ".
>
> It has to be in python 2.4.
>
> Thanks a lot,
> Ray
>
One way is this:

 >>> import SE  # 
Download from http://cheeseshop.python.org/pypi/SE/2.2%20beta
 >>> SE.SE ('HTM2ISO.se')('input_file_name', 'output_file_name')# 
HTM2ISO.se is included
'output_file_name'

For repeated translations the SE object would be assigned to a variable:

 >>> HTM_Decoder = SE.SE ('HTM2ISO.se')

SE objects take and return strings as well as file names which is useful 
for translating string variables, doing line-by-line translations and 
for interactive development or verification. A simple way to check a 
substitution set is to use its definitions as test data. The following 
is a section of the definition file HTM2ISO.se:

test_string = '''
ø=(xf8)   #  248  f8
ù=(xf9)   #  249  f9
ú=(xfa)   #  250  fa
û=(xfb)#  251  fb
ü=(xfc) #  252  fc
ý=(xfd)   #  253  fd
þ=(xfe)#  254  fe
é=(xe9)
ê=(xea)
ë=(xeb)
ì=(xec)
í=(xed)
î=(xee)
ï=(xef)
'''

 >>> print HTM_Decoder (test_string)

ø=(xf8)   #  248  f8
ù=(xf9)   #  249  f9
ú=(xfa)   #  250  fa
û=(xfb)#  251  fb
ü=(xfc) #  252  fc
ý=(xfd)   #  253  fd
þ=(xfe)#  254  fe
é=(xe9)
ê=(xea)
ë=(xeb)
ì=(xec)
í=(xed)
î=(xee)
ï=(xef)

Another feature of SE is modularity.

 >>> strip_tags = '''
   ~<(.|\x0a)*?>~=(9)   # one tag to one tab
   ~~=(9)  # one comment to one tab
|   # run
   "~\x0a[ \x09\x0d\x0a]*~=(x0a)"   # delete empty lines
   ~\t+~=(32)   # one or more tabs to one space
   ~\x20\t+~=(32)   # one space and one or more tabs to 
one space
   ~\t+\x20~=(32)   # one or more tab and one space to 
one space
'''

 >>> HTM_Stripper_Decoder = SE.SE (strip_tags + ' HTM2ISO.se ')   # 
Order doesn't matter

If you write 'strip_tags' to a file, say 'STRIP_TAGS.se' you'd name it 
together with HTM2ISO.se:

 >>> HTM_Stripper_Decoder = SE.SE ('STRIP_TAGS.se  HTM2ISO.se')   # 
Order doesn't matter

Or, if you have two SE objects, one for stripping tags and one for 
decoding the ampersands, you can nest them like this:

 >>> test_string = "René est un garçon qui 
paraît plus âgé. "

 >>> print Tag_Stripper (HTM_Decoder (test_string))
  René est un garçon qui paraît plus âgé.

Nesting works with file names too, because file names are returned:

 >>> Tag_Stripper (HTM_Decoder ('input_file_name'), 'output_file_name')
'output_file_name'


Frederic



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


Re: question about True values

2006-10-29 Thread Steven D'Aprano
On Sun, 29 Oct 2006 00:31:23 -0700, Carl Banks wrote:

> Steven D'Aprano wrote:
>> Carl Banks:
>> > Overall, your objections don't really apply, since you're arguing what
>> > ought to be whereas my argument is pragmatic.  Practically speaking, in
>> > realistic situations, "if len(a)>0" will work for a wider range of types
>> > than "if a:".
>>
>> Well, that's a quantitative claim you're making there. Have you
>> actually gone through, say, the built in types and checked how many
>> have a length versus how many work in a truth-context?
> 
> No, and it's irrelevant to my argument.

And yet you not only made the claim in the first place, but you also spend
a good half or three quarters of your response justifying your claim. You
obviously didn't think it was irrelevant when you first made the claim,
and you clearly still don't think it was irrelevant now that you've spent
time checking an arbitrary set of types. Either way, you're still wrong.

"if a:" will work with EVERY TYPE except those few (the only one?) like
numpy arrays which deliberately raise an exception because they don't make
sense in a Boolean context. (And even then, arguably numpy is doing the
wrong thing: the Pythonic behaviour would be for numpy arrays to all
be True.)

"if len(a)>0:" can only work with types that have lengths. It is a logical
necessity that the number of types that have lengths must be no bigger
than the number of types in total, numpy arrays notwithstanding.



> For some reason, people seem to think it's absolutely wonderful that
> you can write "if X:" somewhere, and that this "works" whether X is a
> list or an int or any other object, as if "working" for both ints and
> lists was actually useful.
> 
> Well, it's not.
> 
> You see, presumably you have to do something with X.  And in realistic
> code, there's not a lot of stuff you can do with that works for both
> container types like lists and dict, and atomic types like ints and
> floats.  

Who cares whether or not your function accepts mixed data types like lists
and floats? Why do you think it matters whether the one function has to
operate on both sequences and atomic types?

What *does* matter is that, regardless of whether you are operating on
sequences, mappings, numeric types, the same syntax works.

That's why (for example) Python allows + to operate on lists, or strings,
or floats -- but that doesn't imply that you can add a list to a float,
or that the same code will operate happily on both lists and floats. You,
the developer, don't need to care what data types you are adding, you just
use the same syntax: a+b. The objects themselves know what addition
means to themselves. In practice, string addition threatens to be so
inefficient that you might wish to avoid doing it, but as a general
principle, Python idioms and syntax are as type-independent as possible.

That's why obj[index] works whether you are getting or setting or deleting
an item, whether it is a sequence or a mapping or a custom class. As much
as possible, you don't need to know what the object is to know what syntax
to use. The idiom for item-access should always be obj[index], not
obj[index] for some types, obj.get(index) for some others, and
getitem(obj, index) for the rest.

(Custom classes are, of course, free to break these guidelines, just as
the numpy developers were free to have __nonzero__ raise an exception. One
hopes they have good reasons for doing so.)

And that's why Python not only allows but prefers "if any_object_at_all:"
over type-dependent tricks. The *object itself* is supposed to know
whether it is equivalent to true or false (or, in rare cases like numpy
arrays, raise an exception if truth-testing doesn't mean anything for the
type). You, the developer, are not supposed to spend your time wondering
how to recognise if the object is equivalent to false, you just ask the
object.

If some well-meaning person argued that the correct way to test for a
numeric value of zero/non-zero was like this:

if x*2 != x:
# x must be non-zero

you'd fall down laughing (at least, I hope you'd fall down laughing). Yes,
such a test works, but you'd be crazy to do such unnecessary work if all
you want to know if x was nonzero. (And beware of floating point rounding:
what if x is tiny?)

And then someone passes a class that implements infinity or the alephs to
this function (that could simply mean an INF float on a platform that
supports the IE standard) and the code wrongly decides that INF is zero.
Oops.

"if x == 0:" is better, but still not good enough, because you're
still making assumptions about the data type. What if it is a numeric type
that works with interval arithmetic? You don't know what the right way to
test for a False interval is -- but the interval class itself will know.

And that's the point -- you're making unnecessary assumptions about the
data, *and* doing unnecessary calculations based on those assumptions. At
best, you're wasting your time. At worst, you're intr

Re: enumerate improvement proposal

2006-10-29 Thread Fredrik Lundh
James Stroud wrote:

> def enumerate(itrbl, start=0, step=1):
>i = start
>for it in itrbl:
>  yield (i, it)
>  i += step

that's spelled

 izip(count(start), sequence)

in today's Python.

 > def in_interval(test, bounds, first=1, reverse=False):

why is it this function's job to add an offset to the actual sequence index?



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


Re: Providing full interaction with the run time

2006-10-29 Thread Fredrik Lundh
Dale Strickland-Clark wrote:

> We have a system we're developing which runs as a server. It has an xml-rpc
> interface which I've extended to provide some debugging facilities. This
> has already proved very useful and will continue to be so as the system is
> prepared for live deployment.
> 
> The debugging interface attempts to emulate the Python interactive shell.
> You type expressions, you get an answer. You type statements, they get
> executed.
> 
> The problem is these two types of input are handled differently by Python.
> You don't seem to be able to pass statements (which includes assignments)
> and expressions through the same calls.
> 
> There are three keywords that support this type of function: EXEC, EVAL and
> COMPILE. We can ignore EXEC for this because it doesn't support saving and
> restoring a local environment and EVAL can do it better.

huh?  both exec and eval take optional execution contexts:

 http://effbot.org/pyref/eval.htm
 http://effbot.org/pyref/exec.htm

> Or am I going about this all wrong?

yes, you're trying to reinvent the "code" module (and badly, it seems 
;-).  see the library reference to details, this page for some examples:

 http://www.effbot.org/librarybook/code.htm



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


Re: Event driven server that wastes CPU when threaded doesn't

2006-10-29 Thread Bjoern Schliessmann
Snor wrote:

> There is a lot of interaction between the clients and they would
> often need to write to the same list of values, which of course
> becomes a problem with a threaded server - so event driven solves
> that problem, and I assumed it would solve all my problems.

Which problem, and why "of course"? Sorry, I can't follow you
here :)

> I will want the server to support as many users as is possible on
> any given machine - and so wasted CPU cycles is something I am
> trying to avoid.

I'm not exactly sure how you connect to that SQL server ... you
shouldn't wait for the response of the MySQL server in a blocking
way, but either using dataReceived() method of the protocol
instance or, if that isn't possible, by using a Deferred instance
that fires when the answer is available. This is also possible with
your client connections.
 
Regards,


Björn

-- 
BOFH excuse #354:

Chewing gum on /dev/sd3c

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


Re: enumerate improvement proposal

2006-10-29 Thread James Stroud
James Stroud wrote:
> I think that it would be handy for enumerate to behave as such:
> 
> def enumerate(itrbl, start=0, step=1):
>   i = start
>   for it in itrbl:
> yield (i, it)
> i += step
> 
> This allows much more flexibility than in the current enumerate, 
> tightens up code in many cases, and seems that it would break no 
> existing code. Yes, I have needed this behavior with enumerate, like 
> tonight and the current example. I put the "step" parameter in for 
> conceptual symmetry with slicing.
> 
> Here is a case use (or is it use case?):
> 
> 
> # with the proposed enumerate
> import operator
> def in_interval(test, bounds, first=1, reverse=False):
>   op = operator.gt if reverse else operator.lt   # python 2.5
>   bounds = sorted(bounds, reverse=reverse)
>   for i, bound in enumerate(bounds, first):
> if op(test, bound):
>   return i
>   return i + 1
> 
> 
> # with the existing enumerate
> import operator
> def in_interval(test, bounds, first=1, reverse=False):
>   op = operator.gt if reverse else operator.lt   # python 2.5
>   bounds = sorted(bounds, reverse=reverse)
>   for i, bound in enumerate(bounds):
> if op(test, bound):
>   return i + first
>   return i + first + 1
> 
> 
> py> # eg
> ...
> py> in_interval(8, bounds)
> 2
> py> in_interval(1, bounds)
> 1
> py> in_interval(1, bounds, reverse=True)
> 5
> py> in_interval(8, bounds, reverse=True)
> 4
> py> in_interval(20, bounds, reverse=True)
> 2
> 
> Of course, I haven't used step here. Even in this trivial example the 
> proposed enumerate cleans the code and logic, eliminating a couple of 
> plus signs. For this real-world example, the practical requirement for 
> reversing the bins obfuscates somewhat the de-obfuscation provided by 
> the proposed enumerate. But I think that it might be obvious that the 
> proposed enumerate could help significantly in cases a bit more 
> complicated than this one.
> 
> Any thoughts?
> 
> James

After a brief reflection, I realized that I just described a 
"for-to-step-do" style loop one might find in many other languages, most 
notably BASIC.

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


Re: Event driven server that wastes CPU when threaded doesn't

2006-10-29 Thread Fredrik Lundh
Snor wrote:


> Is the only solution to use a threaded server to let my clients make
> their requests and receive a response in the fastest possible time?

since the problem is that you need to wait for database anyway, maybe 
you could use one or more threads to deal with the database, and keep 
using events to talk to the clients?



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


enumerate improvement proposal

2006-10-29 Thread James Stroud
I think that it would be handy for enumerate to behave as such:

def enumerate(itrbl, start=0, step=1):
   i = start
   for it in itrbl:
 yield (i, it)
 i += step

This allows much more flexibility than in the current enumerate, 
tightens up code in many cases, and seems that it would break no 
existing code. Yes, I have needed this behavior with enumerate, like 
tonight and the current example. I put the "step" parameter in for 
conceptual symmetry with slicing.

Here is a case use (or is it use case?):


# with the proposed enumerate
import operator
def in_interval(test, bounds, first=1, reverse=False):
   op = operator.gt if reverse else operator.lt   # python 2.5
   bounds = sorted(bounds, reverse=reverse)
   for i, bound in enumerate(bounds, first):
 if op(test, bound):
   return i
   return i + 1


# with the existing enumerate
import operator
def in_interval(test, bounds, first=1, reverse=False):
   op = operator.gt if reverse else operator.lt   # python 2.5
   bounds = sorted(bounds, reverse=reverse)
   for i, bound in enumerate(bounds):
 if op(test, bound):
   return i + first
   return i + first + 1


py> # eg
...
py> in_interval(8, bounds)
2
py> in_interval(1, bounds)
1
py> in_interval(1, bounds, reverse=True)
5
py> in_interval(8, bounds, reverse=True)
4
py> in_interval(20, bounds, reverse=True)
2

Of course, I haven't used step here. Even in this trivial example the 
proposed enumerate cleans the code and logic, eliminating a couple of 
plus signs. For this real-world example, the practical requirement for 
reversing the bins obfuscates somewhat the de-obfuscation provided by 
the proposed enumerate. But I think that it might be obvious that the 
proposed enumerate could help significantly in cases a bit more 
complicated than this one.

Any thoughts?

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


Event driven server that wastes CPU when threaded doesn't

2006-10-29 Thread Snor
I'm attempting to create a lobby & game server for a multiplayer game,
and have hit a problem early on with the server design. I am stuck
between using a threaded server, and using an event driven server. I've
been told time and time again that I should use an event driven server
design (that is, use twisted).

There is a lot of interaction between the clients and they would often
need to write to the same list of values, which of course becomes a
problem with a threaded server - so event driven solves that problem,
and I assumed it would solve all my problems. However some requests
from clients would require that the server goes on to query a mySQL
server (separate machine from the server). As this occurs, there is a
small amount of lag while the communication with the mySQL server takes
place, and there could be another 100 clients waiting to make a request
at this point, meanwhile the server is idling while waiting for a
response from the mySQL server - obviously not a good server model.

I will want the server to support as many users as is possible on any
given machine - and so wasted CPU cycles is something I am trying to
avoid.

Is the only solution to use a threaded server to let my clients make
their requests and receive a response in the fastest possible time?

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


  1   2   >