Re: The reverse of encode('...', 'backslashreplace')

2007-09-04 Thread Duncan Booth
"Tor Erik Sønvisen" <[EMAIL PROTECTED]> wrote:

> How can I transform b so that the assertion holds? I.e., how can I
> reverse the backslash-replaced encoding, while retaining the str-type?
> 
 a = u'‘'
 b = a.encode('ascii', 'backslashreplace')
 b
> '\\xe6'
 assert isinstance(b, str) and b == '‘'
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> assert isinstance(b, str) and b == '‘'
> AssertionError
> 

The simple answer is that you cannot: the backslashreplace isn't a 
reversible operation. e.g. Try:

>>> a = u'\\xe6æ'
>>> print a
\xe6æ
>>> b = a.encode('ascii', 'backslashreplace')
>>> b
'\\xe6\\xe6'
>>> 

There is no way after the encoding that you can tell which of the \xe6 
sequences needs reversing and which doesn't. Perhaps the following is 
what you want:

>>> b = a.encode('unicode_escape')
>>> print b
\\xe6\xe6
>>> print b.decode('unicode_escape')
\xe6æ
>>> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parameter list notation

2007-09-04 Thread Duncan Booth
TheFlyingDutchman <[EMAIL PROTECTED]> wrote:

> I am trying to use a database written in Python called buzhug.
> 
> In looking at some of the functions I see this prototype:
> 
> def create(self,*fields,**kw):
> 
> I am not clear on what the * and the ** are for or what they
> represent. Or, what are they referred to as so I can do a query for
> information on them.
> 
You could try searching for 'function definitions'. That might lead you to 
http://docs.python.org/ref/function.html "Python Reference Manual, 7.6 
Function definitions":

> Function call semantics are described in more detail in section 5.3.4.
> A function call always assigns values to all parameters mentioned in
> the parameter list, either from position arguments, from keyword
> arguments, or from default values. If the form ``*identifier'' is
> present, it is initialized to a tuple receiving any excess positional
> parameters, defaulting to the empty tuple. If the form
> ``**identifier'' is present, it is initialized to a new dictionary
> receiving any excess keyword arguments, defaulting to a new empty
> dictionary. 
-- 
http://mail.python.org/mailman/listinfo/python-list


how to get a formatted string?

2007-09-04 Thread Ginger
like format function in Visual Basic, 
format("##.##%",0.3456) ==>>  34.56%
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to get a formatted string?

2007-09-04 Thread Gary Herron
Ginger wrote:
> like format function in Visual Basic, 
> format("##.##%",0.3456) ==>>  34.56%
>   
"%5.2f%%" % (0.3456*100)
'34.56%'


See this section of the manual: 
http://docs.python.org/lib/typesseq-strings.html

Gary Herron

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


pickle error/instancemethod

2007-09-04 Thread Gregor Kling
Hello,

I have some of these nefarious pickle errors I do not understand,
maybe some of you have a clue.

This is what I get
(nd is the object which I want to pickle [cPickle.dumps(nd,2)], with
the printout of nd.__dict__):

 ERROR Error: Can't pickle : attribute lookup
__builtin__.instancemethod failed, nd: {'dvzLogger':
, '_DVZnetzDataBase__netzentries':
[], '_DVZnetzDataBase__option_fqdn_alias':
set(['a.b.c']), '_DVZnetzDataBase__admins': set([]),
'_DVZnetzDataBase__aliasentries': []}


I follow the hints on http://docs.python.org/lib/node318.html, so I
do not understand the source of the problem. I do not try to pickle
an instancemethod directly. The dict does apparently contains only
top level tuples, lists, sets, and dictionaries, classes/instances.

So if more Data is needed to analyse the problem - demand.

gfk

-- 
gfk


smime.p7s
Description: S/MIME Cryptographic Signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: list index()

2007-09-04 Thread Campbell Barton
Jason wrote:
> On Aug 30, 1:27 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote:
>>> [EMAIL PROTECTED] writes:
 What's with the index() function of lists throwing an exception on not
 found?
>>> It's letting you know that the item isn't in the list. There's no
>>> sensible return value from an "index" function in that condition.
>> What about -1?  C programmers do this all the time.  :-)
>>
>> Ciao,
>> Marc 'BlackJack' Rintsch
> 
> As other people pointed out, C doesn't have exceptions, so a C
> programmer must make an in/out parameter to indicate an error, or have
> a special return value.  In Python, you're most often searching the
> list for an object which is in the list, so the lack of the object is
> an exceptional condition.  You can certain check with the "in"
> operator beforehand to avoid the exception.  You may also subclass a
> list and override the index method, or write a standalone function to
> catch the exception and change its value.
> 
> The reason why the exception is more Pythonic is that the return value
> is always a guaranteed good index into the list.  Any errors
> (including calling .index() on a non-list instance that doesn't have
> a .index method) are exceptional, and should probably follow a very
> different code path.
> 
> Returning -1 is not a good return value to indicate an error.  After
> all, -1 is a valid index in most Python lists.  (Negative numbers
> index from the tail of the list.)
> 
>   --Jason

Agree in general tho its a bit inconsistent how...

"string".find(val)

...can return -1 but .index() cant, though the inconsistency is probably 
with string since most other areas of the py api raise errors in cases 
like this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter

2007-09-04 Thread Eric Brunel
On Tue, 04 Sep 2007 07:12:00 +0200, vijayca <[EMAIL PROTECTED]> wrote:

> i tried to use python gui module Tkinter in solaris,aix,hpux.
> while importing the module it  shows an error...
>
> import Tkinter
> error says that your python may not be configured for Tk()...
> how to get out of this...

Did you compile the Python interpreter yourself, or did it come in a sort  
of package?

In the first case, you have to install tcl/tk yourself if it's not already  
there, then tweak the build options for Python to make it use the tcl/tk  
installation you've done. How to tweak these options depends on the Python  
version you use, so please tell us what it is.

In the second case, Tkinter may be provided as a separate package, that  
you also need to install.

And BTW, Wildemar's comment still holds: please copy/paste the exact  
traceback you get if it doesn't work. I'm only guessing here...

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


[pygtk] problem with TreeView + ListStore

2007-09-04 Thread Guillermo Heizenreder
Hi list
I'm developing a application for learn pygkt, and I need to know when a
user selected or clicked one determinate row of my TreeView for shot
another signal .

Study the tutorial [1] I began to see the explanation that I see in the
chapter 14.7. TreeView Signal and found one in particular
"select-cursor-row", but I don't understood  how implementing.

Something like that.
   if user_selected_row:
  self.hbox_118.show()
  print "YES"   

NOTE: self.hbox_118 = wTree.get_widget("hbox118")

Thank and Regard
  
[1] http://www.pygtk.org/pygtk2tutorial/sec-TreeViewSignals.html

P/D: my English it to bad, I'm a novice.
-- 
Heizenreder Guillermo
http://code.google.com/u/gheize/

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


Re: parameter list notation

2007-09-04 Thread TheFlyingDutchman
Steve, Ben, Duncan,

Thanks for the replies.

TFD


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


Re: Applying transformation matrix to 3D vertex coordinates

2007-09-04 Thread PhilC
On Mon, 03 Sep 2007 23:24:42 -0500, Robert Kern
<[EMAIL PROTECTED]> wrote:

>transpose()


ahh yes I can see where that would work. Just tried it in the above
and I do get a last line of ones.

OK onward and upward :)

Many thanks Robert.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError: 'module object is not callable'

2007-09-04 Thread Chris . Tidy
Thanks guys. Changing to how Python does things has a lot of geting
used to!
Do any of you have any ideas on the best way to do the following
problem:

Each loop I perform, I get a new list of Strings.
I then want to print these lists as columns adjacent to each other
starting with the first
created list in the first column and last created list in the final
column.

If you need any more information, just let me know!
Cheers

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


Re: TypeError: 'module object is not callable'

2007-09-04 Thread Amit Khemka
On 9/4/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Thanks guys. Changing to how Python does things has a lot of geting
> used to!
> Do any of you have any ideas on the best way to do the following
> problem:
>
> Each loop I perform, I get a new list of Strings.
> I then want to print these lists as columns adjacent to each other
> starting with the first
> created list in the first column and last created list in the final
> column.
>
> If you need any more information, just let me know!
> Cheers

If I understand correctly what you may want is:

>>> l =  ['1', '2', '3', '4']

you can do:

>>> print "\t".join(l)  # lookup join method in string module,
assuming "\t" as the delimiter

or,

>>> for i in l:
 print i, '\t' ,   # note the trailing ","

If this is not what you want, post an example.

Btw, Please post new issues in a separate thread.

Cheers,
-- 

Amit Khemka
website: www.onyomo.com
wap-site: www.owap.in
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FCGI app reloading on every request

2007-09-04 Thread Michael Ströder
John Nagle wrote:
> 
> What's actually happening is that FCGI isn't running at all.
> My .fcgi file is being executed by Apache's CGI handler, and
> "fcgi.py" recognizes this, then reads the parameters as if
> a CGI program.  So it works just like a CGI program: one
> load per request.  Not sure why Apache is doing that yet.
> I'm looking at Apache configuration files now.

Are you running mod_fastcgi oder mod_fcgid?

Disclaimer: I don't claim to be an expert in that. My web2ldap source
distribution contains two examples configuration files for each of the
modules above for FastCGI over Unix Domain Socket( see directory
/etc/httpd/, comments of sample-mod_fcgid.conf
misleading). web2ldap can also be deployed as (multi-threaded)
FastCGI-server.

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


Undeterministic strxfrm?

2007-09-04 Thread Tuomas
Python 2.4.3 (#3, Jun  4 2006, 09:19:30)
[GCC 4.0.0 20050519 (Red Hat 4.0.0-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import locale
 >>> def key(s):
... locale.setlocale(locale.LC_COLLATE, 'en_US.utf8')
... return locale.strxfrm(s.encode('utf8'))
...
 >>> first=key(u'maupassant guy')
 >>> first==key(u'maupassant guy')
False
 >>> first
'\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12 
$\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xf5\xb79'
 >>> key(u'maupassant guy')
'\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12 
$\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xb5'
 >>>

May be this is enough for a sort order but I need to be able to catch 
equals too. Any hints/explanations?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: pronounciation [was: list index()]

2007-09-04 Thread Neil Cerutti
On 2007-08-31, Paddy <[EMAIL PROTECTED]> wrote:
> On Aug 31, 11:19 am, Tim Golden <[EMAIL PROTECTED]> wrote:
>> Tim Golden wrote:
>> > Erik Max Francis wrote:
>> >> Paddy wrote:
>>
>> >>> I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll
>> >>> and role similarly.
>>
>> >>> My accent is probably from the East Midlands of the UK, but is not
>> >>> pronounced.
>> >> _Troll_ and _frolic_ aren't pronounced with the same "o" sound in any
>> >> accent I've ever heard of.  Which you pronounce _boat_ and _bot_ the
>> >> same way, too?
>>
>> > [Amusingly contemplating a trolling war about the pronunciation of "troll"]
>>
>> > Well they sound the same in my more-or-less South London accent.
>> > I can't write those funny phonetic symbols (and I hate to
>> > imagine the Unicode encoding hoops I'd have to jump through
>> > to make them readable anyway) but both "o"s sound short to me.
>> > Like "bot" rather than "boat" using your example.
>>
>> Since we're talking... I'm still a little startled when I listen
>> to some of the excellent webcasts that are being produced these
>> days (showmedo.com and friends) and hear American voices pronounce
>> Python... well, the way they do, with the stress and something of a
>> drawl on the second syllable. I'm sure it's just as amusing the other
>> way round: we pronounce it with the stress on the first syllable and
>> the characteristic short vowel sound in the second.
>> (Something like: Pie'thun).
>>
>> TJG
>
> The only true way of pronouncing Python (the computing language), is
> the way it is done at the beginning of Monty Pythons Flying Circus of
> course :-)
>
> Your right, the American way does make me pause.

Ya'll can keep yer gall-dern schwa outta my Pie-thawn, ya hear?

-- 
Neil Cerutti
Persons are prohibited from picking flowers from any but their own graves.
--sign at Pennsylvania cemetery
-- 
http://mail.python.org/mailman/listinfo/python-list


Printing lists in columns (was: TypeError: 'module object is not callable')

2007-09-04 Thread A.T.Hofkamp
On 2007-09-04, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Thanks guys. Changing to how Python does things has a lot of geting
> used to!

That's part of the fun :-)

> Do any of you have any ideas on the best way to do the following
> problem:
>
> Each loop I perform, I get a new list of Strings.
> I then want to print these lists as columns adjacent to each other
> starting with the first
> created list in the first column and last created list in the final
> column.

Use zip:

>>> x = ['1', '2']
>>> y = ['3', '4']
>>> for row in zip(x,y):
...   print ', '.join(row)
...
1, 3
2, 4


zip() constructs a list of rows, like

[('1', '3'), ('2', '4')]

which is then quite easy to print



Good luck,
Albert
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError: 'module object is not callable'

2007-09-04 Thread cjt22
On Sep 4, 11:24 am, "Amit Khemka" <[EMAIL PROTECTED]> wrote:
> On 9/4/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> > Thanks guys. Changing to how Python does things has a lot of geting
> > used to!
> > Do any of you have any ideas on the best way to do the following
> > problem:
>
> > Each loop I perform, I get a new list of Strings.
> > I then want to print these lists as columns adjacent to each other
> > starting with the first
> > created list in the first column and last created list in the final
> > column.
>
> > If you need any more information, just let me know!
> > Cheers
>
> If I understand correctly what you may want is:
>
> >>> l =  ['1', '2', '3', '4']
>
> you can do:
>
> >>> print "\t".join(l)  # lookup join method in stringmodule,
>
> assuming "\t" as the delimiter
>
> or,
>
> >>> for i in l:
>
>  print i, '\t' ,   # note the trailing ","
>
> If this isnotwhat you want, post an example.
>
> Btw, Please post new issues in a separate thread.
>
> Cheers,
> --
> 
> Amit Khemka
> website:www.onyomo.com
> wap-site:www.owap.in

I think that is very similar to what I want to do.
Say I had lists a = ["1" , "2", "3"]  b = ["4", "5", "6"]  c = ["7",
"8", "9"]
Stored in another list d = [a,b,c]
I want the printed output from d to be of the form:
1   4   7
2   5   8
3   6   9

>From what I am aware, there is no table module to do this. The '\t'
operator looks like it can allow this,
I am playing with it at the moment, although going for my lunch break
now!

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


Re: TypeError: 'module object is not callable'

2007-09-04 Thread Amit Khemka
On 9/4/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> On Sep 4, 11:24 am, "Amit Khemka" <[EMAIL PROTECTED]> wrote:
> > On 9/4/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> >
> > > Thanks guys. Changing to how Python does things has a lot of geting
> > > used to!
> > > Do any of you have any ideas on the best way to do the following
> > > problem:
> >
> > > Each loop I perform, I get a new list of Strings.
> > > I then want to print these lists as columns adjacent to each other
> > > starting with the first
> > > created list in the first column and last created list in the final
> > > column.
> >
> > > If you need any more information, just let me know!
> > > Cheers
> >
> > If I understand correctly what you may want is:
> >
> > >>> l =  ['1', '2', '3', '4']
> >
> > you can do:
> >
> > >>> print "\t".join(l)  # lookup join method in stringmodule,
> >
> > assuming "\t" as the delimiter
> >
> > or,
> >
> > >>> for i in l:
> >
> >  print i, '\t' ,   # note the trailing ","
> >
> > If this isnotwhat you want, post an example.
> >
> > Btw, Please post new issues in a separate thread.
> >
> > Cheers,
> > --
> > 
> > Amit Khemka
> > website:www.onyomo.com
> > wap-site:www.owap.in
>
> I think that is very similar to what I want to do.
> Say I had lists a = ["1" , "2", "3"]  b = ["4", "5", "6"]  c = ["7",
> "8", "9"]
> Stored in another list d = [a,b,c]
> I want the printed output from d to be of the form:
> 1   4   7
> 2   5   8
> 3   6   9
>
> >From what I am aware, there is no table module to do this. The '\t'
> operator looks like it can allow this,
> I am playing with it at the moment, although going for my lunch break
> now!

Have a look at function 'zip' or function 'izip' in module "itertools" .

-- 

Amit Khemka
website: www.onyomo.com
wap-site: www.owap.in
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing lists in columns (was: TypeError: 'module object is not callable')

2007-09-04 Thread Duncan Booth
"A.T.Hofkamp" <[EMAIL PROTECTED]> wrote:

>> Each loop I perform, I get a new list of Strings.
>> I then want to print these lists as columns adjacent to each other
>> starting with the first
>> created list in the first column and last created list in the final
>> column.
> 
> Use zip:
> 
 x = ['1', '2']
 y = ['3', '4']
 for row in zip(x,y):
> ...   print ', '.join(row)
> ...
> 1, 3
> 2, 4
> 
> 
> zip() constructs a list of rows, like
> 
> [('1', '3'), ('2', '4')]
> 
> which is then quite easy to print

But watch out if the lists aren't all the same length: zip won't pad out 
any sequences, so it may not be exactly what is wanted here:

>>> x = ['1', '2', '3']
>>> y = ['4', '5']
>>> for row in zip(x,y):
print ', '.join(row)


1, 4
2, 5
>>> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing lists in columns (was: TypeError: 'module object is not callable')

2007-09-04 Thread cjt22

> But watch out if the lists aren't all the same length: zip won't pad out
> any sequences, so it maynotbe exactly what is wanted here:
>
> >>> x = ['1', '2', '3']
> >>> y = ['4', '5']
> >>> for row in zip(x,y):
>
> print ', '.join(row)
>
> 1, 4
> 2, 5
>

Unfortunately the lists will be of different sizes
By the way I apologise for different questions within the same thread.
When I have another question, I will make a new topic


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


Setting Current Dir in Python

2007-09-04 Thread Sandipan Gangopadhyay
Hi all!

I have utility programs in Python that do clean up, image processing tasks
on files in a folder. I just drop the program into the folder and run it.

I have been double clicking on a Python program in my Windows XP Home to
make it run . it sets the program's directory as the current directory when
it runs.

I have recently installed Python 2.5.1 and Pythonwin (without any errors) on
Windows Vista Ultimate.

Now, the programs run fine within Pythonwin IDE when current directory is
set to the program's directory.

But, when I double click them from Windows Explorer, the program is not run.

If I run the following program:


===
# MODULE IMPORT
try:
import time, os, Image, urllib, string, math, os.path, filecmp, shutil,
sys
except:
strInput = raw_input("Failed import. Hit enter key to continue.")
pass

# FIGURE OUT CURR DIR
try:
print "CURENT = %s" % os.listdir(".")
print "PARENT = %s" % os.listdir("..")
print "ABS PATH = %s" % os.path.abspath(".")
print "CURENT = %s" % os.listdir(os.curdir)
print "PARENT = %s" % os.listdir(os.pardir)
except:
strInput = raw_input("Failed os module calls. Hit enter key to end.")
pass

print
strInput = raw_input("Hit enter key to end program")

Through Pythonwin IDE without setting the directory (using Open, or Save
As), I get:


===
CURENT = ['addins', 'AppPatch', 'assembly', 'atl80.dll',  . - snip - . ,
'winsxs', 'WMSysPr9.prx', 'xpsp1hfm.log', '_default.pif']
PARENT = ['$Recycle.Bin', 'autoexec.bat', 'Boot', 'bootmgr', 'BOOTSECT.BAK',
'config.sys', 'Documents and Settings', . - snip - . , 'Program Files',
'ProgramData', 'Python25', . - snip - . , 'System Volume Information',
'temp', 'Users', 'Windows']
ABS PATH = C:\Windows
CURENT = ['addins', 'AppPatch', 'assembly', 'atl80.dll', . - snip - ., ,
'winsxs', 'WMSysPr9.prx', 'xpsp1hfm.log', '_default.pif']
PARENT = ['$Recycle.Bin', 'autoexec.bat', 'Boot', 'bootmgr', 'BOOTSECT.BAK',
'config.sys', 'Documents and Settings', . - snip - . , 'Program Files',
'ProgramData', 'Python25', . - snip - . , 'System Volume Information',
'temp', 'Users', 'Windows']

If I run it using double click on the program through Windows Explorer, I
get:


===
Nothing . the window closes immediately. Despite the except catches.

If I run it from a Command Prompt, by first navigating to the program's
directory and then specifying [ python.exe SandhirFileMonitor.py ], I get:


===
sys:1: DeprecationWarning: Non-ASCII character '\xef' in file
SandhirFileMonitor.py on line 356, but no encoding declared; see
http://www.python.org/peps/pep-0263.html for details
Failed import. Hit enter key to continue.
CURENT = ['Diff.txt', 'Folder2', 'report-templates', 'reports - Copy
(2).html','reports - Copy (3).html', 'reports - Copy (4).html', 'reports -
Copy (5).html', 'reports - Copy.html', 'reports.html',
'SandhirFileBackupUtility - Copy.py', 'SandhirFileBackupUtility.py',
SandhirFileBackupUtility.py - Shortcut.lnk', 'SandhirFileMonitor.py']
PARENT = ['BackupV10', 'BackupV11', 'DayReadiness', 'reporterV70']
ABS PATH =
E:\Data\ActiveData\SandipanPersonalData\FromNODE06\SoftwareBackups\BackupV11
CURENT = ['Diff.txt', 'Folder2', 'report-templates', 'reports - Copy
(2).html', 'reports - Copy (3).html', 'reports - Copy (4).html', 'reports -
Copy (5).html', 'reports - Copy.html', 'reports.html',
'SandhirFileBackupUtility - Copy.py', 'SandhirFileBackupUtility.py',
'SandhirFileBackupUtility.py - Shortcut.lnk', 'SandhirFileMonitor.py']
PARENT = ['BackupV10', 'BackupV11', 'DayReadiness', 'reporterV70']

I am obviously missing something very simple, but I can't figure this out .
it's been a few days now.

Can someone help? Thanks.

Sandipan


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


Re: list index()

2007-09-04 Thread Neil Cerutti
On 2007-09-04, Campbell Barton <[EMAIL PROTECTED]> wrote:
> Jason wrote:
>> Returning -1 is not a good return value to indicate an error.
>> After all, -1 is a valid index in most Python lists.
>> (Negative numbers index from the tail of the list.)
>
> Agree in general tho its a bit inconsistent how...
>
> "string".find(val)
>
> ...can return -1 but .index() cant, though the inconsistency is
> probably with string since most other areas of the py api raise
> errors in cases like this.

The two functions have different ranges, but also different
domains.

sequence.index 
  domain: any item '==' to an item in sequence
  range: All non-negative indexes of sequence

string.find 
  domain: any string
  range: -1 for not found, and all non-negative indexes of string.

If you want to search for subsequences in a sequence, a la
string.find, you can use something like (what I naively assume
will be a maximally efficent):

def find(seq, subseq):
""" Find a subsequence of seq in seq, and return its index. Return -1 if
subseq is not found.

>>> seq = [0, 1, 2, 3, 4, 5]
>>> find(seq, [0, 1, 2])
0
>>> find(seq, [])
0
>>> find(seq, [3, 4])
3
>>> find(seq, [3, 2])
-1
>>> find(seq, [5, 6])
-1
>>> find(seq, [3])
3
>>> find(seq, [0, 2])
-1

"""
i = 0
j = 0
while i < len(seq) and j < len(subseq):
if seq[i] == subseq[j]: 
j += 1
else:
j = 0
i += 1
if j == len(subseq): return i - j
else: return -1

It's probable that a simpler implementation using slice
operations will be faster for shortish lengths of subseq. It was
certainly easier to get it working correctly. ;)

def find(seq, subseq):
  for i, j in itertools.izip(xrange(len(seq)-len(subseq)),
 xrange(len(subseq), len(seq))):
if subseq == seq[i:j]:
  return i
  return -1

-- 
Neil Cerutti
I pulled away from the side of the road, glanced at my mother-in-law and
headed over the embankment. --Insurance Claim Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: So what exactly is a complex number?

2007-09-04 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Steve Holden <[EMAIL PROTECTED]> wrote:

> Roy Smith wrote:
> > Boris Borcic <[EMAIL PROTECTED]> wrote:
> >> Complex numbers are like a subclass of real numbers 
> > 
> > I wouldn't use the term "subclass".  It certainly doesn't apply in the same 
> > sense it applies in OOPLs.  For example, you can't say, "All complex 
> > numbers are real numbers".  In fact, just the opposite.
> > 
> > But, it's equally wrong to say, "real numbers are a subclass of complex 
> > numbers", at least not if you believe in LSP 
> > (http://en.wikipedia.org/wiki/Liskov_substitution_principle).  For example, 
> > it is true that you can take the square root of all complex numbers.  It is 
> > not, however, true that you can take square root of all real numbers.
> > 
> That's not true. I suspect what you are attempting to say is that the 
> complex numbers are closed with respect to the square root operation, 
> but the reals aren't.

Yes, that's what I was trying to say.

> I don't think "subclass" has a generally defined meaning in mathematics 

That may be true, but this is a programming newsgroup, so I was using a 
programming sort of definition.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is overtaking Perl

2007-09-04 Thread Jean-Paul Calderone
On Tue, 04 Sep 2007 00:32:23 -, Ben <[EMAIL PROTECTED]> wrote:
>Here are the statistics from Google Trends:
>
>http://benyang22a.blogspot.com/2007/09/perl-vs-python.html
>

>From the graph, it seems more accurate to say that Perl is undertaking Python.

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


Re: Setting Current Dir in Python

2007-09-04 Thread Tim Couper
"Non-ASCII character '\xef' in file"

SandhirFileMonitor.py on line 356, 

This is reason for the failure .. you have a (probably accidentally placed) 
non-ascii (ie whose value is > 128) character on line 356, whose hex value is 
ef (decimal 259) . Solution: find that line and remove the character - or line.

Tim

Dr Tim Couper
CTO, SciVisum Ltd

www.scivisum.com



Sandipan Gangopadhyay wrote:
> Hi all!
>
> I have utility programs in Python that do clean up, image processing tasks
> on files in a folder. I just drop the program into the folder and run it.
>
> I have been double clicking on a Python program in my Windows XP Home to
> make it run . it sets the program's directory as the current directory when
> it runs.
>
> I have recently installed Python 2.5.1 and Pythonwin (without any errors) on
> Windows Vista Ultimate.
>
> Now, the programs run fine within Pythonwin IDE when current directory is
> set to the program's directory.
>
> But, when I double click them from Windows Explorer, the program is not run.
>
> If I run the following program:
>
> 
> ===
> # MODULE IMPORT
> try:
> import time, os, Image, urllib, string, math, os.path, filecmp, shutil,
> sys
> except:
> strInput = raw_input("Failed import. Hit enter key to continue.")
> pass
>
> # FIGURE OUT CURR DIR
> try:
> print "CURENT = %s" % os.listdir(".")
> print "PARENT = %s" % os.listdir("..")
> print "ABS PATH = %s" % os.path.abspath(".")
> print "CURENT = %s" % os.listdir(os.curdir)
> print "PARENT = %s" % os.listdir(os.pardir)
> except:
> strInput = raw_input("Failed os module calls. Hit enter key to end.")
> pass
>
> print
> strInput = raw_input("Hit enter key to end program")
>
> Through Pythonwin IDE without setting the directory (using Open, or Save
> As), I get:
>
> 
> ===
> CURENT = ['addins', 'AppPatch', 'assembly', 'atl80.dll',  . - snip - . ,
> 'winsxs', 'WMSysPr9.prx', 'xpsp1hfm.log', '_default.pif']
> PARENT = ['$Recycle.Bin', 'autoexec.bat', 'Boot', 'bootmgr', 'BOOTSECT.BAK',
> 'config.sys', 'Documents and Settings', . - snip - . , 'Program Files',
> 'ProgramData', 'Python25', . - snip - . , 'System Volume Information',
> 'temp', 'Users', 'Windows']
> ABS PATH = C:\Windows
> CURENT = ['addins', 'AppPatch', 'assembly', 'atl80.dll', . - snip - ., ,
> 'winsxs', 'WMSysPr9.prx', 'xpsp1hfm.log', '_default.pif']
> PARENT = ['$Recycle.Bin', 'autoexec.bat', 'Boot', 'bootmgr', 'BOOTSECT.BAK',
> 'config.sys', 'Documents and Settings', . - snip - . , 'Program Files',
> 'ProgramData', 'Python25', . - snip - . , 'System Volume Information',
> 'temp', 'Users', 'Windows']
>
> If I run it using double click on the program through Windows Explorer, I
> get:
>
> 
> ===
> Nothing . the window closes immediately. Despite the except catches.
>
> If I run it from a Command Prompt, by first navigating to the program's
> directory and then specifying [ python.exe SandhirFileMonitor.py ], I get:
>
> 
> ===
> sys:1: DeprecationWarning: Non-ASCII character '\xef' in file
> SandhirFileMonitor.py on line 356, but no encoding declared; see
> http://www.python.org/peps/pep-0263.html for details
> Failed import. Hit enter key to continue.
> CURENT = ['Diff.txt', 'Folder2', 'report-templates', 'reports - Copy
> (2).html','reports - Copy (3).html', 'reports - Copy (4).html', 'reports -
> Copy (5).html', 'reports - Copy.html', 'reports.html',
> 'SandhirFileBackupUtility - Copy.py', 'SandhirFileBackupUtility.py',
> SandhirFileBackupUtility.py - Shortcut.lnk', 'SandhirFileMonitor.py']
> PARENT = ['BackupV10', 'BackupV11', 'DayReadiness', 'reporterV70']
> ABS PATH =
> E:\Data\ActiveData\SandipanPersonalData\FromNODE06\SoftwareBackups\BackupV11
> CURENT = ['Diff.txt', 'Folder2', 'report-templates', 'reports - Copy
> (2).html', 'reports - Copy (3).html', 'reports - Copy (4).html', 'reports -
> Copy (5).html', 'reports - Copy.html', 'reports.html',
> 'SandhirFileBackupUtility - Copy.py', 'SandhirFileBackupUtility.py',
> 'SandhirFileBackupUtility.py - Shortcut.lnk', 'SandhirFileMonitor.py']
> PARENT = ['BackupV10', 'BackupV11', 'DayReadiness', 'reporterV70']
>
> I am obviously missing something very simple, but I can't figure this out .
> it's been a few days now.
>
> Can someone help? Thanks.
>
> Sandipan
>
>
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing lists in columns (was: TypeError: 'module object is not callable')

2007-09-04 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

>> But watch out if the lists aren't all the same length: zip won't pad out
>> any sequences, so it maynotbe exactly what is wanted here:
>>
>> >>> x = ['1', '2', '3']
>> >>> y = ['4', '5']
>> >>> for row in zip(x,y):
>>
>> print ', '.join(row)
>>
>> 1, 4
>> 2, 5
>>
> 
> Unfortunately the lists will be of different sizes

In that case use:

from itertools import repeat, chain, izip
def izip_longest(*args, **kwds):
fillvalue = kwds.get('fillvalue')
def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
yield counter() # yields the fillvalue, or raises IndexError
fillers = repeat(fillvalue)
iters = [chain(it, sentinel(), fillers) for it in args]
try:
for tup in izip(*iters):
yield tup
except IndexError:
pass


x = ['1', '2', '3']
y = ['4', '5']
for row in izip_longest(x,y, fillvalue='*'):
print ', '.join(row)


which gives:

1, 4
2, 5
3, *


(izip_longest is in a future version of itertools, but for 
now you have to define it yourself).

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


REGULAR EXPRESSION

2007-09-04 Thread AniNair
hi.. I am trying to match '+ %&/-' etc using regular expression  in
expressions like 879+34343. I tried \W+   but it matches only in the
beginning of the string Plz help Thanking you in advance...

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


Re: Setting Current Dir in Python

2007-09-04 Thread Steve Holden
Tim Couper wrote:
> "Non-ASCII character '\xef' in file"
> 
> SandhirFileMonitor.py on line 356, 
> 
> This is reason for the failure .. you have a (probably accidentally placed) 
> non-ascii (ie whose value is > 128) character on line 356, whose hex value is 
> ef (decimal 259) . Solution: find that line and remove the character - or 
> line.
> 
Tim:

You should know that any two-digit hexadecimal number is less than 255!

 >>> int("ef", 16)
239

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: REGULAR EXPRESSION

2007-09-04 Thread Steve Holden
AniNair wrote:
> hi.. I am trying to match '+ %&/-' etc using regular expression  in
> expressions like 879+34343. I tried \W+   but it matches only in the
> beginning of the string Plz help Thanking you in advance...
> 
Perhaps you could give a few example of strings that should and 
shouldn't match? It isn't clear from your description what pattern you 
are trying to find.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Tkinter(2)

2007-09-04 Thread vijayca
my python installation is:Active python 2.5.1
i am using Red Hat Linux
i have the Tkinter module installed but any simple script produces an
error

script:
from Tkinter import Label
widget = Label(None, text='Hello GUI world!')
widget.pack()
widget.mainloop()


error:
Traceback (most recent call last):
  File "guy.py", line 2, in 
widget = Label(None, text='Hello GUI world!')
  File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/
INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 2464, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
  File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/
INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1923, in __init__
BaseWidget._setup(self, master, cnf)
  File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/
INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1898, in _setup
_default_root = Tk()
  File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/
INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1636, in __init__
self.tk = _tkinter.create(screenName, baseName, className,
interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment
variable


please help me
i hate those error messages...
vijay

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


Calling a dos batch file from python

2007-09-04 Thread n o s p a m p l e a s e
Suppose I have a batch file called mybatch.bat  and I want to run it
from a python script. How can I call this batch file in python script?

Thanx/NSP

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


Re: Printing lists in columns (was: TypeError: 'module object is not callable')

2007-09-04 Thread cjt22
On Sep 4, 2:06 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> >> But watch out if the lists aren't all the same length: zip won't pad out
> >> any sequences, so it maynotbe exactly what is wanted here:
>
> >> >>> x = ['1', '2', '3']
> >> >>> y = ['4', '5']
> >> >>> for row in zip(x,y):
>
> >> print ', '.join(row)
>
> >> 1, 4
> >> 2, 5
>
> > Unfortunately the lists will be of different sizes
>
> In that case use:
>
> from itertools import repeat, chain, izip
> def izip_longest(*args, **kwds):
> fillvalue = kwds.get('fillvalue')
> def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
> yield counter() # yields the fillvalue, or raises IndexError
> fillers = repeat(fillvalue)
> iters = [chain(it, sentinel(), fillers) for it in args]
> try:
> for tup in izip(*iters):
> yield tup
> except IndexError:
> pass
>
> x = ['1', '2', '3']
> y = ['4', '5']
> for row in izip_longest(x,y, fillvalue='*'):
> print ', '.join(row)
>
> which gives:
>
> 1, 4
> 2, 5
> 3, *
>
> (izip_longest is in a future version of itertools, but for
> now you have to define it yourself).

Thanks guys

I have a list of lists such as
 a = ["1" , "2"]  b = ["4", "5", "6"]  c = ["7",8", "9"]
Stored in another list: d = [a,b,c]

I know this makes me sound very stupid but how would I specify
in the parameter the inner lists without having to write them all out
such as:

for row in izip_longest(d[0], d[1], d[2], fillvalue='*'):
print ', '.join(row)

i.e. How could I do the following if I didn't know how many list of
lists I had.
Sorry this sounds stupid and easy.
Thankyou very much in advance as well, you are all very helpful
indeed.

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


Re: Setting Current Dir in Python

2007-09-04 Thread Tim Couper
Steve

Of course it is. I'd like to think I left a test for the observant, but 
in reality it just shows I can't copy-type  ... :-)

Tim


Dr Tim Couper
CTO, SciVisum Ltd

www.scivisum.com



Steve Holden wrote:
> Tim Couper wrote:
>   
>> "Non-ASCII character '\xef' in file"
>>
>> SandhirFileMonitor.py on line 356, 
>>
>> This is reason for the failure .. you have a (probably accidentally placed) 
>> non-ascii (ie whose value is > 128) character on line 356, whose hex value 
>> is ef (decimal 259) . Solution: find that line and remove the character - or 
>> line.
>>
>> 
> Tim:
>
> You should know that any two-digit hexadecimal number is less than 255!
>
>  >>> int("ef", 16)
> 239
>
> regards
>   Steve
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


GC performance with lists

2007-09-04 Thread jonas
While working on some python wrapping, I've run into some problems
where the GC seems to take an unreasonable amount of time to run. The
code below is a demonstration:

import gc
#gc.disable()

data = []
for i in xrange(10):

shortdata = []
for j in range(57):
mytuple = (j, i+1, i+2, i+3, i+4, i+5, i+6)
shortdata.append(mytuple)
data.extend(shortdata)

print len(data)

with gc disabled (the second line) the code runs in 15 seconds, with
it enabled it runs in 2:15, or ~9x slower. I expected some gc
overhead, but not an order of magnitude! Am I doing something
obviously wrong in the above code?

Thanks,
 ...Eric

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


Re: Printing lists in columns

2007-09-04 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
(snip)

> Thanks guys
> 
> I have a list of lists such as
>  a = ["1" , "2"]  b = ["4", "5", "6"]  c = ["7",8", "9"]
> Stored in another list: d = [a,b,c]
> 
> I know this makes me sound very stupid but how would I specify
> in the parameter the inner lists without having to write them all out
> such as:
> 
> for row in izip_longest(d[0], d[1], d[2], fillvalue='*'):
> print ', '.join(row)
> 
> i.e. How could I do the following if I didn't know how many list of
> lists I had.

for row in izip_longest(*d, fillvalue='*'):
 print ', '.join(row)


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


gucci shoes,LV handbag chanel levi's kobe max

2007-09-04 Thread cheapestsell
Cheap sport shoe
www.cheapestsell.com

Hotmail:[EMAIL PROTECTED]
Yahoo: [EMAIL PROTECTED]
www.cheapestsell.com
Nike Air Jordan 1 ,Nike Air Jordan 2 Shoes,Nike Air Jordan 3,Nike Air
Jordan 4 Shoes ,Nike Air Jordan 5 Chaussure Shoes,Nike Air Jordan 6
Catalog ,Nike Air Jordan 7 Shoes Catalog ,
Nike Air Jordan 8 Customized ,Nike Air Jordan 9 Shoes Customized ,Nike
Air Jordan 10 Wholesalers,Nike Jordan 11 Shoes Wholesalers,Nike Air
Jordan 12 retailer,Nike Air Jordan 13 Shoes Factory ,Nike Air Jordan
14 Shoes Sell,Nike Air Jordan 16 Exporter ,Nike Air Jordan 17 Shoes
Exporter, Nike Air Jordan 18 Offer, Nike Air Jordan 19 Shoes
Offer,Nike Air Jordan 20 Manufacture,Nike Jordan 21 Shoes
Manufacture,Nike Jordan 22 CUSTOMIZED ,
We Import&Export&Trading&Retail&sell&buy&distribution& Wholesale Nike
footwear and Nikes Sneakers Jordans Sneakers to this market:
USA,America,US,United States,UK,England,United Kingdom,IT,Italy,
NT,Netherlands,China,Chinese,Germany,DE,Greece,GR,France,
FR,Spain,Portugal,Switzerland,Switzerland,Brazil,Chile,Peru,C
Korea,Australia,Hongkong,Canada,Mexico,Etc
Nike shoes | china nike shoes | air jordan sneakers | cheap gucci
shoes | cheap prada sneakers | gucci sneakers | mix jordan sneakers |
chanel sandals | gucci sandals | dior sandals | wholesale jordan
sneakers |  nike running shoes | nike stock shoes | air jordan at
whlesale price | nike shoes air jordan supplier from in china |
Lacoste Trainers | puma trainers | louis vuitton purse | prada purse
|
gucci handbags | chanel purse | coach purse | nike bas kerball shoes
|
Nike Sneakers| cheap nike sneakers | nike shoes from china | nike
replica | copy nike sneakers |  nike factory stores |  nike stores
Nike wholesale - Nike shoes wholesale
nike jordan sneakers wholesale( www.cheapestsell.com)
We (http: //www.cheapestsell.com)
Wholesale Cheap Jordan
Shoes,Michael
Jordan Shoes,Nike Jordan Basketball shoes, ... Jordan Shoes,Air
Jordan
Sneakers,Air Jordan Wholesale All of the Air Jordan sneakers have
Nike
Air in the shoes.Authentic quality Jordan Sneakers Custom Jordan
Sneakers Wholesale Jordan Sneakers gucci sneakers prada sneakers in
www.cheapestsell.com,lv
chanel coach dior DG DSQUARED2 DIESEL,miumiu handbags
sneakers,shoes,t-
shirts,jeans,jackets.We sale new Nike Sneakers,Air Jordan
Sneakers,AIR
FORCE 1S,Nike Dunks SB,Bape Sta from nike outlets and factory
stores,also Nike wholesale-Jordan Shoes,sneakers! china online store!
Cheap Lacoste Trainers Please,Lacoste Trainers for Women,Lacoste Shoes
Online,Lacoste Shoes for Women,Buy Lacoste Trainers Online,Lacoste
Sneakers(www.cheapestsell.com)
Lacoste Footwear,Black Lacoste Trainers,Lacoste Trinity
Trainers(www.cheapestsell.com)
Lacoste Leisure Shoe, cheap nike dunks,cheap gucci
sneakers(www.cheapestsell.com)
cheap sunglasses factory,wholesale nike  tshirts,cheap air jordans
(www.cheapestsell.com)
nike sb china wholesale,cheap puma sneakers,sneaker wholesale
china,jordans sneakers,gucci shirts wholesale,cheap bape trainers,shoe
wholesalers in china,cheap nike sneakers,DISCOUNT nike SNEAKERS,Tennis
Sneakers,gucci Sneakers, Prada Sneakers,Shoes Jordan's +
Wholesale,jordan wholesale manufacturers,nike customes,cheap wholesale
jordans nike,cheap tiffany necklace,gucci shoes shop,Wholesale
Distributor Authentic Nike Shoes,wholesale air forces and
jordans,dsquared manufacturers,dsquared womens shoes,dsquared2
jeans,dsquared2
shoes
ed hardy caps,ed hardy caps cheap,ed hardy for cheap,ed hardy hats
for
cheap
addidas wholesalers distributor(www.cheapestsell.com)
bulk air force ones for sale(www.cheapestsell.com)
Burberry Handbags made in China(www.cheapestsell.com)
BUY ARMANI SHOES(www.cheapestsell.com)
Buy holesale from china GUCCI(www.cheapestsell.com)
buy jordans made in china(www.cheapestsell.com)
buy nike shoes at wholesale price(www.cheapestsell.com)

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


Re: problem with TreeView + ListStore

2007-09-04 Thread Ali
On Sep 4, 10:43 am, Guillermo Heizenreder <[EMAIL PROTECTED]> wrote:
> Hi list
> I'm developing a application for learn pygkt, and I need to know when a
> user selected or clicked one determinate row of my TreeView for shot
> another signal .

Hi,

Well, ignoring the rest of the post, I can tell you that the usual way
of
doing this is to connect the changed signal of the treeview's
selection.

This explains it better than I would:

http://faq.pygtk.org/index.py?req=show&file=faq13.011.htp

Now to complete your actual use case:

def on_selection_changed(selection, *args):
 model, paths = selection.get_selected_rows()
 if paths:
hbox.show()

treeView = gtk.TreeView()
selection = self.treeView.get_selection()
selection.connect('changed', on_selection_changed)

There are some situations where you may want to actually connect the
mouse click event, and we can discuss them further if you require.

I should of course mention kiwi.ui.objectlist.ObjectList. It is an
easier to use abstraction over TreeView, and has helped me in every
situation where I would use a TreeView.


Ali

> Study the tutorial [1] I began to see the explanation that I see in the
> chapter 14.7. TreeView Signal and found one in particular
> "select-cursor-row", but I don't understood  how implementing.
>
> Something like that.
>if user_selected_row:
>   self.hbox_118.show()
>   print "YES"
>
> NOTE: self.hbox_118 = wTree.get_widget("hbox118")
>
> Thank and Regard
>
> [1]http://www.pygtk.org/pygtk2tutorial/sec-TreeViewSignals.html
>
> P/D: my English it to bad, I'm a novice.
> --
> Heizenreder Guillermohttp://code.google.com/u/gheize/


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


Parse or Pass?

2007-09-04 Thread frenchy64
I'm very confused...I want to describe passing variables to functions
and I've seen these two words used in very similar contexts.

Is there a difference between them?

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


Re: Parse or Pass?

2007-09-04 Thread Steve Holden
frenchy64 wrote:
> I'm very confused...I want to describe passing variables to functions
> and I've seen these two words used in very similar contexts.
> 
> Is there a difference between them?
> 
In general, "parsing" is analyzing the grammatical structure of a 
string. People sometimes talk loosely about "parsing the command line". 
but I don't think that's normally applied to providing the actual 
arguments (corresponding to the definition's "formal parameters") when a 
function is called - that's argument passing.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Printing lists in columns

2007-09-04 Thread cjt22
On Sep 4, 3:20 pm, Bruno Desthuilliers  wrote:
> [EMAIL PROTECTED] a écrit :
> (snip)
>
> > Thanks guys
>
> > I have a list of lists such as
> >  a = ["1" , "2"]  b = ["4", "5", "6"]  c = ["7",8", "9"]
> > Stored in another list: d = [a,b,c]
>
> > I know this makes me sound very stupid but how would I specify
> > in the parameter the inner lists without having to write them all out
> > such as:
>
> > for row in izip_longest(d[0], d[1], d[2], fillvalue='*'):
> > print ', '.join(row)
>
> > i.e. How could I do the following if I didn't know how many list of
> > lists I had.
>
> for row in izip_longest(*d, fillvalue='*'):
>  print ', '.join(row)
>
> HTH

I thought that but when I tried it I recieved a
"Syntax Error: Invalid Syntax"
with a ^ pointing to fillvalue :S

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

Re: Printing lists in columns

2007-09-04 Thread cjt22
On Sep 4, 3:20 pm, Bruno Desthuilliers  wrote:
> [EMAIL PROTECTED] a écrit :
> (snip)
>
> > Thanks guys
>
> > I have a list of lists such as
> >  a = ["1" , "2"]  b = ["4", "5", "6"]  c = ["7",8", "9"]
> > Stored in another list: d = [a,b,c]
>
> > I know this makes me sound very stupid but how would I specify
> > in the parameter the inner lists without having to write them all out
> > such as:
>
> > for row in izip_longest(d[0], d[1], d[2], fillvalue='*'):
> > print ', '.join(row)
>
> > i.e. How could I do the following if I didn't know how many list of
> > lists I had.
>
> for row in izip_longest(*d, fillvalue='*'):
>  print ', '.join(row)
>
> HTH

I thought that, but when I tried it, I recieved a
"Syntax error: invalid syntax"
message with ^ pointing to the 'e' of fillvalue

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

Re: Parse or Pass?

2007-09-04 Thread frenchy64
> In general, "parsing" is analyzing the grammatical structure of a
> string. People sometimes talk loosely about "parsing the command line".
> but I don't think that's normally applied to providing the actual
> arguments (corresponding to the definition's "formal parameters") when a
> function is called - that's argument passing.
>
> regards
>   Steve
Thanks Steve, great post!

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


Re: Calling a dos batch file from python

2007-09-04 Thread kyosohma
On Sep 4, 8:42 am, n o s p a m p l e a s e <[EMAIL PROTECTED]>
wrote:
> Suppose I have a batch file called mybatch.bat  and I want to run it
> from a python script. How can I call this batch file in python script?
>
> Thanx/NSP

The subprocess module should work.

Mike

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


Re: scipy.org website

2007-09-04 Thread Robert Kern
Hiten Madhani wrote:
> Hi,
> 
> The scipy.org website has been down. Does anyone know whether it is 
> coming back up?

It is back up now. We're working on making it more stable. We're getting a lot
more traffic than we used to.

  http://projects.scipy.org/pipermail/scipy-user/2007-September/013573.html

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Printing lists in columns (was: TypeError: 'module object is not callable')

2007-09-04 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> I know this makes me sound very stupid but how would I specify
> in the parameter the inner lists without having to write them all out
> such as:
> 
> for row in izip_longest(d[0], d[1], d[2], fillvalue='*'):
> print ', '.join(row)
> 
> i.e. How could I do the following if I didn't know how many list of
> lists I had.
> Sorry this sounds stupid and easy.
> Thankyou very much in advance as well, you are all very helpful
> indeed.

The variable arguments have to appear last in the call (in the order *x, 
**y if you have both):

>>> a = ["1" , "2"];  b = ["4", "5", "6"];  c = ["7", "8", "9"]
>>> d = [a, b, c]
>>> for row in izip_longest(fillvalue='*', *d):
print ', '.join(row)


1, 4, 7
2, 5, 8
*, 6, 9
>>> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FCGI app reloading on every request

2007-09-04 Thread John Nagle
Michael Ströder wrote:
> John Nagle wrote:
> 
>>What's actually happening is that FCGI isn't running at all.
>>My .fcgi file is being executed by Apache's CGI handler, and
>>"fcgi.py" recognizes this, then reads the parameters as if
>>a CGI program.  So it works just like a CGI program: one
>>load per request.  Not sure why Apache is doing that yet.
>>I'm looking at Apache configuration files now.
> 
> 
> Are you running mod_fastcgi oder mod_fcgid?

I'm using mod_fcgid.

This is running on a dedicated server at APlus.net,
running Red Hat Fedora Core 6, Python 2.5, and managed with Plesk 8.2.
I just turned on fcgid from the Plesk control panel ("Physical hosting
setup page for domain", checked "FastCGI"), and enabled the standard
FCGI configuration, which is actually mod_fcgid.

The Python app is launched from "cgi-bin" with a file ending in
".fcgi".  It uses Alan Saddi's "fcgi.py" module to interface with
an FCGI server.  Python programs that use "fcgi.py" will also run
as standard CGI programs, for debug purposes.  And that's what's
happening.  I modified my test Python program to patch
"fcgi.CGIrequest._end" with a version that logged its calls,
and that's being called.  This indicates that "fcgi.py" is running
in CGI mode, not FCGI mode.  My test program is reloaded for every
HTTP request, as indicated by debug output, so it really is running
in CGI mode, with the expected low performance.

   What's wierd is that the ".fcgi" suffix files get executed at all.
I'd expect them to be either ignored or run properly with FCGI.

John Nagle


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


Re: FCGI app reloading on every request

2007-09-04 Thread Thorsten Kampe
* John Nagle (Mon, 03 Sep 2007 21:26:01 -0700)
> I'm converting a web app from CGI to FCGI.  The application works fine
> under FCGI, but it's being reloaded for every request, which makes FCGI
> kind of pointless.  I wrote a little FCGI app which prints when the program 
> is 
> loaded and when it gets a request.  And indeed, the program gets reloaded for
> each HTTP request.  Something is probably misconfigured.  But what?
> [...]
> On the Python side, I'm using Python 2.5 on Linux, with Alan
> Saddi's "fcgi.py" module.

Do you use fcgi.py or flup? Go for flup


"What's the difference between flup's fcgi module and your previous 
fcgi.py?

Feature-wise, very little, as I do try to keep both implementations in 
sync. The most significant difference is that flup's fcgi module uses 
thread pooling, fcgi.py simply starts a new thread for each 
connection/request. flup's code is refactored and modularized, to 
minimize duplicated code between all 6 servers."

http://trac.saddi.com/flup/wiki/FlupFaq#Whatsthedifferencebetweenflups
fcgimoduleandyourpreviousfcgi.py
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: GC performance with lists

2007-09-04 Thread Zentrader
On Sep 4, 7:06 am, [EMAIL PROTECTED] wrote:
One thing to do is to calc i+1 etc before the j loop instead of on
every iteration.  That is, calculate 600,000 times instead of
6*57*100,000=34,200,00,  And in today's world, it probably won't make
a lot of difference, This is not related to gc but is a good
programming practice IMHO.  Personal preference is to use a varialble
to store the result If I have to calculate something more than twice.


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


Re: REGULAR EXPRESSION

2007-09-04 Thread Tuomas
AniNair wrote:
> hi.. I am trying to match '+ %&/-' etc using regular expression  in
> expressions like 879+34343. I tried \W+   but it matches only in the
> beginning of the string Plz help Thanking you in advance...
> 

Is this what you are seeking for?

 >>> re.compile('(\+{0,1})?([0-9]+)').findall('879+34343')
[('', '879'), ('+', '34343')]

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


Re: How do I get triangles from a vtkPolyData object?

2007-09-04 Thread Grant Edwards
On 2007-09-03, Grant Edwards <[EMAIL PROTECTED]> wrote:

Is there _any_ documentation for the Python bindings to the vtk
library?   I'm still beating my head against a wall trying to
figure out how to get the actual data out of vtk objects when
Python doesn't make visible the required "Get" methods



> I posted this question to the vtk mailing list last week:
>
>   I've been Googling and wandering through the class references
>   most of the afternoon, but I can't figure out how to get the
>   triangles out of the vtkPolyData that vtkDelaunay2D produces?
>
>   I can get the vertex corredinates like this:
>
> delny = vtk.vtkDelaunay2D()
> delny.SetInput(profile)
> delny.SetTolerance(0.001)
> delny.Update()
>
> o = delny.GetOutput()
>
> vertexes = [o.GetPoint(i) for i in xrange(o.GetNumberOfPoints())]
>
>   I can see that there are 84 triangles, and 'o' is a vtkPolyData
>   object that has 84 cells and 84 polygons, so they obviously
>   represent the triangles, but I can't figure out how to get
>   something useful out of the cells or polys.
>
> I got multiple replies telling me that I need to make calls to
> o.GetNextCell().  The posters were even kind enough to include
> examples in C++ showing how to do a delaunay triangulation and
> retrieve the triangle info.

I accidentally left out a step -- it's actually a vtkCellArray
object obtained by calling o.GetPolys() that is missing the
GetCell() and GetNextCell() methods which I need to call.

-- 
Grant Edwards   grante Yow! My mind is a potato
  at   field ...
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter(2)

2007-09-04 Thread Zentrader
On Sep 4, 6:42 am, vijayca <[EMAIL PROTECTED]> wrote:
> my python installation is:Active python 2.5.1
> i am using Red Hat Linux
> i have the Tkinter module installed but any simple script produces an
> error
>
> script:
> from Tkinter import Label
> widget = Label(None, text='Hello GUI world!')
> widget.pack()
> widget.mainloop()
>
> error:
> Traceback (most recent call last):
>   File "guy.py", line 2, in 
> widget = Label(None, text='Hello GUI world!')
>   File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/
> INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 2464, in __init__
> Widget.__init__(self, master, 'label', cnf, kw)
>   File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/
> INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1923, in __init__
> BaseWidget._setup(self, master, cnf)
>   File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/
> INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1898, in _setup
> _default_root = Tk()
>   File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/
> INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1636, in __init__
> self.tk = _tkinter.create(screenName, baseName, className,
> interactive, wantobjects, useTk, sync, use)
> _tkinter.TclError: no display name and no $DISPLAY environment
> variable
>
> please help me
> i hate those error messages...
> vijay

See this example
http://www.pythonware.com/library/tkinter/introduction/hello-tkinter.htm#AEN50
http://www.python-eggs.org/?row=2

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


Re: parameter list notation

2007-09-04 Thread Steven D'Aprano
On Mon, 03 Sep 2007 22:00:28 -0700, TheFlyingDutchman wrote:

> I am trying to use a database written in Python called buzhug.
> 
> In looking at some of the functions I see this prototype:
> 
> def create(self,*fields,**kw):
> 
> I am not clear on what the * and the ** are for or what they represent.
> Or, what are they referred to as so I can do a query for information on
> them.

And yet you're making your own fork of Python.

Good luck with that! Do let us know how it works out for you.

For the record, your question is answered in the FAQ:
http://www.python.org/doc/faq/programming/

and in the tutorial:
http://docs.python.org/tut/node6.html



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


RE: GC performance with lists

2007-09-04 Thread John Krukoff
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of [EMAIL PROTECTED]
> Sent: Tuesday, September 04, 2007 8:07 AM
> To: [email protected]
> Subject: GC performance with lists
> 
> While working on some python wrapping, I've run into some problems
> where the GC seems to take an unreasonable amount of time to run. The
> code below is a demonstration:
> 
> import gc
> #gc.disable()
> 
> data = []
> for i in xrange(10):
> 
> shortdata = []
> for j in range(57):
> mytuple = (j, i+1, i+2, i+3, i+4, i+5, i+6)
> shortdata.append(mytuple)
> data.extend(shortdata)
> 
> print len(data)
> 
> with gc disabled (the second line) the code runs in 15 seconds, with
> it enabled it runs in 2:15, or ~9x slower. I expected some gc
> overhead, but not an order of magnitude! Am I doing something
> obviously wrong in the above code?
> 
> Thanks,
>  ...Eric
> 
> --
> http://mail.python.org/mailman/listinfo/python-list

The only real optimization I see for this is moving the common
subexpressions (i+1, i+2, etc...) out of the loop as previous poster
suggested. 

Something that looks like this, maybe:
data = []
append = data.append
for i in xrange( 10 ):
shortdata = ( i+1, i+2, i+3, i+4, i+5, i+6 )
for j in range( 57 ):
append( ( j, ) + shortdata )

That'll help a little, I just checked the docs to be sure, and collection is
triggered by the number of allocations - number of deallocations going over
a certain threshold (700 by default). 

You do realize just what a massive data structure you're building here, too,
right? On my box, building this consumes about 750Mb of memory. You're doing
a massive number of allocations to create it, too, approximately 40 million.
So, if the gc gets called every 700 allocations, you're spending a lot of
time in the gc, and it's got a huge amount of memory it's sweeping.

It sounds to me like you're triggering worst case behaviour for the gc, and
should either change the threshold values, or simply disable the gc before
the loop and reenable it after. A single gc run at the end probably won't be
so bad as all the intermediate ones, though my box has pretty severe issues
doing anything after creating this data structure as it starts swapping to
disc.

My architechtural suggestion would be to refactor this as an iterator if at
all possible, so as to avoid the massive allocation burden.

-
John Krukoff
[EMAIL PROTECTED]

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


Re: How do I get triangles from a vtkPolyData object?

2007-09-04 Thread Grant Edwards
On 2007-09-04, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2007-09-03, Grant Edwards <[EMAIL PROTECTED]> wrote:
>
> Is there _any_ documentation for the Python bindings to the vtk
> library?   I'm still beating my head against a wall trying to
> figure out how to get the actual data out of vtk objects when
> Python doesn't make visible the required "Get" methods

I found a way to get at the object's "raw data" (a raw list of
floats) and parse out the cell/polygon information, but it's
bafflingly lame that Python doesn't make the normal "Get"
methods available so that one can actually retrieve the
individual cell elements of the vtkCellArray object.

-- 
Grant Edwards   grante Yow! All right, you
  at   degenerates!  I want
   visi.comthis place evacuated in
   20 seconds!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is overtaking Perl

2007-09-04 Thread George Sakkis
On Sep 4, 8:35 am, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Tue, 04 Sep 2007 00:32:23 -, Ben <[EMAIL PROTECTED]> wrote:
> >Here are the statistics from Google Trends:
>
> >http://benyang22a.blogspot.com/2007/09/perl-vs-python.html
>
> >From the graph, it seems more accurate to say that Perl is undertaking 
> >Python.
>
> Jean-Paul

And to make it even more accurate, "Perl is undertaking Python in
India", since that's where the difference in favor of Python comes
from.

George

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


Re: Python is overtaking Perl

2007-09-04 Thread Matimus
> So I think we can at least say from the chart that searches combining
> the terms 'python' and 'programming' have been falling, by some
> unquantifiable amount (it don't _look_ like much!?), relative to the
> number of total searches.

I think it is the search volume relative to the total number of
searches. So, all the decline means is that the number of  searches
for "Python programming" releative to all searches done is declining.
For example, there is a larger number of people searching for things
like "Britney Spears", "Paris Hilton" and "pr0n" than there are for
Python. It is simply a sign that Google is becoming more popular with
the mainstream user, not python, ruby or even perl becoming less
popular.

Matt


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


Re: Printing lists in columns

2007-09-04 Thread Hrvoje Niksic
[EMAIL PROTECTED] writes:

>> for row in izip_longest(*d, fillvalue='*'):
>>  print ', '.join(row)
>>
>> HTH
>
> I thought that but when I tried it I recieved a
> "Syntax Error: Invalid Syntax"
> with a ^ pointing to fillvalue :S

Python isn't too happy about adding individual keyword arguments after
an explicit argument tuple.  Try this instead:

for row in izip_longest(*d, **dict(fillvalue='*')):
 print ', '.join(row)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parse or Pass?

2007-09-04 Thread Martin v. Löwis
> In general, "parsing" is analyzing the grammatical structure of a
> string. People sometimes talk loosely about "parsing the command line".
> but I don't think that's normally applied to providing the actual
> arguments (corresponding to the definition's "formal parameters") when a
> function is called - that's argument passing.

I find that people often use "parsing" in contexts where my
(non-native) language feeling says it should not be used.

For example, people talk about "parsing" trees, meaning that
they perform some processing on the tree with the objective
of extracting certain information. In the same sense, I
have seen people "parsing" lists - meaning they iterate over
the list.

If I extrapolate my experience with German IT language, I
think people often use terminology they have not fully
understood. I often ask my students what the difference
between "eingeben", "ausgeben", "übergeben" und
"zurückgeben" is when they start saying that "die
Funktion gibt das Ergebnis aus".

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


Re: Python is overtaking Perl

2007-09-04 Thread OKB (not okblacke)
George Sakkis wrote:

> On Sep 4, 8:35 am, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>> On Tue, 04 Sep 2007 00:32:23 -, Ben <[EMAIL PROTECTED]>
>> wrote: 
>> >Here are the statistics from Google Trends:
>>
>> >http://benyang22a.blogspot.com/2007/09/perl-vs-python.html
>>
>> >From the graph, it seems more accurate to say that Perl is
>> >undertaking Python. 
>>
>> Jean-Paul
> 
> And to make it even more accurate, "Perl is undertaking Python in
> India", since that's where the difference in favor of Python comes
> from.

No, it's the other way around.  The big difference in India is in 
favor of Perl.

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
--author unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Noob: What is a slot? Me trying to understand another's code

2007-09-04 Thread Carnell, James E


I am thinking about purchasing a book, but wanted to make sure I could
get through the code that implements what the book is about (Artificial
Intelligence a Modern Approach). Anyway, I'm not a very good programmer
and OOP is still sinking in, so please don't answer my questions like I
really know anything.

MY QUESTION:
What is a slot? In class Object below the __init__ has a slot.  Note:
The slot makes use of a data object called 'percept' that is used in the
TableDrivenAgent(Agent) at the bottom of this post. I am guessing this
is a type of Finite State Machine (I haven't bought the book yet so I am
guessing).

MY GUESS AT THE ANSWER:
I've played around with it, and my guess is that is just some data
container local to the instance of Object (after it has been extended or
inherited or whatever). In other words, if I would have made some global
dictionary that each instance of Object and or Agent(Object) could
access it would be possible to allow instances of other classes to
access the global dictionary.

Why not make a class instance have something like a dictionary for
keeping it's own records like self.myListOfActions then you could append
to it etc. I guess it wouldn't be private, but I don't think anything
really is private in python.

Anyway, why a slot (whatever that is)?


class Object:
"""This represents any physical object that can appear in an
Environment.
You subclass Object to get the objects you want.  Each object can
have a
.__name__  slot (used for output only)."""
def __repr__(self):
return '<%s>' % getattr(self, '__name__',
self.__class__.__name__)

def is_alive(self):
"""Objects that are 'alive' should return true."""
return hasattr(self, 'alive') and self.alive

class Agent(Object):
"""An Agent is a subclass of Object with one required slot,
.program, which should hold a function that takes one argument, the
percept, and returns an action. (What counts as a percept or action
will depend on the specific environment in which the agent exists.) 
Note that 'program' is a slot, not a method.  If it were a method,
then the program could 'cheat' and look at aspects of the agent.
It's not supposed to do that: the program can only look at the
percepts.  An agent program that needs a model of the world (and of
the agent itself) will have to build and maintain its own model.
There is an optional slots, .performance, which is a number giving
the performance measure of the agent in its environment."""


# HERE IS THE SLOT ###

def __init__(self):
def program(percept):
return raw_input('Percept=%s; action? ' % percept)
self.program = program
self.alive = True

THIS APPEARS LATER IN THE PROGRAM##
< so you can see where the 'percept' is coming from and how it is being
used.

class TableDrivenAgent(Agent):
"""This agent selects an action based on the percept sequence.
It is practical only for tiny domains.
To customize it you provide a table to the constructor. [Fig.
2.7]"""

def __init__(self, table):
"Supply as table a dictionary of all {percept_sequence:action}
pairs."
## The agent program could in principle be a function, but
because
## it needs to store state, we make it a callable instance of a
class.
Agent.__init__(self)
### percept ##
percepts = []
def program(percept):
percepts.append(percept)
action = table.get(tuple(percepts))
return action
self.program = program


Thanks for your time (and patience),

James Carnell


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


Re: Printing lists in columns

2007-09-04 Thread Miles
On 9/4/07, Hrvoje Niksic wrote:
> Python isn't too happy about adding individual keyword arguments after
> an explicit argument tuple.  Try this instead:
>
> for row in izip_longest(*d, **dict(fillvalue='*')):
>  print ', '.join(row)

Or simply:

for row in izip_longest(fillvalue='*', *d):
print ', '.join(row)

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


Rendering API for python?

2007-09-04 Thread Robert Dailey
Hi,

I'm developing a quick python script to test an algorithm of mine. I would
like to be able to plot the algorithm results to a diagram (much like you
can do in Matlab). I was wondering if there's an API around that would allow
me to quickly do this? Perhaps some sort of rendering API or plotting API
for python? Any help is greatly appreciated. Thanks.

PS: I'm using Python on Windows.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: [Tutor] Code reading for learning Python

2007-09-04 Thread Shawn Milochik
I second the Python Cookbook recommendation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rendering API for python?

2007-09-04 Thread Robert Dailey
Well, I guess I wrote too soon. I found this:
http://matplotlib.sourceforge.net/

I'm going to try it out and see if it is what I'm looking for, however I'm
pretty confident!

On 9/4/07, Robert Dailey <[EMAIL PROTECTED]> wrote:
>
> Hi,
>
> I'm developing a quick python script to test an algorithm of mine. I would
> like to be able to plot the algorithm results to a diagram (much like you
> can do in Matlab). I was wondering if there's an API around that would allow
> me to quickly do this? Perhaps some sort of rendering API or plotting API
> for python? Any help is greatly appreciated. Thanks.
>
> PS: I'm using Python on Windows.
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: FCGI app reloading on every request

2007-09-04 Thread John Nagle
Thorsten Kampe wrote:
> * John Nagle (Mon, 03 Sep 2007 21:26:01 -0700)
> 
>>I'm converting a web app from CGI to FCGI.  The application works fine
>>under FCGI, but it's being reloaded for every request, which makes FCGI
>>kind of pointless.  I wrote a little FCGI app which prints when the program 
>>is 
>>loaded and when it gets a request.  And indeed, the program gets reloaded for
>>each HTTP request.  Something is probably misconfigured.  But what?
>>[...]
>>On the Python side, I'm using Python 2.5 on Linux, with Alan
>>Saddi's "fcgi.py" module.
> 
> 
> Do you use fcgi.py or flup? Go for flup

I think that's irrelevant.  The Python app is being launched in
CGI mode, indicating trouble on the Apache side.

Anything executable in the
cgi-bin directory is being launched as a CGI program.  A file
named "example.foo", if executable, will launch as a CGI program.
Nothing launches with FCGI.

Tried putting this in the .htaccess file:


SetHandler fcgid-script
Options ExecCGI
allow from all



ErrorDocument 403 "File type not supported."


 Even with that, a ".foo" file gets executed as a CGI script,
and so does a ".fcgi" file.  It's an Apache configuration problem.

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


Re: Noob: What is a slot? Me trying to understand another's code

2007-09-04 Thread Gabriel Genellina
En Tue, 04 Sep 2007 15:03:16 -0300, Carnell, James E  
<[EMAIL PROTECTED]> escribi�:

> MY QUESTION:
> What is a slot? In class Object below the __init__ has a slot.  Note:
> The slot makes use of a data object called 'percept' that is used in the
> TableDrivenAgent(Agent) at the bottom of this post. I am guessing this
> is a type of Finite State Machine (I haven't bought the book yet so I am
> guessing).

The authors appear to be using the term in a very general sense - meaning  
"something that has to be filled in".
That is, you (the programmer) is supposed to "fill" the slot with  
meaningful code or data.

> [...] You subclass Object to get the objects you want.  Each object can
> have a .__name__  slot (used for output only).
> [...] An Agent is a subclass of Object with one required slot,
> .program, which should hold a function that takes one argument, the
> percept, and returns an action. Note that 'program' is a slot, not a  
> method.

Here they're trying to bind a simple function (not a method) to a name. I  
don't see the point in forcing things that way, maybe the authors have  
good reasons. But I'd use a staticmethod instead, perhaps.

Note: The C Python source code does use "slots", fields in a structure  
holding function pointers. For example, filling the nb_add slot in a type  
object, one can evaluate a+b for instances of that type.

-- 
Gabriel Genellina

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

Re: Noob: What is a slot? Me trying to understand another's code

2007-09-04 Thread Wildemar Wildenburger
Carnell, James E wrote:
> 
> I am thinking about purchasing a book, but wanted to make sure I could
> get through the code that implements what the book is about (Artificial
> Intelligence a Modern Approach). Anyway, I'm not a very good programmer
> and OOP is still sinking in, so please don't answer my questions like I
> really know anything.
> 
> MY QUESTION:
> What is a slot? In class Object below the __init__ has a slot.  Note:
> The slot makes use of a data object called 'percept' that is used in the
> TableDrivenAgent(Agent) at the bottom of this post. I am guessing this
> is a type of Finite State Machine (I haven't bought the book yet so I am
> guessing).
> 
I really have a hard time grasping what it is you don't understand (the 
annoying thing about not understanding stuff is that you usually lack 
the proper terms to explain what you don't understand, precisely 
_because_ you don't understand it ;)).

At first I thought you were talking about __slots__, as explained in the 
docs http://docs.python.org/ref/slots.html>.

> [but some snipped code later you say:]
> 
> # HERE IS THE SLOT ###
> 
> def __init__(self):
> def program(percept):
> return raw_input('Percept=%s; action? ' % percept)
> self.program = program
> self.alive = True
> 

That is "simply" a special method (namely the one that is called after 
instance creation so you can set up the instance variables).
You should really know that.<\nagging>
Lookie here: http://docs.python.org/ref/customization.html>

Did that do it? Sorry, I have big trouble looking at long listings and 
figuring out their meaning. If that didn't help, try reformulating your 
question (please).

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


Re: Undeterministic strxfrm?

2007-09-04 Thread Gabriel Genellina
En Tue, 04 Sep 2007 07:34:54 -0300, Tuomas <[EMAIL PROTECTED]>  
escribi�:

> Python 2.4.3 (#3, Jun  4 2006, 09:19:30)
> [GCC 4.0.0 20050519 (Red Hat 4.0.0-8)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> import locale
>  >>> def key(s):
> ... locale.setlocale(locale.LC_COLLATE, 'en_US.utf8')
> ... return locale.strxfrm(s.encode('utf8'))
> ...
>  >>> first=key(u'maupassant guy')
>  >>> first==key(u'maupassant guy')
> False
>  >>> first
> '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12
> $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xf5\xb79'
>  >>> key(u'maupassant guy')
> '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12
> $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xb5'
>  >>>
>
> May be this is enough for a sort order but I need to be able to catch
> equals too. Any hints/explanations?

I can't use your same locale, but with my own locale settings, I get  
consistent results:

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit  
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
py> import locale
py> locale.setlocale(locale.LC_COLLATE, 'Spanish_Argentina')
'Spanish_Argentina.1252'
py> def key(s):
...   return locale.strxfrm(s.encode('utf8'))
...
py> first=key(u'maupassant guy')
py> print repr(first)
'\x0eQ\x0e\x02\x0e\x9f\x0e~\x0e\x02\x0e\x91\x0e\x91\x0e\x02\x0ep\x0e\x99\x07\x02
\x0e%\x0e\x9f\x0e\xa7\x01\x01\x01\x01'
py> print repr(key(u'maupassant guy'))
'\x0eQ\x0e\x02\x0e\x9f\x0e~\x0e\x02\x0e\x91\x0e\x91\x0e\x02\x0ep\x0e\x99\x07\x02
\x0e%\x0e\x9f\x0e\xa7\x01\x01\x01\x01'
py> print first==key(u'maupassant guy')
True

Same thing with Python 2.4.4

-- 
Gabriel Genellina

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

Re: gucci shoes,LV handbag chanel levi's kobe max

2007-09-04 Thread Zentrader
Reported as spam

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


Re: GC performance with lists

2007-09-04 Thread Zentrader
On Sep 4, 9:27 am, "John Krukoff" <[EMAIL PROTECTED]> wrote:
> > -Original Message-
> > From: [EMAIL PROTECTED] [mailto:python-
> > [EMAIL PROTECTED] On Behalf Of [EMAIL PROTECTED]
> > Sent: Tuesday, September 04, 2007 8:07 AM
> > To: [EMAIL PROTECTED]
> > Subject: GC performance with lists
>
> > While working on some python wrapping, I've run into some problems
> > where the GC seems to take an unreasonable amount of time to run. The
> > code below is a demonstration:
>
> > import gc
> > #gc.disable()
>
> > data = []
> > for i in xrange(10):
>
> > shortdata = []
> > for j in range(57):
> > mytuple = (j, i+1, i+2, i+3, i+4, i+5, i+6)
> > shortdata.append(mytuple)
> > data.extend(shortdata)
>
> > print len(data)

Isn't this the type of program that psyco is supposed to do well
with?  Perhaps someone else knows a little bit more.

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


Sort of an odd way to debug...

2007-09-04 Thread xkenneth
All,

Sorry for the vague topic, but I really didn't know how to
describe what I want to do. I'd like to almost do a traceback of my
code for debugging and I thought this would be a really cool way to do
it if possible.

What I'd like to do, is define a base class. This base class would
have a function, that gets called every time another function is
called (regardless of whether in the base class or a derived class),
and prints the doc string of each function whenever it's called. I'd
like to be able to do this without explicitly specifying the function
inside all of the other functions of a base class or derived class.

Here's what I think it would look like:

class Base:
 __init__(self,debug=False):
if debug:
self.debug = debug

 def functionThatAlwaysGetsCalled(self):
   print self.__docstring__

class Derived(Base):
"""This function prints something"""
def printSometing(something)
 #ghost function get's called here
 print something

Output would be:
This function prints something
something

Thanks for any help!

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


Questions on FOX GUI and Python

2007-09-04 Thread Kenneth McDonald
Would anyone care to offer their opinions as to using Python with the 
FOX GUI toolkit? Ease of use, stability, power,
speed, etc., all thoughts would be appreciated.


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


Re: Sort of an odd way to debug...

2007-09-04 Thread Chris Mellon
On 9/4/07, xkenneth <[EMAIL PROTECTED]> wrote:
> All,
>
> Sorry for the vague topic, but I really didn't know how to
> describe what I want to do. I'd like to almost do a traceback of my
> code for debugging and I thought this would be a really cool way to do
> it if possible.
>
> What I'd like to do, is define a base class. This base class would
> have a function, that gets called every time another function is
> called (regardless of whether in the base class or a derived class),
> and prints the doc string of each function whenever it's called. I'd
> like to be able to do this without explicitly specifying the function
> inside all of the other functions of a base class or derived class.
>
> Here's what I think it would look like:
>
> class Base:
>  __init__(self,debug=False):
> if debug:
> self.debug = debug
>
>  def functionThatAlwaysGetsCalled(self):
>print self.__docstring__
>
> class Derived(Base):
> """This function prints something"""
> def printSometing(something)
>  #ghost function get's called here
>  print something
>
> Output would be:
> This function prints something
> something
>
> Thanks for any help!
>

This approach won't work, because you need cooperation from child
classes to trigger your  printing. A trace function (see sys.settrace)
is probably more useful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Setting Current Dir in Python

2007-09-04 Thread Gabriel Genellina
En Tue, 04 Sep 2007 09:12:22 -0300, Sandipan Gangopadhyay  
<[EMAIL PROTECTED]> escribi�:

> I have recently installed Python 2.5.1 and Pythonwin (without any  
> errors) on
> Windows Vista Ultimate.
>
> Now, the programs run fine within Pythonwin IDE when current directory is
> set to the program's directory.
>
> But, when I double click them from Windows Explorer, the program is not  
> run.

First, fix your source code (either removing the non-ascii character or  
adding an encoding line at the top, see  
) (PEP0263 is enforced from  
Python 2.5 and up; you got a warning on earlier versions).

os.getcwd() returns the current directory.
os.chdir() changes the current directory.
A shortcut on the desktop may use the desktop itself as the initial  
directory.
If you want to run your script from within the same directory as it  
resides, try this:
os.chdir(os.path.dirname(__file__))


-- 
Gabriel Genellina

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

Re: REGULAR EXPRESSION

2007-09-04 Thread Jonathan Gardner
On Sep 4, 6:32 am, AniNair <[EMAIL PROTECTED]> wrote:
> hi.. I am trying to match '+ %&/-' etc using regular expression  in
> expressions like 879+34343. I tried \W+   but it matches only in the
> beginning of the string Plz help Thanking you in advance...

You may want to read the page describing the regex syntax a little
closer. http://docs.python.org/lib/re-syntax.html

\W would match anything but \w. That is, it would match spaces and
tabs as well as the weird characters. I don't think that's what you
want.

Also, don't forget to use raw strings. r"\W+" is preferred over "\W+".

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


Re: Undeterministic strxfrm?

2007-09-04 Thread Tuomas
Gabriel Genellina wrote:
> En Tue, 04 Sep 2007 07:34:54 -0300, Tuomas 
> <[EMAIL PROTECTED]>  escribi�:
> 
>> Python 2.4.3 (#3, Jun  4 2006, 09:19:30)
>> [GCC 4.0.0 20050519 (Red Hat 4.0.0-8)] on linux2
>> Type "help", "copyright", "credits" or "license" for more information.
>>  >>> import locale
>>  >>> def key(s):
>> ... locale.setlocale(locale.LC_COLLATE, 'en_US.utf8')
>> ... return locale.strxfrm(s.encode('utf8'))
>> ...
>>  >>> first=key(u'maupassant guy')
>>  >>> first==key(u'maupassant guy')
>> False
>>  >>> first
>> '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12
>> $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xf5\xb79'
>>  
>>
>>  >>> key(u'maupassant guy')
>> '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12
>> $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xb5'
>>  
>>
>>  >>>
>>
>> May be this is enough for a sort order but I need to be able to catch
>> equals too. Any hints/explanations?
> 
> 
> I can't use your same locale, but with my own locale settings, I get  
> consistent results:
> 
> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit  
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
> py> import locale
> py> locale.setlocale(locale.LC_COLLATE, 'Spanish_Argentina')
> 'Spanish_Argentina.1252'
> py> def key(s):
> ...   return locale.strxfrm(s.encode('utf8'))
> ...

Because I am writing a multi language application I need to plase the 
locale setting inside the key function. Actually I am implementing 
binary search in a locally sorted list of strings and should be able to 
count on stable results of strxfrm despite possibly visiting another 
locale at meantime. Could repeated calls to setlocale cause some problems?

> py> first=key(u'maupassant guy')
> py> print repr(first)
> '\x0eQ\x0e\x02\x0e\x9f\x0e~\x0e\x02\x0e\x91\x0e\x91\x0e\x02\x0ep\x0e\x99\x07\x02
>  
> 
> \x0e%\x0e\x9f\x0e\xa7\x01\x01\x01\x01'
> py> print repr(key(u'maupassant guy'))
> '\x0eQ\x0e\x02\x0e\x9f\x0e~\x0e\x02\x0e\x91\x0e\x91\x0e\x02\x0ep\x0e\x99\x07\x02
>  
> 
> \x0e%\x0e\x9f\x0e\xa7\x01\x01\x01\x01'
> py> print first==key(u'maupassant guy')
> True
> 
> Same thing with Python 2.4.4
> 

I get the same unstability with my locale 'fi_FI.utf8' too, so I am 
wondering if the source of the problem is the clib or the Python wrapper 
around it. Differences in strxfrm results for identical source are 
allways in the few latest bytes of the results.



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

Re: Printing lists in columns

2007-09-04 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> On Sep 4, 3:20 pm, Bruno Desthuilliers  [EMAIL PROTECTED]> wrote:
> 
>>[EMAIL PROTECTED] a écrit :
>>(snip)
>>
>>
>>>Thanks guys
>>
>>>I have a list of lists such as
>>> a = ["1" , "2"]  b = ["4", "5", "6"]  c = ["7",8", "9"]
>>>Stored in another list: d = [a,b,c]
>>
>>>I know this makes me sound very stupid but how would I specify
>>>in the parameter the inner lists without having to write them all out
>>>such as:
>>
>>>for row in izip_longest(d[0], d[1], d[2], fillvalue='*'):
>>>print ', '.join(row)
>>
>>>i.e. How could I do the following if I didn't know how many list of
>>>lists I had.
>>
>>for row in izip_longest(*d, fillvalue='*'):
>> print ', '.join(row)
>>
>>HTH
> 
> 
> I thought that but when I tried it I recieved a
> "Syntax Error: Invalid Syntax"
> with a ^ pointing to fillvalue :S
> 
Yes, sorry - answered too fast, which is a cardinal sin. The 
func(*sequence) is of course the right answer, but indeed you cannot 
directly pass a keyword arg after it - you must either pass the keyword 
args first:

   izip_longest(fillvalue='*', *d)

or wrap it in a dict and use the ** notation:

   izip_longest(*d, **dict(fillvalue='*'))

In this case, the second solution only makes sens if you already have 
this dict for other reasons.
-- 
http://mail.python.org/mailman/listinfo/python-list


Py3K: Ensuring future compatibility between function annotation based tools

2007-09-04 Thread Ferenczi Viktor
There could be future compatibility issues between libraries using the new 
function annotation scheme: PEP 3107 -- Function Annotations
See also: http://www.python.org/dev/peps/pep-3107/

Let's assume two hypotetic libraries:
mashaller: provides JSON marshalling support
typechecker: provides runtime type checking

Let's write a simple function that uses both libraries:

from marshaller import marshall, JSON
from typechecker import check, Str

@marshall
@check
def splitter(s:Str) -> JSON:
return s.split(',')

The function get a singe string and returns JSON encoded list of it's comma 
separated parts. Both libraries can be used together without problems as long 
as all arguments and the return value are annotated by at most one annotator 
object. However, there could be frequent use cases, when multiple annotations 
for a single argument or return value is required:

@marshall
@check
def splitter(s:(JSON, Str)) -> JSON:
return s.split(',')

The above function does the same as the first one, but accepts a JSON encoded 
string. This solution works only if both libraries can cooperatively handle 
composite annotator objects and do not complain about unknown ones.
(Note, that the order of processing depends on the order of the decorators, 
not on the order of the annotators.)

Let me suggest the following recommendation for tool developers:

If you encounter a tuple as the annotator, then iterate it and process only 
the known ones while silently skipping all others. Keep all existing 
annotators if you include new ones. Create a tuple if you find an existing 
annotator and need to include a second one. Extend existing tuples by 
replacing them with new ones including new annotator(s).
(Possibly lists or dictionaries in place of tuples? I don't think so. Ideas?)

This way all annotation based tools will be compatible and should work 
seamlessly without imposing any unnecessary constraint.
Anybody with a better solution? Any comments?

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


function call

2007-09-04 Thread ianaré
Hey all,

Is there a way of printing out how a function was called? In other
words if I do the following:

def someFunction(self):
self.someOtherFunction(var1, var2)


I would get something like "someOtherFunction: called by:
someFunction, args are: var1, var2"

Thanks in advance

- ianaré

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


doctest and decorators

2007-09-04 Thread Daniel Larsson
Hi,

I assume this is a FAQ, but I couldn't find much helpful information
googling. I'm having trouble with doctest skipping my functions, if I'm
using decorators (that are defined in a separate module). If I'm
understanding what is happening correctly, it's because doctest checks if
the function's func_global attribute is the same as the module's __dict__
attribute. The decorator in question returns a wrapping function, though, so
this check fails.

What are some solutions to this? I can define __test__, but it seems rather
cumbersome.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: function call

2007-09-04 Thread Bruno Desthuilliers
ianaré a écrit :
> Hey all,
> 
> Is there a way of printing out how a function was called? In other
> words if I do the following:
> 
> def someFunction(self):
> self.someOtherFunction(var1, var2)
> 
> 
> I would get something like "someOtherFunction: called by:
> someFunction, args are: var1, var2"
> 
> Thanks in advance
> 
You may be able to solve this using a decorator (to avoid polluting your 
code with this) and the infamous sys._getframe() hack.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: doctest and decorators

2007-09-04 Thread Ferenczi Viktor
> I assume this is a FAQ, but I couldn't find much helpful information
> googling. I'm having trouble with doctest skipping my functions, if I'm
> using decorators (that are defined in a separate module). If I'm
> understanding what is happening correctly, it's because doctest checks if
> the function's func_global attribute is the same as the module's __dict__
> attribute. The decorator in question returns a wrapping function, though,
> so this check fails.
> What are some solutions to this? I can define __test__, but it seems rather
> cumbersome.

Please take a look at the documentation of the functools standard module in 
the Python manual, especially the wraps decorator. It could probably help.

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


Re: function call

2007-09-04 Thread kyosohma
On Sep 4, 3:17 pm, ianaré <[EMAIL PROTECTED]> wrote:
> Hey all,
>
> Is there a way of printing out how a function was called? In other
> words if I do the following:
>
> def someFunction(self):
> self.someOtherFunction(var1, var2)
>
> I would get something like "someOtherFunction: called by:
> someFunction, args are: var1, var2"
>
> Thanks in advance
>
> - ianaré

I think you can use __name__, but I'm not sure how to apply it here.
Read up on Python's introspection tools:

http://www.ibm.com/developerworks/library/l-pyint.html

Mike

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


Re: Undeterministic strxfrm?

2007-09-04 Thread Chris Mellon
On 9/4/07, Tuomas <[EMAIL PROTECTED]> wrote:
> Gabriel Genellina wrote:
> > En Tue, 04 Sep 2007 07:34:54 -0300, Tuomas
> > <[EMAIL PROTECTED]>  escribi�:
> >
> >> Python 2.4.3 (#3, Jun  4 2006, 09:19:30)
> >> [GCC 4.0.0 20050519 (Red Hat 4.0.0-8)] on linux2
> >> Type "help", "copyright", "credits" or "license" for more information.
> >>  >>> import locale
> >>  >>> def key(s):
> >> ... locale.setlocale(locale.LC_COLLATE, 'en_US.utf8')
> >> ... return locale.strxfrm(s.encode('utf8'))
> >> ...
> >>  >>> first=key(u'maupassant guy')
> >>  >>> first==key(u'maupassant guy')
> >> False
> >>  >>> first
> >> '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12
> >> $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xf5\xb79'
> >>
> >>  >>> key(u'maupassant guy')
> >> '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12
> >> $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xb5'
> >>
> >>  >>>
> >>
> >> May be this is enough for a sort order but I need to be able to catch
> >> equals too. Any hints/explanations?
> >
> >
> > I can't use your same locale, but with my own locale settings, I get
> > consistent results:
> >
> > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
> > (Intel)] on
> > win32
> > Type "help", "copyright", "credits" or "license" for more information.
> > py> import locale
> > py> locale.setlocale(locale.LC_COLLATE, 'Spanish_Argentina')
> > 'Spanish_Argentina.1252'
> > py> def key(s):
> > ...   return locale.strxfrm(s.encode('utf8'))
> > ...
>
> Because I am writing a multi language application I need to plase the
> locale setting inside the key function. Actually I am implementing
> binary search in a locally sorted list of strings and should be able to
> count on stable results of strxfrm despite possibly visiting another
> locale at meantime. Could repeated calls to setlocale cause some problems?
>
> > py> first=key(u'maupassant guy')
> > py> print repr(first)
> > '\x0eQ\x0e\x02\x0e\x9f\x0e~\x0e\x02\x0e\x91\x0e\x91\x0e\x02\x0ep\x0e\x99\x07\x02
> >
> > \x0e%\x0e\x9f\x0e\xa7\x01\x01\x01\x01'
> > py> print repr(key(u'maupassant guy'))
> > '\x0eQ\x0e\x02\x0e\x9f\x0e~\x0e\x02\x0e\x91\x0e\x91\x0e\x02\x0ep\x0e\x99\x07\x02
> >
> > \x0e%\x0e\x9f\x0e\xa7\x01\x01\x01\x01'
> > py> print first==key(u'maupassant guy')
> > True
> >
> > Same thing with Python 2.4.4
> >
>
> I get the same unstability with my locale 'fi_FI.utf8' too, so I am
> wondering if the source of the problem is the clib or the Python wrapper
> around it.

Looking at the python source, the only possible error case I can see
is that the wrapper assumes the string returned by strxfrm will be
null terminated.

It's not 100% clear from the documentation I have that the string is
guaranteed to be null terminated, although it's implied, so this is a
remotely possible case. You might try calling the clib directly.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: pyPortMidi

2007-09-04 Thread daz.diamond
Cappy2112 wrote:
> Does anyone here use pyPortMidi- in particular for Sending/receiving
> sysex?
> 

I'm starting to, but then I lurk more than I know ...

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


Re: function call

2007-09-04 Thread Bruno Desthuilliers
Bruno Desthuilliers a écrit :
> ianaré a écrit :
> 
>> Hey all,
>>
>> Is there a way of printing out how a function was called? In other
>> words if I do the following:
>>
>> def someFunction(self):
>> self.someOtherFunction(var1, var2)
>>
>>
>> I would get something like "someOtherFunction: called by:
>> someFunction, args are: var1, var2"
>>
>> Thanks in advance
>>
> You may be able to solve this using a decorator (to avoid polluting your 
> code with this) and the infamous sys._getframe() hack.

Not even with sys._getframe in fact - or at least not directly !-)


import inspect

def trace(func):
 def traced(*args, **kw):
 f = inspect.currentframe(1)
 caller = inspect.getframeinfo(f)[2]
 print "%s : called by %s with %s %s" \
   % (caller, func.__name__, str(args), kw)
 return func(*args, **kw)
 return traced

@trace
def test(toto, tata=None):
 return 42

def call(toto):
 return test(toto, 24)

call("foo")

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


Re: parameter list notation

2007-09-04 Thread Steven D'Aprano
On Mon, 03 Sep 2007 22:10:41 -0700, TheFlyingDutchman wrote:

> Well I did a search on "Python variable length arguments" and found a
> hit that seems to explain the *fields parameter:
> 
> When you declare an argment to start with '*', it takes the argument
> list into an array.

No it doesn't. 

>>> def test(*args):
... import array
... assert type(args) is array.array, "Not an array"
...
>>> test(1, 2, 3)
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in test
AssertionError: Not an array




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


Re: function call

2007-09-04 Thread Chris Mellon
On 9/3/07, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> ianaré a écrit :
> > Hey all,
> >
> > Is there a way of printing out how a function was called? In other
> > words if I do the following:
> >
> > def someFunction(self):
> > self.someOtherFunction(var1, var2)
> >
> >
> > I would get something like "someOtherFunction: called by:
> > someFunction, args are: var1, var2"
> >
> > Thanks in advance
> >
> You may be able to solve this using a decorator (to avoid polluting your
> code with this) and the infamous sys._getframe() hack.
> --

Every reasonable use case for this (and several unreasonable ones)
that I've encountered (and some that I've just imagined) can be better
addressed with a trace function (sys.set_trace) than by trying to do
this at the point of call.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: doctest and decorators

2007-09-04 Thread Daniel Larsson
On 9/4/07, Ferenczi Viktor <[EMAIL PROTECTED]> wrote:
>
> > I assume this is a FAQ, but I couldn't find much helpful information
> > googling. I'm having trouble with doctest skipping my functions, if I'm
> > using decorators (that are defined in a separate module). If I'm
> > understanding what is happening correctly, it's because doctest checks
> if
> > the function's func_global attribute is the same as the module's
> __dict__
> > attribute. The decorator in question returns a wrapping function,
> though,
> > so this check fails.
> > What are some solutions to this? I can define __test__, but it seems
> rather
> > cumbersome.
>
> Please take a look at the documentation of the functools standard module
> in
> the Python manual, especially the wraps decorator. It could probably help.
>


Hmm, not really.

# decorator.py
import functools

def simplelog(f):
@functools.wraps
def new_f(*args, **kwds):
print "Wrapper calling func"
return f(*args, **kwds)
return new_f

# test.py
from decorator import simplelog

@simplelog
def test():
"""
>>> test()
'works!'
"""
return "works!"

if __name__ == '__main__':
import doctest
doctest.testmod()

$ python test.py -v
1 items had no tests:
__main__
0 tests in 1 items.
0 passed and 0 failed.
Test passed.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: function call

2007-09-04 Thread Bruno Desthuilliers
Chris Mellon a écrit :
> On 9/3/07, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> 
>>ianaré a écrit :
>>
>>>Hey all,
>>>
>>>Is there a way of printing out how a function was called? In other
>>>words if I do the following:
>>>
>>>def someFunction(self):
>>>self.someOtherFunction(var1, var2)
>>>
>>>
>>>I would get something like "someOtherFunction: called by:
>>>someFunction, args are: var1, var2"
>>>
>>>Thanks in advance
>>>
>>
>>You may be able to solve this using a decorator (to avoid polluting your
>>code with this) and the infamous sys._getframe() hack.
>>--
> 
> 
> Every reasonable use case for this (and several unreasonable ones)
> that I've encountered (and some that I've just imagined) can be better
> addressed with a trace function (sys.set_trace) than by trying to do
> this at the point of call.

Indeed. Thanks for the correction.


relevant doc here:
http://docs.python.org/lib/debugger-hooks.html

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


Re: Undeterministic strxfrm?

2007-09-04 Thread Peter Otten
Am Tue, 04 Sep 2007 19:54:57 + schrieb Tuomas:

> I get the same unstability with my locale 'fi_FI.utf8' too, so I am 
> wondering if the source of the problem is the clib or the Python wrapper 
> around it. Differences in strxfrm results for identical source are 
> allways in the few latest bytes of the results.

Python seems to be the culprit as there is a relatively recent
strxfrm-related bugfix, see

http://svn.python.org/view/python/trunk/Modules/_localemodule.c?rev=54669

If I understand it correctly the error makes it likely that the resulting
string has trailing garbage characters.

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


Re: Does shuffle() produce uniform result ?

2007-09-04 Thread Steven D'Aprano
On Mon, 03 Sep 2007 23:42:56 -0700, Paul Rubin wrote:

> Antoon Pardon <[EMAIL PROTECTED]> writes:
>> > No the idea is that once there's enough entropy in the pool to make
>> > one encryption key (say 128 bits), the output of /dev/urandom is
>> > computationally indistinguishable from random output no matter how
>> > much data you read from it.
>> 
>> If you were talking about /dev/random I would agree. But this is what
>> the man page on my system says about /dev/urandom. ...
>>the returned values are theoretically vulnerable to a
>>cryptographic attack on the algorithms used by the driver.
> 
> Right.  The idea is that those attacks don't exist and therefore the
> output is computationally indistinguishable from random.

It is a huge leap from what the man page says, that they don't exist in 
the unclassified literature at the time the docs were written, to what 
you're saying, that they don't exist.

The man page is clear: there is a possible vulnerability in /dev/urandom. 
Any cryptographer worth his salt (pun intended) would be looking to close 
that vulnerability BEFORE an attack is made public, and not just wait for 
the attack to trickle down from the NSA to the script kiddies. The time 
to close the stable door is _before_ the horse gets away.


> Of course
> whether the idea is correct, an unproven conjecture, but it looks pretty
> good; certainly finding any problem with the specific algorithms in
> urandom would be a significant research discovery and not likely to
> affect the application being discussed.

I agree that this flaw doesn't sound like it will effect the application 
being discussed, but a problem has already been found and a solution is 
already known: block until there's enough entropy. That's what /dev/
random does.


[snip]
 
> In short, using /dev/random is fairly silly once you know there's enough
> entropy in the randomness pool to make a good key.  If /dev/urandom's
> algorithms are broken then whatever you're doing with the /dev/random
> output is probably also broken.

That doesn't follow. Antoon is specifically warning that /dev/urandom is 
non-blocking. If you knew there was enough entropy available, you 
wouldn't need /dev/random -- but how do you know there's enough entropy?

(I suppose you could look in /proc/sys/kernel/random/entropy_avail.)

For this specific application, it probably doesn't matter -- using /dev/
urandom is surely overkill, and on a single-user Linux desktop you're 
unlikely to have vast numbers of applications reading /dev/urandom 
without your knowledge. But why not use /dev/random? What's the downside?



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


Re: doctest and decorators

2007-09-04 Thread Ferenczi Viktor
> @functools.wraps

Correctly:

@functools.wraps(f)

Pass the function to be wrapped by the decorator to the wraps function.

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


Re: function call

2007-09-04 Thread Steven D'Aprano
On Tue, 04 Sep 2007 13:17:39 -0700, ianaré wrote:

> Hey all,
> 
> Is there a way of printing out how a function was called? In other words
> if I do the following:
> 
> def someFunction(self):
> self.someOtherFunction(var1, var2)
> 
> 
> I would get something like "someOtherFunction: called by: someFunction,
> args are: var1, var2"

The obvious way is:

def someFunction(self):
print "someOtherFunction: called by: someFunction," \
"args are: %s, %s" % (var1, var2)
self.someOtherFunction(var1, var2)

but that has obvious inconveniences. 

Perhaps you should look at the Python debugger and profiler? Do they 
solve the underlying problem you are trying to solve?



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

Re: Looking for Delaunay triangulation module...

2007-09-04 Thread Grant Edwards
On 2007-09-03, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2007-09-02, Robert Kern <[EMAIL PROTECTED]> wrote:
>
>>> Can anybody point me to a Delaunay triangulation module (for
>>> Win32)?  I'm currently using
>>> http://flub.stuffwillmade.org/delny/ under Linux, but I have
>>> been unable to find a build for Windows. I don't have the
>>> tools (or skills) to build libqhull and Python extensions on
>>> Win32).
>>> 
>>> I've also found the delaunay module in scipy's "sandbox".  I
>>> could never get that module to work under Linux, and I can't
>>> build it for Windows anyway.

> I do have Dlaunay triangulation working using VTK (which is
> included in Enthought Python),

Well, of course that doesn't work under Windows either. Doing
an "import vtk" crashes the python interpreter.

How people get any work at all done using Winodows is beyond me...

-- 
Grant Edwards   grante Yow! Everybody gets free
  at   BORSCHT!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FCGI app reloading on every request

2007-09-04 Thread Martin v. Löwis
>Anything executable in the
> cgi-bin directory is being launched as a CGI program.  A file
> named "example.foo", if executable, will launch as a CGI program.
> Nothing launches with FCGI.

Perhaps you have a SetHandler declaration somewhere that makes all
files CGI by default? I would advise against Sethandler, and
recommend AddHandler instead.

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


Re: doctest and decorators

2007-09-04 Thread Daniel Larsson
On 9/4/07, Ferenczi Viktor <[EMAIL PROTECTED]> wrote:
>
> > @functools.wraps
>
> Correctly:
>
> @functools.wraps(f)
>
> Pass the function to be wrapped by the decorator to the wraps function.


Ooops, right. That doesn't change the fact that decorated functions get
hidden from doctest though.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: parameter list notation

2007-09-04 Thread TheFlyingDutchman
On Sep 4, 1:53 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Mon, 03 Sep 2007 22:10:41 -0700, TheFlyingDutchman wrote:
> > Well I did a search on "Python variable length arguments" and found a
> > hit that seems to explain the *fields parameter:
>
> > When you declare an argment to start with '*', it takes the argument
> > list into an array.
>
> No it doesn't.
>
> >>> def test(*args):
>
> ... import array
> ... assert type(args) is array.array, "Not an array"
> ...>>> test(1, 2, 3)
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 3, in test
> AssertionError: Not an array

Oh, I forgot the context of the discussion! As you are well aware, my
Python fork() (which I am now calling PIEthun 3.01 in beta and PIEthun
3000 upon release) has made a few changes. Tuples are known as arrays.
Lists are known as uarrays (for updatable array) and the array module
has been renamed to homo_uarray (homogenous_updatable_array was just
too much typing).

In the future I will be sure to specify the context of my statements -
whether PIEthunic or Pythonic in nature.


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


Re: doctest and decorators

2007-09-04 Thread Ferenczi Viktor
> > @functools.wraps(f)
> > Pass the function to be wrapped by the decorator to the wraps function.
> Ooops, right. That doesn't change the fact that decorated functions get
> hidden from doctest though.

Run my test script (one file) with the -v (verbose) option. Without the -v 
option it does not show output. This fact is documented in the Python manual 
at the doctest module.

--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- 
import functools

def simplelog(f):
@functools.wraps(f)
def new_f(*args, **kwds):
print "Wrapper calling func"
return f(*args, **kwds)
return new_f

@simplelog
def test():
"""
>>> test()
Wrapper calling func
'works!'
"""
return 'works!'

def fn():
"""
>>> fn()
'ok'
"""
return 'ok'

if __name__ == '__main__':
import doctest
doctest.testmod()
--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- 

Regard, Viktor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function call

2007-09-04 Thread ianaré
> > Every reasonable use case for this (and several unreasonable ones)
> > that I've encountered (and some that I've just imagined) can be better
> > addressed with a trace function (sys.set_trace) than by trying to do
> > this at the point of call.
>
> Indeed. Thanks for the correction.
>
> 
> relevant doc here:http://docs.python.org/lib/debugger-hooks.html
> 

Thanks for your help. I was hoping to see a quick and easy way to do
this, so this was helpful for this particular situation. I did not
want to set up a debugger, although I am aware it's the "correct"
thing to do ...

Cheers!


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


  1   2   >