Nagare web framework - 0.1.0

2008-09-25 Thread Alain Poirier
Hi all,

I'm pleased to announce that the first (0.1.0) version
of the Nagare web framework is released!

To read about its features:
http://www.nagare.org/trac/wiki/NagareFeatures
Release info and download page:
 http://pypi.python.org/pypi/nagare/
Source and documentation are available at the website:
 http://www.nagare.org
Mailing lists:
 http://groups.google.com/group/nagare-users

About Nagare


Nagare is a components based framework: a Nagare application
is a composition of interacting components each one with its
own state and workflow kept on the server. Each component
can have one or several views that are composed to generate
the final web page. This enables the developers to reuse or
write highly reusable components easily and quickly.

Thanks to Stackless Python, Nagare is also a continuation-based
web framework which enables to code a web application like a
desktop application, with no need to split its control flow in
a multitude of controllers and with the automatic handling of
the back, fork and refresh actions from the browser.

Its component model and use of the continuation come from the
famous Seaside SmallTalk framework.

Enjoy!

A. Poirier

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: Off topic: Sent from my Foo messages

2008-09-25 Thread Steven D'Aprano
On Wed, 24 Sep 2008 20:04:14 -0700, Sean DiZazzo wrote:

 --
 Steven
 
 I don't appreciate the two lines you put above your name in your posts. 
 Please remove them in the future.

I don't like them either, but it is an email and Usenet standard to 
separate the body of your post from the signature with -- . I'm afraid 
that as obnoxious as the dashes are, leaving them out would be much worse.



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


Re: Time.sleep(0.0125) not available within Linux

2008-09-25 Thread Steven D'Aprano
On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote:

 Just a thought, your minimum sleep time is probably limited by the
 resolution of the system HZ clock. Type
 
 less /proc/config.gz


$ less /proc/config.gz
/proc/config.gz: No such file or directory


What OS are you using?



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


Re: curses.setsyx()?

2008-09-25 Thread Tim Roberts
[EMAIL PROTECTED] wrote:

On Sep 23, 4:16 pm, [EMAIL PROTECTED] wrote:
 On Sep 22, 11:24 pm, Tim Roberts [EMAIL PROTECTED] wrote:
  [EMAIL PROTECTED] wrote:
  On Sep 19, 6:42 pm, [EMAIL PROTECTED] wrote:
   On Sep 19, 1:24 am, Tim Roberts [EMAIL PROTECTED] wrote:

[EMAIL PROTECTED] wrote:

I tried curses.setsyx(2,3) in my script and it doesn't move the 
curses
cursor. Any alternatives/solutions?
...
   I added it and it still doesn't work. This is what I'm doing when I
   want to display the cursor and prepare it for input at 2,3:

   curses.echo()
   curses.curs_set(1)
   curses.setsyx(2,3)
   curses.doupdate()

  Any idea what's wrong?

 http://pastebin.com/m6413db1

 Run that and press 'n' key. It is supposed to move the cursor to 2,3
 and it doesn't.

Of course it does.  It moves the cursor, then does an update, then
immediately calls draw.game, which redraws the screen and moves the cursor.
If you want curses.setsyx (or the equivalent and more mnemonic scr.move) to
leave the cursor somewhere, you can't draw more text afterward.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza  Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: is decorator the right thing to use?

2008-09-25 Thread Diez B. Roggisch

Dmitry S. Makovey schrieb:

Dmitry S. Makovey wrote:

In my real-life case A is a proxy to B, C and D instances/objects, not
just one. 


forgot to mention that above would mean that I need to have more than one
decorator function like AproxyB, AproxyC and AproxyD or make Aproxy smarter
about which property of A has instance of which class etc. 


Unless I'm totally out for lunch and there are better ways of implementing
this (other than copy-pasting stuff whenever anything in B, C or D
changes).


__getattr__?

class Proxy(object):


def __init__(self, delegate):
self._delegate = delegate


def __getattr__(self, attr):
v = getattr(self._delegate, attr)
if callable(v):
   class CallInterceptor(object):
 def __init__(self, f):
 self._f = f

 def __call__(self, *args, **kwargs):
 print Called  + str(self._f) +  with  + 
str(args) + str(kwargs)

 return self._f(*args, **kwargs)
   return CallInterceptor(v)
return v


Decorators have *nothing* to do with this. They are syntactic sugar for


def foo(...):
...

foo = a_decorator(foo)

Nothing less, nothing more.

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


Re: How to parse a string completely into a list

2008-09-25 Thread Tino Wildenhain

[EMAIL PROTECTED] wrote:

On Sep 24, 10:12 pm, Matt Nordhoff [EMAIL PROTECTED] wrote:

[EMAIL PROTECTED] wrote:

On Sep 24, 9:44 pm, Chris Rebert [EMAIL PROTECTED] wrote:



Could you please define exactly what you mean by elements of a string?
If you mean characters, then just use list(): list(  \n \t abc)
[' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c']
Regards,
Chris

Worked like a charm.
kudos!

Why do you need to convert it to a list? Strings are sequences, so you
can do things like slice them or iterate through them by character:


for character in foo:

... print character
...
f
o
o

--


The string draws a map that I then want to be able to traverse
through. If I can count through the individual characters of a list I
can create an x-y coordinate plane for navigation.


You can 'count' (whatever that means) equally in strings as you do in
lists. As said above, they behave exactly the same. Just strings
are imutable - e.g. you can't change individual parts of them.

Tino



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




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

Re: empty csv file attachments

2008-09-25 Thread Peter Otten
Bobby Roberts wrote:

 I'm new to python but a veteran at programming.  

Hm, your code doesn't show that. The time to read the tutorial would be time
well spend. After that, a quick look at what the standard library has to
offer wouldn't hurt. E. g. reading/writing CSV files is a solved problem in
python ;) 

 This one has me 
 stumped.  I have a simple contact form which the user fills out.  The
 email is sent to the site user as well and it is delivered with the
 content in the body of the email as well in nice order.  I have
 modified my code to also send the content as a csv attachment.  On the
 server, the file is perfectly generated with content.  The attachment,
 however, is completely blank.  Any ideas what that could be?  My code
 snippet is shown below:
 
 
       if int(attachmenttype)==2 or int(attachmenttype)==3:
         for field in ctx.request.field_names():
           if field=='last_name':
             myfilename=ctx.request.field_value(field)+'.txt'
         if myfilename=='':
           myfilename='tempfile.txt'
         mypath= mynewfilepath + '/' + myfilename
         f=open(mypath, 'w')
         mynewstring=''
         counter=0
         for field in ctx.request.field_names():
           if field != 'inquiry_required':
             mynewstring=mynewstring + field +','
         if mynewstring[-1]==',':
           mynewstring=mynewstring[0:len(mynewstring)-1]
         f.write(mynewstring)
         f.write ('\n')
 
         mynewstring=''
         counter=1
         for field in ctx.request.field_names():
           fielddata=ctx.request.field_value(field)
           if counter==1:

Hm, above you skip the field inquiry_required, here you skip the second
field.

             dummydata=0
           else:
             mynewstring=mynewstring + '' + fielddata.replace('','')
 + ','
           counter = counter + 1
         if mynewstring[-1]==',':
           mynewstring=mynewstring[0:len(mynewstring)-1]
         f.write(mynewstring)
         f.write('\n')
         f.close

Your actual problem might be that f.close doesn't close (and therefore
flush) the file, you need to call it with f.close().

         attachments.append('/'.join((ctx.request.library,
 myfilename)))

Hm, is ctx.request.library the same as mynewfilepath?

With some guessing your code becomes (untested)

import csv
import os

if int(attachmenttype) in (2, 3):
filename = 'tempfile.txt'

if last_name in ctx.request.field_names():
last_name = ctx.request.field_value(last_name)
if last_name:
filename = last_name + .txt

path = os.path.join(ctx.request.library, filename)

f = open(path, 'wb')
writer = csv.writer(f)
fieldnames = [field for field in ctx.request.field_names()
  if field != inquiry_required]
writer.writerow(fieldnames)
writer.writerow(ctx.request.field_value(field) for field in fieldnames)
f.close()
attachments.append(path)

The code to build the filename is still clumsy, but to do better I'd have to
know the library you are using. Personally I'd always use tempfile.txt
and be done. This would also avoid fun with last names
like ../../just_testing_file_permissions.

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

Re: Comparing float and decimal

2008-09-25 Thread Tim Roberts
Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:

On Tue, 23 Sep 2008 07:08:07 -0700, Michael Palmer wrote:

  This seems to break the rule that if A is equal to B and B is equal
  to C then A is equal to C.

 I don't see why transitivity should apply to Python objects in general.
 
 Well, for numbers it surely would be a nice touch, wouldn't it. May be
 the reason for Decimal to accept float arguments is that irrational
 numbers or very long rational numbers cannot be converted to a Decimal
 without rounding error, and Decimal doesn't want any part of it. Seems
 pointless to me, though.

Is 0.1 a very long number?  Would you expect ``0.1 == Decimal('0.1')`` to 
be `True` or `False` given that 0.1 actually is

In [98]: '%.50f' % 0.1
Out[98]: '0.1555111512312578270211815834045410'
?

Actually, it's not.  Your C run-time library is generating random digits
after it runs out of useful information (which is the first 16 or 17
digits).  0.1 in an IEEE 784 double is this:

 0.100088817841970012523233890533447265625
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza  Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Connecting to SMB share in python

2008-09-25 Thread Ronnie Kwok
Hello,

I am trying to write a script that copy files from my local machine to a samba
share.

I've notice a library call Pysamba which is a wrapper on smb service but it
requires a compilation of SAMBA with some amendment in order to use it.

Are there alternative method that I could do the same thing?

Thank you for your advise.

ronnie

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


Re: How to parse a string completely into a list

2008-09-25 Thread Tim Roberts
[EMAIL PROTECTED] wrote:

The string draws a map that I then want to be able to traverse
through. If I can count through the individual characters of a list I
can create an x-y coordinate plane for navigation.

Well, the point Matt was making is that traversing through a list and
traversing through a string are the same.

  # Given this:
  s = 'abcde'
  l = ['a','b','c','d','e']

  # These are identical:
  for ch in s:
pass
  for ch in l:
pass

  # And these are identical:
  print s[3]
  print l[3]

Slicing is identical.  Subsetting is identical.  The only difference is
that I can change an element of the list.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza  Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


python sorting 2dim. array ?

2008-09-25 Thread fredo66
hello,
Can someone help me with this:
I have a array like this

 list[rowindex][colomindex]

where rows are the records and colom the fields. If I use the .sort()
method on 'list' the data is sorted on the items of the first colom.
But I want to sort on the second colom as first (and as second
sortfield the first colom).

What is the shortest code for this pls ?

(all fields are text value, first colom is name, second category)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python style: exceptions vs. sys.exit()

2008-09-25 Thread Bruno Desthuilliers

Steven D'Aprano a écrit :

On Wed, 24 Sep 2008 17:11:28 -0400, Ross Ridge wrote:


Plenty of people were quick to say that the exception should be passed
through to the caller.  No one said this behaviour should be documented.
 There may be little practical difference bewteen calling sys.exit()
after printing an error and progating an exception if no one using the
library knows that it could generate that exception in those
circumstances.


That's true, I didn't explicitly say that the library should be 
documented. Nor did I say that it shouldn't be riddled with bugs. There's 
little practical difference between a buggy library and one that raises 
unexpected (i.e. undocumented) exceptions either.


Also note that there are quite a couples cases where the library authors 
themselves cannot predict which exception types may be raised - as soon 
as the library functions expect callback functions, file-like or 
dict-like or whatever-like objects etc, it's the caller's responsability 
to handle the exceptions that may be raised by what *he* passes to the 
library...


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

Re: How to parse a string completely into a list

2008-09-25 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

I want to take a long alpha-numeric string with \n and white-space and
place ALL elements of the string (even individual parts of a long
white-space) into separate list elements. The most common way I've
seen this performed is with the split() function, however I don't
believe that it has the power to do what I am looking for.
Any suggestions?


Did you try passing your string to the list() type ?

Python 2.5.1 (r251:54863, Mar  7 2008, 03:41:45)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type help, copyright, credits or license for more information.
 s = I want to take a long alpha-numeric string with \n and 
white-space and

... place ALL elements of the string (even individual parts of a long
... white-space) into separate list elements. The most common way I've
... seen this performed is with the split() function, however I don't
... believe that it has the power to do what I am looking for.
... Any suggestions?
... thanks
... 

 s
I want to take a long alpha-numeric string with \n and white-space 
and\nplace ALL elements of the string (even individual parts of a 
long\nwhite-space) into separate list elements. The most common way 
I've\nseen this performed is with the split() function, however I 
don't\nbelieve that it has the power to do what I am looking for.\nAny 
suggestions?\nthanks\n

 list(s)
['I', ' ', 'w', 'a', 'n', 't', ' ', 't', 'o', ' ', 't', 'a', 'k', 'e', ' 
', 'a', ' ', 'l', 'o', 'n', 'g', ' ', 'a', 'l', 'p', 'h', 'a', '-', 'n', 
'u', 'm', 'e', 'r', 'i', 'c', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ', 
'w', 'i', 't', 'h', ' ', '\n', ' ', 'a', 'n', 'd', ' ', 'w', 'h', 'i', 
't', 'e', '-', 's', 'p', 'a', 'c', 'e', ' ', 'a', 'n', 'd', '\n', 'p', 
'l', 'a', 'c', 'e', ' ', 'A', 'L', 'L', ' ', 'e', 'l', 'e', 'm', 'e', 
'n', 't', 's', ' ', 'o', 'f', ' ', 't', 'h', 'e', ' ', 's', 't', 'r', 
'i', 'n', 'g', ' ', '(', 'e', 'v', 'e', 'n', ' ', 'i', 'n', 'd', 'i', 
'v', 'i', 'd', 'u', 'a', 'l', ' ', 'p', 'a', 'r', 't', 's', ' ', 'o', 
'f', ' ', 'a', ' ', 'l', 'o', 'n', 'g', '\n', 'w', 'h', 'i', 't', 'e', 
'-', 's', 'p', 'a', 'c', 'e', ')', ' ', 'i', 'n', 't', 'o', ' ', 's', 
'e', 'p', 'a', 'r', 'a', 't', 'e', ' ', 'l', 'i', 's', 't', ' ', 'e', 
'l', 'e', 'm', 'e', 'n', 't', 's', '.', ' ', 'T', 'h', 'e', ' ', 'm', 
'o', 's', 't', ' ', 'c', 'o', 'm', 'm', 'o', 'n', ' ', 'w', 'a', 'y', ' 
', 'I', ', 'v', 'e', '\n', 's', 'e', 'e', 'n', ' ', 't', 'h', 'i', 
's', ' ', 'p', 'e', 'r', 'f', 'o', 'r', 'm', 'e', 'd', ' ', 'i', 's', ' 
', 'w', 'i', 't', 'h', ' ', 't', 'h', 'e', ' ', 's', 'p', 'l', 'i', 't', 
'(', ')', ' ', 'f', 'u', 'n', 'c', 't', 'i', 'o', 'n', ',', ' ', 'h', 
'o', 'w', 'e', 'v', 'e', 'r', ' ', 'I', ' ', 'd', 'o', 'n', ', 't', 
'\n', 'b', 'e', 'l', 'i', 'e', 'v', 'e', ' ', 't', 'h', 'a', 't', ' ', 
'i', 't', ' ', 'h', 'a', 's', ' ', 't', 'h', 'e', ' ', 'p', 'o', 'w', 
'e', 'r', ' ', 't', 'o', ' ', 'd', 'o', ' ', 'w', 'h', 'a', 't', ' ', 
'I', ' ', 'a', 'm', ' ', 'l', 'o', 'o', 'k', 'i', 'n', 'g', ' ', 'f', 
'o', 'r', '.', '\n', 'A', 'n', 'y', ' ', 's', 'u', 'g', 'g', 'e', 's', 
't', 'i', 'o', 'n', 's', '?', '\n', 't', 'h', 'a', 'n', 'k', 's', '\n']




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


Re: Linq to Python

2008-09-25 Thread Duncan Booth
sturlamolden [EMAIL PROTECTED] wrote:

 On Sep 24, 10:59 pm, Duncan Booth [EMAIL PROTECTED]
 wrote:
 
 Simple LINQ expressions like the one you gave map easily to Python
 list comprehensions. What Microsoft have done though is provide a
 consistent implementation which allows you to write complex SQL like
 expressions whi 
 ch
 will work identically on databases or most other sequence types.
 han extensions to syntax.
 
 List comprehensions work with any iterable sequence. You can nest them
 to make more complex statements. You can also use a generator to
 iterate through a database or an XML document. Here is approximately
 where linq stops being a marvelous addition to Python.
 
A lot of what LINQ does is already easy to do in Python, and most of the 
rest can probably be added fairly easily, but it does provide a consistent 
framework which may make it easier to do complex LINQ statements than 
complex list comprehensions.

BTW, a minor correction: LINQ statements are closer to generators, not list 
comprehensions. They don't actually evaluate their results until you 
iterate over them and you can re-used the same LINQ statement multiple 
times getting different results if the data has changed.

 And I can honestly do without the SQL syntax.
 
snap :)

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Er, one -lime- or two.

2008-09-25 Thread Bruno Desthuilliers

Aaron Castironpi Brady a écrit :

A Python walks into a bar and orders a complex data structure.
Bartender says, One line or two?


I don't think that one will have much success in parties !-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to build a MacOS universal python package including external dependencies

2008-09-25 Thread Jaime Huerta Cepas
Thanks Mathieu,

I think MacPorts will be the easiest way (all dependencies are available).
I could even base the installation script on  port commands.
The major problem will be to compile Qt4, which takes hours and requires
X11.

thnks, again.
Jaime.



On Wed, Sep 24, 2008 at 6:44 PM, Mathieu Prevot [EMAIL PROTECTED]wrote:

 2008/9/24 Jaime Huerta Cepas [EMAIL PROTECTED]:
  Hi all,
 
  I have developed a set python libraries that provide several scientific
  methods to analyse and visualize certain type of biological data.  This
  libraries are based on many external python modules, such as python-mysql
  python-sip or python-qt4. I use GNU/linux to develop my tools and I found
 no
  problems into installing all dependencies, however it does not seem to be
  that easy on MacOS. I am sure that all the dependencies (qt4, pyqt4 ,
  mysqldb, scipy, numpy) are cross platform, but when you are trying to
  publish your tool in an academic journal, most referees (many of them
 using
  MacOS) expect some kind of straightforward installation process for the
  tool.
 
  I wonder if there would be a way in which I could compile all the
  dependencies and libraries in a MacOs system and then building a static
  universal binary that I can distribute. I guess  it should be possible,
 but
  I am not sure how difficult it might be, and whether all dependencies
 (qt4
  is huge) can be packaged together.

 IMHO this is too complex to commit. Macport is a way to do what you
 want, but packages may not be up to date enough. Maybe the easiest and
 simplest way for you to do this is to write a script that will
 download, compile and install everything.

 The script should work like:

 sudo all_in_one_script.py

 and then wait for jobs to be done. Your script will need to know if a
 package was sucessfully installed and then continue or take steps and
 say it. For a complex set of dependencies, I recommend you to write
 Makefiles.

 For instance, in pseudo-code:
 if /usr/local/lib/libfoo.dylib doesn't exist
  download foo
  install foo

 if python-module foo doesn't exist
  download foo
  python foo/setup.py install

 etc

 HTH
 Mathieu


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

Re: python sorting 2dim. array ?

2008-09-25 Thread fredo66
remark: The server is using python server version 2.3.4
--
http://mail.python.org/mailman/listinfo/python-list


unable to parse the content using the regular expression

2008-09-25 Thread dudeja . rajat
 Hello,

I've the following results from Difflib.Compare() which I want to parse them
using the regular expression to find out the the values that have changed.

  ##

  Testing DLL interface

  ##

  Input File:c:\12.txt
  Config File:c:\abc.ini

  ##

  Results:-
  ---

- Analysis Time (Iterations = 1) = 0.0449145s
?   ^^ ^
+ Analysis Time (Iterations = 1) = 0.0447347s
?   ^^ ^

  Width = 0.89

  Height = 0.044

- Length = 10
?   ^
+ Length = 11
?   ^

  End of Results

  ##

  Testing DOTNET interface

  ##
  Input File:c:\12.txt
  Config File:c:\abc.ini

  ###

  Results:-
  ---

- Analysis Time (Iterations = 1) = 0.0449145s
?   ^^ ^
+ Analysis Time (Iterations = 1) = 0.0447347s
?   ^^ ^

  Width = 0.89

  Height = 0.044

- Length = 12
?   ^
+ Length = 13
?   ^

  End of Results



**

How Can I extract the headings out of this file? The headings are:

  ##

  Testing DLL interface

  ##

  Input File:c:\12.txt
  Config File:c:\abc.ini

  ##


 Here I want to display only the values that differ i.e. the lines prceded
with +,?,- signs 


  ##

  Testing DOTNET interface

  ##
  Input File:c:\12.txt
  Config File:c:\abc.ini

  ###


I intent to show only the things that differ with their proper headings(as
above)

Please help me to get the heading stuff out.

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

Re: Connecting to SMB share in python

2008-09-25 Thread Tim Golden

Ronnie Kwok wrote:

Hello,

I am trying to write a script that copy files from my local machine to a samba
share.



Can't you just mount the share (albeit temporarily) and copy
the files over in the normal way? You haven't said what OS
you're on, but I'm assuming Linux otherwise you'd simply be
talking about a Windows share and copying to a UNC.

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


Re: python sorting 2dim. array ?

2008-09-25 Thread Peter Otten
[EMAIL PROTECTED] wrote:

 hello,
 Can someone help me with this:
 I have a array like this
 
  list[rowindex][colomindex]
 
 where rows are the records and colom the fields. If I use the .sort()
 method on 'list' the data is sorted on the items of the first colom.
 But I want to sort on the second colom as first (and as second
 sortfield the first colom).
 
 What is the shortest code for this pls ?
 
 (all fields are text value, first colom is name, second category)


 items = [(1,2), (2,2), (2,1)]
 items.sort(lambda x, y: cmp(x[1::-1], y[1::-1]))
 items
[(2, 1), (1, 2), (2, 2)]

If you want something more efficient, see

http://www.python.org/doc/faq/programming/#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python

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


Re: is decorator the right thing to use?

2008-09-25 Thread Bruno Desthuilliers

Dmitry S. Makovey a écrit :

Aaron Castironpi Brady wrote:
 

It might help to tell us the order of events that you want in your
program.  You're not using 'mymethod' or 'mymethod2', and you probably
want 'return fnew' for the future.  Something dynamic with __getattr__
might work.  Any method call to A, that is an A instance, tries to
look up a method of the same name in the B instance it was initialized
with.


well 'mymethod' and 'mymethod2' were there just to show that A doesn't
function as a pure proxy - it has methods of it's own. See my respnse to
Steve - I proxy messages to more than one aggregated object. going over
them on __getattr__ to look up methods just doesn't seem to be really
efficient to me (I might be wrong though). Decorators seemed to present
good opportunity to simplify the code (well except for the decorator
function itself :) ), make code bit more fool-proofed (and give me the
opportunity to test decorators in real life, he-he).

So decorators inside of B just identify that those methods will be proxied
by A. On one hand from logical standpoint it's kind of weird to tell class
that it is going to be proxied by another class,


Indeed - usually, proxied objects shouldn't have to be aware of the 
fact. That doesn't mean your variation on the proxy pattern is 
necessarily bad design (hard to tell without lot of context anyway...), 
but still there's some alarm bell ringing here IMHO - IOW : possibly the 
right thing to do, but needs to be double-checked.



but declaration would be
real close to original function definition which helps to identify where is
it used.

Note that my decorator doesn't change original function - it's a subversion
of decorator to a certain degree as I'm just hooking into python machinery
to add methods to A upon their declaration in B (or so I think).


I wouldn't call this a subversion of decorators - it's even a pretty 
common idiom to use decorators to flag some functions/methods for 
special use.


Now I'm not sure I really like your implementation. Here's a possible 
rewrite using a custom descriptor:


class Proxymaker(object):
def __init__(self, attrname):
self.attrname = attrname

def __get__(self, instance, cls):
def _proxied(fn):
fn_name = fn.__name__
def delegate(inst, *args, **kw):
target = getattr(inst, self.attrname)
#return fn(target, *args,**kw)
method = getattr(target, fn_name)
return method(*args, **kw)

delegate.__name__ = %s_%s_delegate % \
(self.attrname, fn_name)

setattr(cls, fn_name, delegate)
return fn

return _proxied

class A(object):
def __init__(self,b):
self.val='aval'
self.b=b
b.val='aval'

proxy2b = Proxymaker('b')

def mymethod(self,a):
print A::mymethod, ,a

def mymethod2(self,a):
print A::another method, ,a

class B(object):
def __init__(self):
self.val='bval'

@A.proxy2b
def bmethod(self,a):
print B::bmethod
print a, self.val

@A.proxy2b
def bmethod2(self,a):
print B::bmethod2
print a, self.val


My point is that:
1/ you shouldn't have to rewrite a decorator function - with basically 
the same code - for each possible proxy class / attribute name pair combo
2/ making the decorator an attribute of the proxy class makes 
dependencies clearer (well, IMHO at least).


I'm still a bit uneasy wrt/ high coupling between A and B, and if I was 
to end up with such a design, I'd probably take some times to be sure 
it's really ok.


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


Tkinter: Unable to update the text scroll

2008-09-25 Thread dudeja . rajat
Hi,

I've a Tkinter application which has some widgets and a textbox with
scrollbar, I call it txtScroll.

The txtScroll is used to display the processing log  that application is
doing. Well the problem is that the txtSxroll is not able to display the log
at the time some thing is processed. Rather, it displays the log after the
complete processing processing is done. Example:

In a function, I've the following lines:

def func():
   print 'Testing  Result Comp'
   TASymbols.objLogToGUI.outputText(Starting Test and Results
Comparison\n)
   if selectedLib != TASymbols.strSelectAll:
# we do not pass it as a string instead we will pass it in a
#single element list
libKey = self.__findKey(self.__libDict, selectedLib)

The colored line should display the stuff at the time it appeared in the
code. But only displays this after the function func() has processed
completely.

PS : I'm not using any threading stuff here..


Please help me resolve this problem.


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

Re: Linq to Python

2008-09-25 Thread sturlamolden
On 25 Sep, 10:08, Duncan Booth [EMAIL PROTECTED] wrote:

 A lot of what LINQ does is already easy to do in Python, and most of the
 rest can probably be added fairly easily, but it does provide a consistent
 framework which may make it easier to do complex LINQ statements than
 complex list comprehensions.

Yes, that's the word, consistent framework. I wonder what that
means? Do you mean Python syntax is inconsitent?


 BTW, a minor correction: LINQ statements are closer to generators, not list
 comprehensions. They don't actually evaluate their results until you
 iterate over them and you can re-used the same LINQ statement multiple
 times getting different results if the data has changed.

Python has generator expressions with the same syntax as list
comprehensions, except you use () instead of [].







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


RE: Regex Help

2008-09-25 Thread Lawrence D'Oliveiro
In message [EMAIL PROTECTED], Support
Desk wrote:

 Thanks for the reply ...

A: The vulture doesn't get Frequent Poster miles.
Q: What's the difference between a top-poster and a vulture?
--
http://mail.python.org/mailman/listinfo/python-list


Re: The Python computer language

2008-09-25 Thread sturlamolden
On 25 Sep, 06:02, ROSEEE [EMAIL PROTECTED] wrote:
 http://pythoncomputer.blogspot.com

I wonder where the usenet cancelbots have gone?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing float and decimal

2008-09-25 Thread Mark Dickinson
On Sep 24, 6:18 pm, Terry Reedy [EMAIL PROTECTED] wrote:
 If there is not now, there could be in the future, and the decimal
 authors are committed to follow the standard wherever it goes.
 Therefore, the safe course, to avoid possible future deprecations due to
 doing too much, is to only do what is mandated.

Makes sense.  It looks as though the standard's pretty stable now
though;  I'd be quite surprised to see it evolve to include discussion
of floats.  But then again, people thought it was stable just before
all the extra transcendental operations appeared. :-)

 For integral values, this is no problem.
   hash(1) == hash(1.0) == hash(decimal.Decimal(1)) ==
 hash(fractions.Fraction(1)) == 1
 True

Getting integers and Decimals to hash equal was actually
something of a pain, and required changing the way that
the hash of a long was computed.  The problem in a nutshell:
what's the hash of Decimal('1e1')?  The number is
clearly an integer, so its hash should be the same as that
of 10**1.  But computing 10**1, and then
finding its hash, is terribly slow...   (Try
hash(Decimal('1e1')) in Python 2.5 and see
what happens!  It's fixed in Python 2.6.)

As more numeric types get added to Python, this
'equal implies equal hash' requirement becomes more
and more untenable, and difficult to maintain. I also find
it a rather unnatural requirement:  numeric equality
is, to me, a weaker equivalence relation than the one
that should be used for identifying keys in dictionaries,
elements of sets, etc.  Fraction(1, 2) and 0.5 should, to my
eyes, be considered
different elements of a set. But the only way to 'fix' this
would be to have Python recognise two different types of
equality, and then it wouldn't be Python any more.

The SAGE folks also discovered that they couldn't
maintain the hash requirement.

 Decimals can also be converted to floats (they also have a  __float__
 method).  But unlike fractions, the conversion must be explicit, using
 float(decimal), instead of implicit, as with ints and fractions.

Maybe:  if I *had* to pick a direction, I'd make float + Decimal
produce a Decimal, on the basis that Decimal is arbitrary precision
and that the float-Decimal conversion can be made losslessly.
But then there are a whole host of decisions one has to make
about rounding, significant zeros, ...  (And then, as you point
out, Cowlishaw might come out with a new version of the standard
that does include interactions with floats, and makes an entirely
different set of decisions...)

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


Re: translating ascii to binary

2008-09-25 Thread Lie
On Sep 17, 11:34 pm, Fredrik Lundh [EMAIL PROTECTED] wrote:
 Lie wrote:
  Any advice about this matter would be very appreciated.
  Thanks in advance.

  It'd be easier to make a one-char version of ascii2bin then make the
  string version based on the one-char version.

 And it'd be a lot easier to read your posts if you trimmed away at least
 some of the original message before posting.  If you cannot do that for
 some technical reason, I recommend using top-posting instead.

 /F


Ah.. yes, sorry for that, I had never thought about that since I use
Google Groups, which automatically trim long quotes, to access the
list.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linq to Python

2008-09-25 Thread hrishy
Hi

If i rephrase my question how will i do this in Python

http://informationr.net/ir/13-2/TB0806.html

Watch this query on the page Where he joins all different kind of things with 
ease and elegance(as per my opinion)

[code]
var stoogeGuys = 
 Beginning with the XML source
 from xmlGuys in xmlSource.Descendants(Stooge)
 Join to the array on the common element stoogeName
 join arrayGuys in familyFacts 
   on xmlGuys.Element(stoogeName).Value equals arrayGuys.stoogeName
 Join to the database on the common element stoogeName
 join dbGuys in stoogeContext.stoogeTables 
   on xmlGuys.Element(stoogeName).Value equals dbGuys.stoogeName 
 select new
 {
firstName= dbGuys.stoogeName,
familyName   = arrayGuys.familyName,
birthDate= xmlGuys.Element(birthDate).Value,
deathDate= xmlGuys.Element(deathDate).Value,
hairCutStyle = dbGuys.stoogeHaircut,
 };
[/code]

regards
Hrishy


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


Re: Comparing float and decimal

2008-09-25 Thread Mark Dickinson
On Sep 25, 8:55 am, Tim Roberts [EMAIL PROTECTED] wrote:
 Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 0.1 actually is

 In [98]: '%.50f' % 0.1
 Out[98]: '0.1555111512312578270211815834045410'
 ?

 Actually, it's not.  Your C run-time library is generating random digits
 after it runs out of useful information (which is the first 16 or 17
 digits).  0.1 in an IEEE 784 double is this:

      0.100088817841970012523233890533447265625

I get (using Python 2.6):

 n, d = 0.1.as_integer_ratio()
 from decimal import Decimal, getcontext
 getcontext().prec = 100
 Decimal(n)/Decimal(d)
Decimal('0.155511151231257827021181583404541015625')

which is a lot closer to Marc's answer.  Looks like your float
approximation to 0.1 is 6 ulps out.  :-)

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


[OT] Looking for developers: platform for fast and effective learning

2008-09-25 Thread Adam Dziendziel
Hello everybody,

I'm working on a website for fast and effective learning using spaced
repetition technique.
This is the same method used in SuperMemo, Mnemosyne, FullRecall or
Anki software.
I'd want to create an online version, supporting easy adding of own
material and sharing with others. The method is very effective and is
great for learning foreign language, learning to exams etc. I wonder
that there is no such site running already. There is SuperMemo.net,
but it is a typical commercial application, oriented for selling
commercial courses. I would like to put on building community,
collaboration in writing material and social learning.

I'm looking for ambitious people, who want to take part in this
undertaking. I can offer revenue share, if the project succeed.

Technologies: Python (Pylons) + JavaScript (Ext JS)
I have a working base in Pylons and Ext JS but we can consider
changing tools.

Best regards,
Adam Dziendziel
adam (dot) dziendziel (at) gmail (dot) com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linq to Python

2008-09-25 Thread hrishy
Hi Grant

haha :-) i discounted that perspective :-)

regards
Hrishy


--- On Thu, 25/9/08, Grant Edwards [EMAIL PROTECTED] wrote:

 From: Grant Edwards [EMAIL PROTECTED]
 Subject: Re: Linq to Python
 To: python-list@python.org
 Date: Thursday, 25 September, 2008, 2:22 AM
 On 2008-09-24, Bruno Desthuilliers
 [EMAIL PROTECTED] wrote:
  hrishy a écrit :
  (snip)
 
 
  I apologise
  (I thought Python programmers were smart and they
 did know what LINQ was)
 
  Is there really any relation between being
 smart and knowing anything 
  about the latest MS fad ?
 
 God, I hope not -- or I'd rather be stupid.
 
 -- 
 Grant
 
 --
 http://mail.python.org/mailman/listinfo/python-list


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


Re: Connecting to SMB share in python

2008-09-25 Thread Ronnie Kwok

Thank you for the reply!

Yes, I am running the script under linux and it will be doing some 
processing before copying it over to the samba mount.


It's totally fine to mount it with os.sys(...) approach but I am just 
thinking if there's other option.


ronnie


On 2008-09-25 16:36:35 +0800, Tim Golden [EMAIL PROTECTED] said:


Ronnie Kwok wrote:

Hello,

I am trying to write a script that copy files from my local machine to a samba
share.



Can't you just mount the share (albeit temporarily) and copy
the files over in the normal way? You haven't said what OS
you're on, but I'm assuming Linux otherwise you'd simply be
talking about a Windows share and copying to a UNC.

TJG



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


Re: Linq to Python

2008-09-25 Thread hrishy
Hi Roger

I am impressed (i always suspected Python programmers are smart no doubt about 
it).

But what about the case where they join different sources like the one here

http://informationr.net/ir/13-2/TB0806.html

Thanks for teaching me :-) i am thankful for that

regards
Hrishy




 
 names = [Burke, Connor,
 Frank, Everett,
  Albert, George,
 Harris, David]
 
 result = [each.upper() for each in names if len(each) == 5]
 
 result.sort()
 
 for each in result: print each
 
 
 Yes clearly 'the Python crowd' must admit LINQ is
 'much better', I'm
 sold, in fact off to download my Free, but limited
 editions of Visual
 Studio 2005 for a single programming language supported by
 .NET right away!
 
 OK so maybe I'm being naive here but it looks to me
 like this new
 paradigm's big idea is to use a python + SQL type
 syntax to access data
 in random objects. Big whoop. It's not that difficult
 to write a
 generators that wraps XML files and databases is it?
 
 What am I missing here?
 
 
 Roger Heathcote.
 --
 http://mail.python.org/mailman/listinfo/python-list


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


Re: python sorting 2dim. array ?

2008-09-25 Thread bearophileHUGS
[EMAIL PROTECTED]:
 list[rowindex][colomindex]
 I want to sort on the second colom as first (and as
 second sortfield the first colom).

A good way, in Python 2.5:

 from operator import itemgetter
 a = [[1, 2], [3, 1], [2, 5], [7, 1]]
 a.sort(key=itemgetter(1, 0))
 a
[[3, 1], [7, 1], [1, 2], [2, 5]]

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Connecting to SMB share in python

2008-09-25 Thread Diez B. Roggisch
Ronnie Kwok wrote:

 Thank you for the reply!
 
 Yes, I am running the script under linux and it will be doing some
 processing before copying it over to the samba mount.
 
 It's totally fine to mount it with os.sys(...) approach but I am just
 thinking if there's other option.

None that is any more comfortable. If anything, you'd need smbclient or some
such to list and fetch data - which is *much* more complicated that simply
mounting a share defined in fstab.

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


Re: Comparing float and decimal

2008-09-25 Thread Nick Craig-Wood
Tim Roberts [EMAIL PROTECTED] wrote:
  Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 
 On Tue, 23 Sep 2008 07:08:07 -0700, Michael Palmer wrote:
 
   This seems to break the rule that if A is equal to B and B is equal
   to C then A is equal to C.
 
  I don't see why transitivity should apply to Python objects in general.
  
  Well, for numbers it surely would be a nice touch, wouldn't it. May be
  the reason for Decimal to accept float arguments is that irrational
  numbers or very long rational numbers cannot be converted to a Decimal
  without rounding error, and Decimal doesn't want any part of it. Seems
  pointless to me, though.
 
 Is 0.1 a very long number?  Would you expect ``0.1 == Decimal('0.1')`` to 
 be `True` or `False` given that 0.1 actually is
 
 In [98]: '%.50f' % 0.1
 Out[98]: '0.1555111512312578270211815834045410'
 ?
 
  Actually, it's not.  Your C run-time library is generating random digits
  after it runs out of useful information (which is the first 16 or 17
  digits).  0.1 in an IEEE 784 double is this:
 
   0.100088817841970012523233890533447265625

Not according to the decimal FAQ

http://docs.python.org/lib/decimal-faq.html


import math
from decimal import *

def floatToDecimal(f):
Convert a floating point number to a Decimal with no loss of information
# Transform (exactly) a float to a mantissa (0.5 = abs(m)  1.0) and an
# exponent.  Double the mantissa until it is an integer.  Use the integer
# mantissa and exponent to compute an equivalent Decimal.  If this cannot
# be done exactly, then retry with more precision.

mantissa, exponent = math.frexp(f)
while mantissa != int(mantissa):
mantissa *= 2.0
exponent -= 1
mantissa = int(mantissa)

oldcontext = getcontext()
setcontext(Context(traps=[Inexact]))
try:
while True:
try:
   return mantissa * Decimal(2) ** exponent
except Inexact:
getcontext().prec += 1
finally:
setcontext(oldcontext)

print float(0.1) is, floatToDecimal(0.1)


Prints this

float(0.1) is 0.155511151231257827021181583404541015625

On my platform

Python 2.5.2 (r252:60911, Aug  8 2008, 09:22:44),
[GCC 4.3.1] on linux2
Linux 2.6.26-1-686
Intel(R) Core(TM)2 CPU T7200

-- 
Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linq to Python

2008-09-25 Thread sturlamolden
On 25 Sep, 12:06, hrishy [EMAIL PROTECTED] wrote:

 var stoogeGuys =
      Beginning with the XML source
      from xmlGuys in xmlSource.Descendants(Stooge)
      Join to the array on the common element stoogeName
      join arrayGuys in familyFacts
            on xmlGuys.Element(stoogeName).Value equals arrayGuys.stoogeName
      Join to the database on the common element stoogeName
      join dbGuys in stoogeContext.stoogeTables
            on xmlGuys.Element(stoogeName).Value equals dbGuys.stoogeName
      select new
      {
         firstName    = dbGuys.stoogeName,
         familyName   = arrayGuys.familyName,
         birthDate    = xmlGuys.Element(birthDate).Value,
         deathDate    = xmlGuys.Element(deathDate).Value,
         hairCutStyle = dbGuys.stoogeHaircut,
      };
 [/code]


That is a for loop over xmlGuys in xmlSource.Descendants(Stooge).
Those joins are e.g. dictionary lookups, and finally an object with
names, birthdates, etc. are appended to the list stoogeGuys.






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


How to get the filename in the right case ?

2008-09-25 Thread Stef Mientki

hello,

How can I find the correct case of a filename ?

Background in my program I use case sensitive filenames, just like 
Python requires.

Now I've integrated pdb into the program,
but pdb acts somwhat strange:
upon a breakpoint it gives the filename always in lowercase (probably 
this only happens on windows).


So is there a way to get the correct case of a given filename in lowercase ?

One solution might be to make the comparison in my program always with 
lowercase,

but then I'm sure the program won't work on non-windows systems.

btw, why does pdb behave that way ( Python 2.5 ) ?

thanks,
Stef Mientki
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linq to Python

2008-09-25 Thread hrishy
Hi Tim

I am not a LINQ expert just a LINQ user and (was a little envious why the 
langauge i fantasize doesnt have it (pardon my ignorance of python))

LINQ as far as i know allows you to query all sources using a consistent 
interface .

You can query a message queue ,xml document ,array object or relational source 
by learning LINQ and even join them as illustrated below

http://informationr.net/ir/13-2/TB0806.html

If somebody can tutor me how i can do that in python that would be great (and 
mayeb satisfy my greed and leave me with a happy feeling that my langauge 
python can do it)

regards
Hrishy


--- On Wed, 24/9/08, Tim Golden [EMAIL PROTECTED] wrote:

 From: Tim Golden [EMAIL PROTECTED]
 Subject: Re: Linq to Python
 To: 
 Cc: python-list@python.org
 Date: Wednesday, 24 September, 2008, 8:20 PM
 [EMAIL PROTECTED] wrote:
  sturlamolden:
  No, because Python already has list comprehensions
 and we don't need the XML buzzword.
  
  LINQ is more than buzzwords. Python misses several of
 those features.
  So maybe for once the Python crowd may recognize such
 C# feature as
  much better than things present in Python.
  Said that, I presume Python will go on as usual, and
 LINQ-like
  capabilities will not be integrated in Python. In the
 meantime where I
  live lot of people will keep using C# instead of
 Python and CLisp,
  natural selection at work indeed.
 
 Perhaps a quick summary of what LINQ offers which might
 be integrated into Python would help those of
 us who
 are ignorant? (This is a serious comment; I'd like to
 know).
 
 TJG
 --
 http://mail.python.org/mailman/listinfo/python-list


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


Question about reading a xml

2008-09-25 Thread xiaowei.lin
Hi all,

I am working on SunOS 5.8,  Python 2.2.2

When I run the python grogram below:

 

#Beginning

import xml.dom.minidom

 

xml_str = \

test

aapos; this is a/a

bcapos; this is b/b

cthis is c/c

/test



 

dom = xml.dom.minidom.parseString(xml_str)

 

na = dom.getElementsByTagName(a)[0]

nb = dom.getElementsByTagName(b)[0]

nc = dom.getElementsByTagName(c)[0]

 

print na.childNodes[0].data

print nb.childNodes[0].data

print nc.childNodes[0].data

#End

 

The result is as below:

 this is a

c

this is c

 

I don't know why the letters following the quote are lost.
Even the quote lost if the quote following another letter.

 

Regards,

Sean

 



This message is for the designated recipient only and may contain privileged, 
proprietary, or otherwise private information.  If you have received it in 
error, please notify the sender immediately and delete the original.  Any other 
use of the email by you is prohibited.
--
http://mail.python.org/mailman/listinfo/python-list

Re: How to get the filename in the right case ?

2008-09-25 Thread Diez B. Roggisch
Stef Mientki wrote:

 hello,
 
 How can I find the correct case of a filename ?
 
 Background in my program I use case sensitive filenames, just like
 Python requires.
 Now I've integrated pdb into the program,
 but pdb acts somwhat strange:
 upon a breakpoint it gives the filename always in lowercase (probably
 this only happens on windows).
 
 So is there a way to get the correct case of a given filename in lowercase
 ?
 
 One solution might be to make the comparison in my program always with
 lowercase,
 but then I'm sure the program won't work on non-windows systems.
 
 btw, why does pdb behave that way ( Python 2.5 ) ?

I doubt it does. It sure doesn't on unix, and I fail to see any reason why
it should do that on windows - given that the total number of lower() in
pdb.py amounts to one, and that's used to process user-input such
as Yes, y, YES or whatnot.

 Are you sure you are not processing the content through some lower()-call
when embedding pdb? 

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


Re: Linq to Python

2008-09-25 Thread sturlamolden
On 25 Sep, 12:06, hrishy [EMAIL PROTECTED] wrote:

 [code]
 var stoogeGuys =
      Beginning with the XML source
      from xmlGuys in xmlSource.Descendants(Stooge)
      Join to the array on the common element stoogeName
      join arrayGuys in familyFacts
            on xmlGuys.Element(stoogeName).Value equals arrayGuys.stoogeName
      Join to the database on the common element stoogeName
      join dbGuys in stoogeContext.stoogeTables
            on xmlGuys.Element(stoogeName).Value equals dbGuys.stoogeName
      select new
      {
         firstName    = dbGuys.stoogeName,
         familyName   = arrayGuys.familyName,
         birthDate    = xmlGuys.Element(birthDate).Value,
         deathDate    = xmlGuys.Element(deathDate).Value,
         hairCutStyle = dbGuys.stoogeHaircut,
      };
 [/code]

It could e.g. look like this in Python:

stoogeGuys = []
for xmlGuys in xmlSource.Descendants[Stooge]:
arrayGuys = familyFacts[xmlGuys.stoogeName]
dbGuys = stoogeContext.stoogeTables[xmlGuys.stoogeName]
stoogeGuys += \
   [{'firstName':dbGuys.stoogeName,
 'familyName':   arrayGuys.familyName,
 'birthDate':xmlGuys.birthDate,
 'deathDate':dbGuys.deathDate,
 'hairCutStyle': dbGuys.stoogeHaircut}]

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


Re: Comparing float and decimal

2008-09-25 Thread Mark Dickinson
On Sep 23, 1:58 pm, Robert Lehmann [EMAIL PROTECTED] wrote:
 I don't see why transitivity should apply to Python objects in general.

Hmmm.  Lack of transitivity does produce some, um, interesting
results when playing with sets and dicts.  Here are sets s and
t such that the unions s | t and t | s have different sizes:

 from decimal import Decimal
 s = set([Decimal(2), 2.0])
 t = set([2])
 len(s | t)
2
 len(t | s)
1

This opens up some wonderful possibilities for hard-to-find bugs...

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


Re: Linq to Python

2008-09-25 Thread hrishy
Hi

Pardon my ignorance again but id ont see any join in python or did i miss 
something ?

regards
Hrishy


--- On Thu, 25/9/08, sturlamolden [EMAIL PROTECTED] wrote:

 From: sturlamolden [EMAIL PROTECTED]
 Subject: Re: Linq to Python
 To: python-list@python.org
 Date: Thursday, 25 September, 2008, 12:02 PM
 On 25 Sep, 12:06, hrishy [EMAIL PROTECTED] wrote:
 
  [code]
  var stoogeGuys =
       Beginning with the XML source
       from xmlGuys in
 xmlSource.Descendants(Stooge)
       Join to the array on the common element
 stoogeName
       join arrayGuys in familyFacts
             on
 xmlGuys.Element(stoogeName).Value equals
 arrayGuys.stoogeName
       Join to the database on the common element
 stoogeName
       join dbGuys in stoogeContext.stoogeTables
             on
 xmlGuys.Element(stoogeName).Value equals
 dbGuys.stoogeName
       select new
       {
          firstName    = dbGuys.stoogeName,
          familyName   = arrayGuys.familyName,
          birthDate    =
 xmlGuys.Element(birthDate).Value,
          deathDate    =
 xmlGuys.Element(deathDate).Value,
          hairCutStyle = dbGuys.stoogeHaircut,
       };
  [/code]
 
 It could e.g. look like this in Python:
 
 stoogeGuys = []
 for xmlGuys in xmlSource.Descendants[Stooge]:
 arrayGuys = familyFacts[xmlGuys.stoogeName]
 dbGuys = stoogeContext.stoogeTables[xmlGuys.stoogeName]
 stoogeGuys += \
[{'firstName':dbGuys.stoogeName,
  'familyName':   arrayGuys.familyName,
  'birthDate':xmlGuys.birthDate,
  'deathDate':dbGuys.deathDate,
  'hairCutStyle': dbGuys.stoogeHaircut}]
 
 --
 http://mail.python.org/mailman/listinfo/python-list


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


Re: Linq to Python

2008-09-25 Thread sturlamolden
On 25 Sep, 13:08, hrishy [EMAIL PROTECTED] wrote:

 Pardon my ignorance again but id ont see any join in python or did i miss 
 something ?

It's more Pythonic to use the syntax of dictionary lookups.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linq to Python

2008-09-25 Thread hrishy
Hi

Thank you very much I appreciate taking the pain to explain this to me.

regards
Hrishy


--- On Thu, 25/9/08, sturlamolden [EMAIL PROTECTED] wrote:

 From: sturlamolden [EMAIL PROTECTED]
 Subject: Re: Linq to Python
 To: python-list@python.org
 Date: Thursday, 25 September, 2008, 12:16 PM
 On 25 Sep, 13:08, hrishy [EMAIL PROTECTED] wrote:
 
  Pardon my ignorance again but id ont see any join in
 python or did i miss something ?
 
 It's more Pythonic to use the syntax of dictionary
 lookups.
 --
 http://mail.python.org/mailman/listinfo/python-list


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


Spring Python 0.7.0 is released

2008-09-25 Thread Goldfish
Release 0.7.0 was completed last night, and released to
sourceforge.net.

NOTE: This release included a lot of API scrubbing, in order to bring
things more in tune with PEP-0008 (python's style guide). You're
existing apps PROBABLY were impacted, if you used any of Spring
Python's utility classes. Since we are pre-1.0, this is the best time
for such a cleanup. When 1.0 hits the streets, we won't make such a
sweeping change without extensive backwards support.

See [url]http://springpython.webfactional.com[/url] for more
information.

Visit our community forum at [url]http://forum.springframework.org/
forumdisplay.php?f=45[/url] for current threads of discussion.

--Greg Turnquist, Spring Python project lead
=
Release Notes - Spring Python - Version 0.7


** Bug
* [SESPRINGPYTHONPY-63] - Running setup.py returns an exception

** Improvement
* [SESPRINGPYTHONPY-49] - Upgrade PetClinic to CherryPy 3.1
* [SESPRINGPYTHONPY-64] - Adding a schema for the regular
component elements
* [SESPRINGPYTHONPY-69] - Remove deprecated connection factories
from baseline
* [SESPRINGPYTHONPY-70] - Scrub function/attribute naming
conventions to more closely follow PEP-0008.

** New Feature
* [SESPRINGPYTHONPY-61] - Generate reference documentation for the
project

** Refactoring
* [SESPRINGPYTHONPY-65] - Change 'type' attribute in XML
application config to 'scope' to be in line with the lifetime concept
in other Spring platforms


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


Re: Folder Actions on Mac OSX Leopard?

2008-09-25 Thread has
On 25 Sep, 00:30, Sean DiZazzo [EMAIL PROTECTED] wrote:

 I always wondered about Folder Actions...  I just tested.  You can
 have applescript call python scripts via `do shell script`.  But it
 seemed a bit flakey.

Should work in theory. For which values of flakey? e.g. Is it a
technical problem with Folder Actions, AppleScript, 'do shell script,
and/or Python, or just your AppleScript code that needs some work
(e.g. there are some common gotchas with using 'do shell script' that
often trip up AppleScript newcomers).

FWIW, I would second the suggestion to look into FSEvents as a
possible alternative to Folder Actions. There's also kqueue which is
lower level but may have/have had Python bindings already written for
it.

Alternatively, if the OP really wants to use FAs, there are a couple
of other options for that:

1. I've got a simple py2app-based application shell and an AppleScript
that automatically forwards FA events to that application - just
insert your Python code into the application shell and build it,
attach the AppleScript to some folders, and you're good to go. Email
me directly if you want a copy.

2. If you're brave, you could try using the PyOSA component on the
appscript website, which allows you to write OSA scripts in Python.
FAs will work with any kind of OSA script (.scpt files), not just
AppleScript ones. PyOSA is officially discontinued due to some
intractable limitations in its/CPython's design (specifically the
inability of an in-process Python interpreter to sandbox unrelated
scripts so that they can't interfere with each others' modules, file
handles, etc). However, it's reasonably functional and should be
usable for FAs with a little care.


HTH

has
--
Control AppleScriptable applications from Python, Ruby and ObjC:
http://appscript.sourceforge.net

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


Re: How to get the filename in the right case ?

2008-09-25 Thread Stef Mientki

Diez B. Roggisch wrote:

Stef Mientki wrote:

  

hello,

How can I find the correct case of a filename ?

Background in my program I use case sensitive filenames, just like
Python requires.
Now I've integrated pdb into the program,
but pdb acts somwhat strange:
upon a breakpoint it gives the filename always in lowercase (probably
this only happens on windows).

So is there a way to get the correct case of a given filename in lowercase
?

One solution might be to make the comparison in my program always with
lowercase,
but then I'm sure the program won't work on non-windows systems.

btw, why does pdb behave that way ( Python 2.5 ) ?



I doubt it does. It sure doesn't on unix, and I fail to see any reason why
it should do that on windows - given that the total number of lower() in
pdb.py amounts to one, and that's used to process user-input such
as Yes, y, YES or whatnot.

  

Yes I'm pretty sure, two reasons:
1. when I perform a step_into, jumping into a file that doesn't have 
breakpoints itself (meaning my program doesn't even know of this file),

pdb returns a lowercase filename
2. rpdb2 (probably based or even inherited from pdb) has the same 
behavior. Asking the writer of rpdb2, I got some excuse (which I didn't 
understand) why he had done it that way.



 Are you sure you are not processing the content through some lower()-call
when embedding pdb? 

  

But maybe pdb does ?

thanks anyway,
Stef
  
Diez

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


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


Re: multiple processes with private working dirs

2008-09-25 Thread Tim Arnold
On Sep 25, 12:11 am, alex23 [EMAIL PROTECTED] wrote:
 On Sep 25, 3:37 am, Tim Arnold [EMAIL PROTECTED] wrote:

  Am I missing something?

 Do you mean something other than the replies you got the last time you
 asked the exact same question?

 http://groups.google.com/group/comp.lang.python/browse_frm/thread/42c...

arggg. My newreader didn't show the initial post so I thought it never
made it through.
sorry for the noise.
--Tim Arnold
--
http://mail.python.org/mailman/listinfo/python-list


Re: multiple processes with private working dirs

2008-09-25 Thread sturlamolden
On 24 Sep, 19:37, Tim Arnold [EMAIL PROTECTED] wrote:

 Am I missing something? Is there a better way?

Use the pyprocessing module (to appear as standard module
multiprocessing in Python 2.6). It has almost the same interface as
Python's threading and Queue standard modules, except you are working
with processes not threads. To wait for a process to finish, just join
it like you would do with a thread.


http://pyprocessing.berlios.de/





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


Re: Connecting to SMB share in python

2008-09-25 Thread Tim Golden

Ronnie Kwok wrote:
Yes, I am running the script under linux and it will be doing some 
processing before copying it over to the samba mount.


It's totally fine to mount it with os.sys(...) approach but I am just 
thinking if there's other option.



I'm not really a Linux person but from all I can see
from Googling around a bit, the os.system (mount/unmount)
option is still the most viable. Hopefully someone with
real expertise can chip in.

BTW, opinion in this ng/mailing list tends to favour
bottom-posting or interleaved posting.

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


Re: How to get the filename in the right case ?

2008-09-25 Thread Diez B. Roggisch
 Yes I'm pretty sure, two reasons:
 1. when I perform a step_into, jumping into a file that doesn't have
 breakpoints itself (meaning my program doesn't even know of this file),
 pdb returns a lowercase filename

What has that to do with potential output postprocessing? 



 2. rpdb2 (probably based or even inherited from pdb) has the same
 behavior. Asking the writer of rpdb2, I got some excuse (which I didn't
 understand) why he had done it that way.

rpdb2 is not pdb.

Below is the output of a Pdb-session I just had:


(eggbasket)[EMAIL PROTECTED]:~/software/vc/EggBasket$ nosetests -s
eggbasket.tests.test_model
2008-09-25 14:13:10,374 turbogears.identity.saprovider INFO Loading:
eggbasket.model.VisitIdentity
. 
/home/dir/software/vc/EggBasket/eggbasket/tests/test_model.py(59)test_versionsets()
- vi1 = vset.add_pkg_info(p1)
(Pdb) n
 /home/dir/software/vc/EggBasket/eggbasket/tests/test_model.py(60)test_versionsets()
- session.flush()
(Pdb) n


As you can see - mixed-case filenames. Linux though.

There is a *very* simple way for you to check: just create a file called

FooBar.py

and inside that, put

import pdb; pdb.set_trace()
print hello


Run that on the windows shell. See if that puts out all lowercase or not. I
can't do that right now as my VBox Windows won't start.

Then we know if PDB is really the culprit.

Apart from that, is that really a problem that the filenames are all lower
case? AFAIK Windows is case-insensitive regarding filenames anyway. So
opening the file by just passing the filename should work seamless.

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


Re: Linq to Python

2008-09-25 Thread Duncan Booth
sturlamolden [EMAIL PROTECTED] wrote:

 On 25 Sep, 10:08, Duncan Booth [EMAIL PROTECTED] wrote:
 
 A lot of what LINQ does is already easy to do in Python, and most of
 the rest can probably be added fairly easily, but it does provide a
 consistent framework which may make it easier to do complex LINQ
 statements than complex list comprehensions.
 
 Yes, that's the word, consistent framework. I wonder what that
 means? Do you mean Python syntax is inconsitent?

No Python's syntax is fine. The api's aren't as consistent though: 
Microsoft added a common set of extension methods which work on 
databases, xml, builtin sequences and can be easily extended to include 
other custom sequences.

As an example to filter a list in Python you'd use a list comprehension 
with an 'if', but for a database you'd probably prefer a select with a 
'where' clause so as to avoid retrieving and discarding 99 or your 1 
million rows. The apis defined by LINQ allow that sort of optimisation 
to happen transparently, the simple list would just test each element 
but the database would run an appropriate query.

So what the 'can we have LINQ in Python' people are asking is to be able 
to write things like:

   x = (c for c in customers if c.id=='123')

and know that they aren't doing a linear search unless that is the best 
that can be done. The LINQ equivalent would be something like:

  var x = from c in customers where c.id=='123'
  select new { c.name, c.id };

which is compiled to:

  var x = customers.Where(c = c.id=='123');

and depending on the type of 'customers' the Where method can either get 
a callable function to test the condition or an expression tree which it 
can compile into another language such as SQL (C# lambdas can compile 
either to executable code or to Expression objects that you can 
further process).

There's an article at 
http://www.interact-sw.co.uk/iangblog/2005/09/30/expressiontrees which 
has a real example showing how:

DataContext db = new DataContext(server=.;initial catalog=northwind);
TableOrders orders = db.GetTableOrders();
TableCustomers customers = db.GetTableCustomers();

var q = from o in orders, c in customers
where o.ShipCity == London  (o.CustomerID == c.CustomerID)
select new { o.OrderDate, c.CompanyName, c.ContactTitle,
 c.ContactName };

actually ends up as a single SQL query:

exec sp_executesql N'SELECT [t1].[CompanyName], [t1].[ContactName], 
[t1].[ContactTitle], [t0].[OrderDate]
FROM [Orders] AS [t0], [Customers] AS [t1]
WHERE ([t0].[ShipCity] = @p0) AND ([t0].[CustomerID] = [t1].
[CustomerID])', N'@p0 nvarchar(6)', @p0 = N'London' 


 BTW, a minor correction: LINQ statements are closer to generators,
 not list comprehensions. They don't actually evaluate their results
 until you iterate over them and you can re-used the same LINQ
 statement multiple times getting different results if the data has
 changed. 
 
 Python has generator expressions with the same syntax as list
 comprehensions, except you use () instead of [].
 
It might surprise you to know that I have actually come across generator 
expressions. :^)

My wording was deliberate: LINQ queries are re-usable, so are Python's 
generators, but generator expressions are not. The comparison isn't 
exact, you have to call the generator to get an iterator whereas a LINQ 
expression gives you something which is directly iterable.

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linq to Python

2008-09-25 Thread sturlamolden
On 25 Sep, 14:22, Duncan Booth [EMAIL PROTECTED] wrote:

 No Python's syntax is fine. The api's aren't as consistent though:
 Microsoft added a common set of extension methods which work on
 databases, xml, builtin sequences and can be easily extended to include
 other custom sequences.

That is correct, but it is a library issue and cannot be solved by
adding new syntax.


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


multiprocessing eats memory

2008-09-25 Thread Max Ivanov
I'm playing with pyprocessing module and found that it eats lot's of
memory. I've made small test case to show it. I pass ~45mb of data to
worker processes and than get it back slightly modified. At any time
in main process there are shouldn't be no more than two copies of data
(one original data and one result). I run it on 8-core server and top
shows me that main process eats ~220 Mb and worker processes eats 90
-150 mb. Isn't it too much?

Small test-case is uploaded to pastebin: http://pastebin.ca/1210523
--
http://mail.python.org/mailman/listinfo/python-list


what does python -i use as input stream (stdin)?

2008-09-25 Thread Almar Klein
Hi,
I want to start python -i from a subprocess and change its stdin stream,
so I get control over the commands I feed the interpreter.

I thought just changing sys.stdin to my custom file-like object would
suffice, but this does not work. Neither does changing sys.__stdin__.

I guess the interpreter got a reference to the original stdin (the Pipe)
before
I could change it, and is using that instead of sys.stdin.

Any thoughts how I can get the interpreter to use MY custom stream?

thanks,
Almar
--
http://mail.python.org/mailman/listinfo/python-list

Re: Linq to Python

2008-09-25 Thread bearophileHUGS
Duncan Booth:
 Microsoft added a common set of extension methods which work on
 databases, xml, builtin sequences and can be easily extended to include
 other custom sequences.

When the processing is done in memory, LINQ may also work well with
multi-core CPUs, see PLINQ.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: urllib error on urlopen

2008-09-25 Thread Mike Driscoll
On Sep 24, 7:08 pm, Michael Palmer [EMAIL PROTECTED] wrote:
 On Sep 24, 11:46 am, Mike Driscoll [EMAIL PROTECTED] wrote:



  Hi,

  I have been using the following code for over a year in one of my
  programs:

  f = urllib2.urlopen('https://www.companywebsite.com/somestring')

  It worked great until the middle of the afternoon yesterday. Now I get
  the following traceback:

  Traceback (most recent call last):
    File pyshell#13, line 1, in module
      response = urllib2.urlopen(req).read().strip()
    File c:\python25\lib\urllib2.py, line 124, in urlopen
      return _opener.open(url, data)
    File c:\python25\lib\urllib2.py, line 381, in open
      response = self._open(req, data)
    File c:\python25\lib\urllib2.py, line 399, in _open
      '_open', req)
    File c:\python25\lib\urllib2.py, line 360, in _call_chain
      result = func(*args)
    File c:\python25\lib\urllib2.py, line 1115, in https_open
      return self.do_open(httplib.HTTPSConnection, req)
    File c:\python25\lib\urllib2.py, line 1082, in do_open
      raise URLError(err)
  URLError: urlopen error (1, 'error:140770FC:SSL
  routines:SSL23_GET_SERVER_HELLO:unknown protocol')

  I tried my Google Fu on this error, but there's not much out there. I
  tried using a proxy in Python, but that returned the same traceback.
  If I copy the URL into my browser, it resolves correctly. Does anyone
  have any advice on how to troubleshoot this error?

  I am using Python 2.5.2 on Windows XP.

  Thanks,

  Mike

 Could it just be a misconfiguration at the other end? Can you open
 other https urls?

This is really weird. Now it works this morning. I've spoken with our
webmaster/system admin and he said he didn't change anything on his
end. We're both befuddled. Sorry for the noise.

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


Re: urllib error on urlopen

2008-09-25 Thread Mike Driscoll
On Sep 24, 9:36 pm, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Wed, 24 Sep 2008 08:46:56 -0700, Mike Driscoll wrote:
  Hi,

  I have been using the following code for over a year in one of my
  programs:

  f = urllib2.urlopen('https://www.companywebsite.com/somestring')

  It worked great until the middle of the afternoon yesterday. Now I get
  the following traceback:
 ...
  URLError: urlopen error (1, 'error:140770FC:SSL
  routines:SSL23_GET_SERVER_HELLO:unknown protocol')

 Have you recently set a proxy where Python can auto-detect it? I
 understand that urllib2 doesn't work well with https proxies.

 If so, you can instruct urllib2 not to use a proxy-handler, but it's more
 work. What I do is construct an opener without a proxyhandler:

 # untested...
 no_proxy_support = urllib2.ProxyHandler({})
 opener = urllib2.build_opener(no_proxy_support)
 f = opener.open('https://www.companywebsite.com/somestring')

 If that doesn't work, you may need to build a Request object from the URL
 before passing it to opener.open.

 --
 Steven

As I mentioned to Mr. Palmer, the error has mysteriously gone away
this morning. I'll keep your advice handy though, in case it happens
again.

Thanks,

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


ANN: eGenix pyOpenSSL Distribution 0.7.0-0.9.8i-1

2008-09-25 Thread eGenix Team: M.-A. Lemburg


ANNOUNCING

   eGenix.com pyOpenSSL Distribution

Version 0.7.0-0.9.8i-1


 An easy to install and use repackaged distribution
   of the pyOpenSSL Python interface for OpenSSL -
  available on Windows and Unix platforms


This announcement is also available on our web-site for online reading:
http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.7.0-0.9.8i-1-GA.html



INTRODUCTION

The eGenix.com pyOpenSSL Distribution includes everything you need to
get started with SSL in Python. It comes with an easy to use installer
that includes the most recent OpenSSL library versions in pre-compiled
form.

pyOpenSSL is an open-source Python add-on (http://pyopenssl.sf.net/)
that allows writing SSL aware networking applications as well as
certificate management tools.

OpenSSL is an open-source implementation of the SSL protocol
(http://www.openssl.org/).

* About Python:
Python is an object-oriented Open Source programming language which
runs on all modern platforms (http://www.python.org/). By integrating
ease-of-use, clarity in coding, enterprise application connectivity
and rapid application design, Python establishes an ideal programming
platform for todays IT challenges.

* About eGenix:
eGenix is a consulting and software product company focused on
providing professional quality services and products to Python
users and developers (http://www.egenix.com/).



NEWS

This second release of the eGenix.com pyOpenSSL Distribution upgrades
the included OpenSSL library version to the latest 0.9.8i, which includes
several bug fixes over the previously included 0.9.8h version.

The release also includes Python 2.6 support for the first time.

Binaries are available for Linux x86 and x64 as well as Windows x86.



DOWNLOADS

The download archives and instructions for installing the package can
be found at:

http://www.egenix.com/products/python/pyOpenSSL/



UPGRADING

Before installing this version of pyOpenSSL, please make sure that
you uninstall any previously installed pyOpenSSL version. Otherwise,
you could end up not using the included OpenSSL libs.

___

SUPPORT

Commercial support for these packages is available from eGenix.com.
Please see

http://www.egenix.com/services/support/

for details about our support offerings.

Enjoy,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Sep 25 2008)
 Python/Zope Consulting and Support ...http://www.egenix.com/
 mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
 mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611



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


Re: How to get the filename in the right case ?

2008-09-25 Thread Stef Mientki

Diez B. Roggisch wrote:

Yes I'm pretty sure, two reasons:
1. when I perform a step_into, jumping into a file that doesn't have
breakpoints itself (meaning my program doesn't even know of this file),
pdb returns a lowercase filename



What has that to do with potential output postprocessing? 




  

2. rpdb2 (probably based or even inherited from pdb) has the same
behavior. Asking the writer of rpdb2, I got some excuse (which I didn't
understand) why he had done it that way.



rpdb2 is not pdb.

Below is the output of a Pdb-session I just had:


(eggbasket)[EMAIL PROTECTED]:~/software/vc/EggBasket$ nosetests -s
eggbasket.tests.test_model
2008-09-25 14:13:10,374 turbogears.identity.saprovider INFO Loading:
eggbasket.model.VisitIdentity
. 
/home/dir/software/vc/EggBasket/eggbasket/tests/test_model.py(59)test_versionsets()
- vi1 = vset.add_pkg_info(p1)
(Pdb) n
  

/home/dir/software/vc/EggBasket/eggbasket/tests/test_model.py(60)test_versionsets()


- session.flush()
(Pdb) n


As you can see - mixed-case filenames. Linux though.

There is a *very* simple way for you to check: just create a file called

FooBar.py

and inside that, put

import pdb; pdb.set_trace()
print hello


Run that on the windows shell. See if that puts out all lowercase or not. I
can't do that right now as my VBox Windows won't start.
  

 import Module1
 d:\data_python_25\pylab_works\module1.py(3)module()
- print hello
(Pdb)


Then we know if PDB is really the culprit.

  

So pdb is the problem.

Apart from that, is that really a problem that the filenames are all lower
case? AFAIK Windows is case-insensitive regarding filenames anyway. So
opening the file by just passing the filename should work seamless.
  

Yes windows is,
but Python is not.
My program should run on Windows and Linux (and maybe a few others).
By converting everything to lowercase, on Linux I can't distinguishes 
between 2 files with the same name but a different case
(btw, giving 2 files the same name, only differing in case, looks like a 
bad idea to me).


And yes I could switch to lowercase in case I'm on a windows machine,
but my program is too beautiful to pollute the code with these kind of 
unnecessary statements ;-)


cheers,
Stef

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


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


Python OOP question

2008-09-25 Thread k3xji
Hi all,

I am trying to develop a game-server in python. Design is as
following:

- ConnectionManager - handling/distributing incoming connections
- IOManager - handling IO recv/send operations on sockets.
(inheritable)
- Socket - basic async socket object
- SocketServer - handling multiple socket object requests.
(inheritable)
- Options - holds the server options (inheritable)

I want this code to be extensible as it can be. So I have developed it
like this. I f one is going to implement some new feature, all needs
to be done is to inherit IOManager or Server object to do it.
Inheritable objects are IOManager, SocketServer and Options.

But there is some feeling about this design that it can be better.
Here is the main.py which I am using to execute the server:

from Base.SocketServer import SocketServer
from testIOManager import testIOManager
from Base.Options import Options
from Base.ConnectionManager import ConnectionManager

iomgr = testIOManager()
opts = Options()

# calculate how many server objects to create
# according to the maximum allowed client count.
serverCnt = opts.MAX_CLIENT_COUNT / opts.MAX_CLIENT_COUNT_PER_SERVER
Servers = []
for i in range(serverCnt):
server = Server(i)
Servers.append(server)


cmgr = ConnectionManager(Servers, iomgr, opts)
cmgr.start()

With current design as server object is inheritable, I need to pass it
to ConnectionManager object. I just have a feeling that above design
is bad in the sense of readability.

Is there any paradigms. patterns specifically in Python for above like
situations, where in a library, we design some objects to be abstract
as possbile and other non-inheritable objects using the functions?

Or just any feedback on this Design structure?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to parse a string completely into a list

2008-09-25 Thread john . ford
On Sep 25, 1:51 am, Tino Wildenhain [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  On Sep 24, 10:12 pm, Matt Nordhoff [EMAIL PROTECTED] wrote:
  [EMAIL PROTECTED] wrote:
  On Sep 24, 9:44 pm, Chris Rebert [EMAIL PROTECTED] wrote:
 
  Could you please define exactly what you mean by elements of a string?
  If you mean characters, then just use list(): list(  \n \t abc)
  [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c']
  Regards,
  Chris
  Worked like a charm.
  kudos!
  Why do you need to convert it to a list? Strings are sequences, so you
  can do things like slice them or iterate through them by character:

  for character in foo:
  ...     print character
  ...
  f
  o
  o

  --

  The string draws a map that I then want to be able to traverse
  through. If I can count through the individual characters of a list I
  can create an x-y coordinate plane for navigation.

 You can 'count' (whatever that means) equally in strings as you do in
 lists. As said above, they behave exactly the same. Just strings
 are imutable - e.g. you can't change individual parts of them.

 Tino

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

  smime.p7s
 4KViewDownload

Ahh, but I forgot to mention that I have to mark the path I took in
the string. So using list() and then join() are my best options.

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


Re: matplotlib in interactive mode locks when run from subprocess

2008-09-25 Thread Almar Klein
To who cares, I found out what my problem was.

Testing interactivity with Tk in a normal Python console gave proper
results, just like IPython. Also running python -i gives the
interactive behaviour I wanted. But running python -i from a subprocess
did not. I was startled, because it worked out of the box with Python!

I read somewhere that Tkinter does not need a mainloop, which should be
true in order to have the interactive behaviour in python without a second
thread. Well, tk does indeed not need a mainloop, but you DO need to
create a tk app and call update() on it from time to time. (Which makes
sense now that I know it :) )

After examing code from IPython, I saw that it runs code to start a Tk app,
and performs tk.update().

So I guess this means that the standard python shell creates such a
hidden tk app, but NOT when run from a subprocess.

I have now solved my problem, and interactivity works!

Almar




2008/9/20 Almar Klein [EMAIL PROTECTED]

 I think my question was not very clear. I narrowed the problem down to
 a reconstructable small example, consisting of a python script (a very
 simple interpreter) and three lines to execute in it:

 == start simple interpreter file ==
 import os
 import sys
 import time

 def run():
 while True:

 # read a line of text, the thread is stuck here untill a \n is
 # fed to the stream.
 time.sleep(0.1)
 line = 
 try:
 line = sys.stdin.readline()
 except Exception, why:
 sys.stdout.wite(why.message+\n)

 if line:
 try:
 code = compile(line,none,exec)
 exec(code)
 except Exception, why:
 sys.stderr.write(why.message)
 sys.stderr.write( )

 if __name__ == __main__:
 run()

 == end of file ==

 Now I run this file (by double clicking it) and I get a prompt. The three
 lines I type in are:
 import matplotlib.pylab as pl
 pl.ion() #interactive mode on
 pl.plot([1,2,3],[4,6,5])

 This produces a tk window, but it's unresponsive. The process does have 5
 threads, so
 matplotlib managed to create the threads, but it seems as if they're
 blocked.

 When I run the three lines of code in a normal python shell, I get the
 proper results:
 a responsive figure (I can zoom and pan) and my shell is still responsive
 too.

 I am in the dark why this does not work. Any thoughts anyone? I've been
 busy all day
 trying to get this right, with hardly any progress... :(

 Almar

 PS: I run windows xp, my matplotlibrc file has the backend: TkAgg,
 interactive: True


 2008/9/18 Almar Klein [EMAIL PROTECTED]

 Hi,

 In wxpython, I made an interactive shell, which creates a remote python
 subprocess
 to do the interpreting. Communication is done via a pipe. The idea is that
 the python
 session is an actual process separate from the GUI, which has some
 advantages,
 like I can have multiple such shells in my application, and I can kill
 them without
 worrying that my wx app will crash.

 To do this I use the wx.Process class, which allows asynchronous
 communication with
 the remote process.

 This all works really, I will also launch wxpython apps. So I was quite
 happy, untill I tried
 doing some plotting with matplotlib (in TkAgg backend). The problem is
 that the process
 becomes unresponsive when I plot something (No prompt is written to the
 stdout/stderr).
 (more details below)

 I don't know much about creating subprocess and how they are different
 from a normal
 process. So can anyone offer some help as to what the problem might be?

 Thanks in advance,
 Almar

 To get to the details:
 - When I start a process with command python -u -i
   -- When interactive mode is off, the whole process becomes unresponsive
 when doing
  pylab.show()
   -- When interactive mode in on, on doing pylab.plot(), a figure appears,
 which I can
 zoom etc., but the process is now stuck, also after closing the figure

 - When I start a process with command
   python -u -c 'import code;code.interact(readfunc=raw_input)'  (This is
 how Pype does it).
   -- When interactive mode is off, the figures show when doing
 pylab.show() and the process
  behaves as normal after closing the figure(s).
   -- When interactive mode in on, on doing pylab.plot(), a figure appears,
 but most of the time
  it is not drawn and emmediately unresponsive, just like the process
 itself.

 I have also tried an asynchronous Popen recipe by Joshiah Carlson I found
 on
 activestate. And I made my own process class using
 win32process.CreateProcess.
 Both alternatives to wx.Process resulted in the same sympoms.

 Oh, and I run windows.



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

which python as a python command?

2008-09-25 Thread chardish
Hello,

I'm trying to find out in a script where the location of the current
python is. (I'm writing an installer script in python for a simple
server application, so i'm going to do a find-replace in a bunch of
files to give them the absolute path of the python binary.

One thought might be to use the subprocess module, run which python
as a subprocess, and then peek at stdout, but that seems way too
complicated. Is there a simple solution for this in just a few lines
of code?

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


Re: which python as a python command?

2008-09-25 Thread Carsten Haese
[EMAIL PROTECTED] wrote:
 Hello,
 
 I'm trying to find out in a script where the location of the current
 python is.

import sys
print sys.executable

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


PID management with popen and spawn

2008-09-25 Thread EEK

Hello,

 My goal is to start and stop separate Linux processes from a python
program by specific PID.  The output of these processes needs to have
their stderr and stdout piped to a particular file, respectively.

 I've been able to make this work with subprocess.Popen only if the
shell variable is set to False but I cannot pipe the outputs of the
targets.

 When using subprocess.Popen with shell=True, I believe the returned
PID is of the shell that opens the target process, not the target
process itself.  Therfore, I cannot stop the target process for the
returned PID is not of that process.

 Spawn will work better but I need the target application to pipe it's
stderr and stdout to a file.  Here I have troubles.

 Any help appreciated.

 prgm = program I want to run (compiled C)
 logfile = file I want to pipe output to

 What I need to do based on a simple shell call:  program  logfile
(yes, that's it)

 proc = subprocess.Popen(program   logfile, shell=True,
env=os.environ)

 The above spawns the new process but proc.pid is not of 'program'.
Therefore, my python program cannot kill/stop it if needed.

 pidNum = os.spawnle(os.P_NOWAIT, program   logfile,
pidName ,os.environ)
 This does not work.  File not found

 Thanks,

EEK




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


Re: which python as a python command?

2008-09-25 Thread chardish
On Sep 25, 11:14 am, Carsten Haese [EMAIL PROTECTED] wrote:
 import sys
 print sys.executable

This is exactly what I needed. Thanks!
--
http://mail.python.org/mailman/listinfo/python-list


How can I customize builtin module search path to prefix/lib to prefix/lib64?

2008-09-25 Thread js
Hi list,

Is it possible to change module search path (PYTHONPATH) built-in to
Python interpreter?
I thought I can change it with configure --libdir but it didn't work for me.
I also tried patching around python source tree replacing lib to lib64
but it didn't work either.

Adjusting sys.path directly or using environ should do the trick but
I'd rather want to make it the default path for my python

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


Re: is decorator the right thing to use?

2008-09-25 Thread Dmitry S. Makovey
Diez B. Roggisch wrote:

 Dmitry S. Makovey schrieb:
 Dmitry S. Makovey wrote:
 In my real-life case A is a proxy to B, C and D instances/objects, not
 just one.
 
 forgot to mention that above would mean that I need to have more than one
 decorator function like AproxyB, AproxyC and AproxyD or make Aproxy
 smarter about which property of A has instance of which class etc.
 
 __getattr__?

see, in your code you're assuming that there's only 1 property ( 'b' )
inside of A that needs proxying. In reality I have several. So in your code
self._delegate should be at least a tupple or a list. Plus what you're
doing - you just promiscuously passing any method not found in Proxy to
self._delegate which is not what I need as I need to pass only a subset of
calls, so now your code needs to acquire dictionary of allowed calls, and
go over all self._delegates to find if any one has it which is not
efficient since there IS a 1:1 mapping of A::method - B::method so lookups
shouldn't be necessary IMO (for performance reasons).

 class Proxy(object):
 
 
  def __init__(self, delegate):
  self._delegate = delegate
 
 
  def __getattr__(self, attr):
  v = getattr(self._delegate, attr)
  if callable(v):
 class CallInterceptor(object):
   def __init__(self, f):
   self._f = f
 
   def __call__(self, *args, **kwargs):
   print Called  + str(self._f) +  with  +
 str(args) + str(kwargs)
   return self._f(*args, **kwargs)
 return CallInterceptor(v)
  return v

 Decorators have *nothing* to do with this. They are syntactic sugar for
 def foo(...):
  ...
 foo = a_decorator(foo)

exactly. and in my case they would've simplified code reading/maintenance.
However introduced tight coupling (A knows about B and be should know
about A) is something that worries me and I'm trying to figure out if there
is another way to use decorators for my scenario or is there another way of
achieving the same thing without using decorators and without bloating up
the code with alternative solution. 

Another way could be to use Metaclass to populate class with method upon
declaration but that presents quite a bit of special cruft which is more
than I have to do with decorators :) (but maybe it's all *necessary* ? )

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


Re: How to get the filename in the right case ?

2008-09-25 Thread OKB (not okblacke)
Stef Mientki wrote:
  import Module1
  d:\data_python_25\pylab_works\module1.py(3)module()
 - print hello
 (Pdb)
 
 Then we know if PDB is really the culprit.

   
 So pdb is the problem.

Yep, it does the same thing for me.

 Apart from that, is that really a problem that the filenames are
 all lower case? AFAIK Windows is case-insensitive regarding
 filenames anyway. So opening the file by just passing the filename
 should work seamless. 
   
 Yes windows is,
 but Python is not.
 My program should run on Windows and Linux (and maybe a few
 others). By converting everything to lowercase, on Linux I can't
 distinguishes between 2 files with the same name but a different
 case (btw, giving 2 files the same name, only differing in case,
 looks like a bad idea to me).

Hmmm, but I don't understand what you're doing here.  Are you 
somehow storing the filename that pdb outputs and you need to use it 
later on a potentially different OS?  If the case is preserved in pdb on 
linux, then presumably running it on linux will be fine, right?  It's 
only a problem if you somehow try to use a filename created by windows-
pdb to open a file (the same file, somehow) on linux.

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


Re: is decorator the right thing to use?

2008-09-25 Thread Dmitry S. Makovey
Thanks Bruno,

your comments were really helpful (so was the improved version of code). 

My replies below:

Bruno Desthuilliers wrote:
 So decorators inside of B just identify that those methods will be
 proxied by A. On one hand from logical standpoint it's kind of weird to
 tell class that it is going to be proxied by another class,
 
 Indeed - usually, proxied objects shouldn't have to be aware of the
 fact. That doesn't mean your variation on the proxy pattern is
 necessarily bad design (hard to tell without lot of context anyway...),
 but still there's some alarm bell ringing here IMHO - IOW : possibly the
 right thing to do, but needs to be double-checked.

I'm kind of looking at options and not dead-set on decorators, but I can't
find any other elegant enough solution which wouldn't lead to such tight
coupling. The problem I'm trying to solve is not much more complicated than
what I have already described so if anybody can suggest a better approach -
I'm all for it. 

 Now I'm not sure I really like your implementation. Here's a possible
 rewrite using a custom descriptor:

yeah, that was going to be my next step - I was just aiming for
proof-of-concept more then efficient code :)

 class Proxymaker(object):
  def __init__(self, attrname):
  self.attrname = attrname
 
  def __get__(self, instance, cls):
  def _proxied(fn):
  fn_name = fn.__name__
  def delegate(inst, *args, **kw):
  target = getattr(inst, self.attrname)
  #return fn(target, *args,**kw)
  method = getattr(target, fn_name)
  return method(*args, **kw)
 
  delegate.__name__ = %s_%s_delegate % \
  (self.attrname, fn_name)
 
  setattr(cls, fn_name, delegate)
  return fn
 
  return _proxied
 
 class A(object):
  def __init__(self,b):
  self.val='aval'
  self.b=b
  b.val='aval'
 
  proxy2b = Proxymaker('b')
 
  def mymethod(self,a):
  print A::mymethod, ,a
 
  def mymethod2(self,a):
  print A::another method, ,a
 
 class B(object):
  def __init__(self):
  self.val='bval'
 
  @A.proxy2b
  def bmethod(self,a):
  print B::bmethod
  print a, self.val
 
  @A.proxy2b
  def bmethod2(self,a):
  print B::bmethod2
  print a, self.val

 My point is that:
 1/ you shouldn't have to rewrite a decorator function - with basically
 the same code - for each possible proxy class / attribute name pair combo
 2/ making the decorator an attribute of the proxy class makes
 dependencies clearer (well, IMHO at least).

agreed on all points

 I'm still a bit uneasy wrt/ high coupling between A and B, and if I was
 to end up with such a design, I'd probably take some times to be sure
 it's really ok.

that is the question that troubles me at this point - thus my original post
(read the subject line ;) ). I like the clarity decorators bring to the
code and the fact that it's a solution pretty much out-of-the-box without
need to create something really-really custom, but I'm worried about tight
coupling and somewhat backward logic that they would introduce (the way I
envisioned them).


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


Re: How to get the filename in the right case ?

2008-09-25 Thread Stef Mientki

OKB (not okblacke) wrote:

Stef Mientki wrote:
  

import Module1
  

d:\data_python_25\pylab_works\module1.py(3)module()
  

- print hello
(Pdb)



Then we know if PDB is really the culprit.

  
  

So pdb is the problem.



Yep, it does the same thing for me.

  

Apart from that, is that really a problem that the filenames are
all lower case? AFAIK Windows is case-insensitive regarding
filenames anyway. So opening the file by just passing the filename
should work seamless. 
  
  

Yes windows is,
but Python is not.
My program should run on Windows and Linux (and maybe a few
others). By converting everything to lowercase, on Linux I can't
distinguishes between 2 files with the same name but a different
case (btw, giving 2 files the same name, only differing in case,
looks like a bad idea to me).



	Hmmm, but I don't understand what you're doing here.  Are you 
somehow storing the filename that pdb outputs and you need to use it 
later on a potentially different OS?  If the case is preserved in pdb on 
linux, then presumably running it on linux will be fine, right?  It's 
only a problem if you somehow try to use a filename created by windows-

pdb to open a file (the same file, somehow) on linux.

  

1. I've a multitab editor.
2. When a breakpoint is reached,
3. I check if the file specified in pdb output, is already open in one 
of the editor tabs,

4. if not, I open a new tab with the correct file,
5. I focus the correct editor tab and jump to the line specified by pdb.
6. After that I should be able to inspect the surrounding of the 
breakpoint, so I need the modules name.


For 3 I need to compare filenames, the editor contains the case 
sensitive name, pdb not.
For 6 I also need the case sensitive filename, but probably there's 
another way to get the modules name.


For 3, I can indeed compare the lowercase version of both,
probably I'll do that for the moment.

thanks guys for the suggestions
Stef


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


text processing

2008-09-25 Thread [EMAIL PROTECTED]

I have string like follow
12560/ABC,12567/BC,123,567,890/JK

I want above string to group like as follow
(12560,ABC)
(12567,BC)
(123,567,890,JK)

i try regular expression i am able to get first two not the third one.
can regular expression given data in different groups


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


Re: is decorator the right thing to use?

2008-09-25 Thread Bruno Desthuilliers

Dmitry S. Makovey a écrit :

Thanks Bruno,

your comments were really helpful (so was the improved version of code). 


My replies below:

Bruno Desthuilliers wrote:

So decorators inside of B just identify that those methods will be
proxied by A. On one hand from logical standpoint it's kind of weird to
tell class that it is going to be proxied by another class,



Indeed - usually, proxied objects shouldn't have to be aware of the
fact. That doesn't mean your variation on the proxy pattern is
necessarily bad design (hard to tell without lot of context anyway...),
but still there's some alarm bell ringing here IMHO - IOW : possibly the
right thing to do, but needs to be double-checked.


I'm kind of looking at options and not dead-set on decorators, but I can't
find any other elegant enough solution which wouldn't lead to such tight
coupling. The problem I'm trying to solve is not much more complicated than
what I have already described 


Well... You didn't mention why you need a proxy to start with !-)



so if anybody can suggest a better approach -
I'm all for it. 


(snip code)


My point is that:
1/ you shouldn't have to rewrite a decorator function - with basically
the same code - for each possible proxy class / attribute name pair combo
2/ making the decorator an attribute of the proxy class makes
dependencies clearer (well, IMHO at least).


agreed on all points


I'm still a bit uneasy wrt/ high coupling between A and B, and if I was
to end up with such a design, I'd probably take some times to be sure
it's really ok.


that is the question that troubles me at this point - thus my original post
(read the subject line ;) ).  I like the clarity decorators bring to the
code and the fact that it's a solution pretty much out-of-the-box without
need to create something really-really custom, but I'm worried about tight
coupling and somewhat backward logic that they would introduce (the way I
envisioned them).


Well... The canonical solution for delegation in Python is using 
__getattr__. Your problem - according to this post and your answer to 
Diez - is that your proxy may have to

1/ delegate to more than one object
2/ don't necessarily delegate each and any attribute access

I can envision one solution using both __getattr__ and a simple decorator:

def proxy(func):
   func._proxied = True
   return func

class A(object):
def __init__(self, delegates):
self._delegates = delegates
def __getattr__(self, name):
for d in self.__delegate:
func = getattr(d, name)
if callable(func) and getattr(func, '_proxied', False):
return func
raise AttributeError(
  'object %s has no attribute '%s' % (self.__class__, name)
  )


class B(object):
def __init__(self):
self.val='bval'

@proxy
def bmethod(self,a):
print B::bmethod
print a, self.val

@proxy
def bmethod2(self,a):
print B::bmethod2
print a, self.val


class C(object):
def __init__(self):
self.val='bval'

@proxy
def cmethod(self,a):
print B::bmethod
print a, self.val

@proxy
def cmethod2(self,a):
print B::bmethod2
print a, self.val


a = A([B(), C()])

# not tested...


This solves most of the coupling problems (B and C still have to make 
clear which methods are to be proxied, but at least they need not know 
which class will be used as proxy), and makes sure only 'allowed' method 
calls are delegated. But I wouldn't call it a perfect solution neither. 
If you do have more than one object having method xxx, only the first 
one will match... And let's not talk about the lookup penalty.


There's a possible variant that avoids the call to __getattr__ (in 
short: attaching delegation instancemethods to A instance in the 
initializer for each proxied method in delegates), but that wont solve 
the problem of potential name clashes.



My 2 cents...




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


Re: Er, one -lime- or two.

2008-09-25 Thread Aaron Castironpi Brady
On Sep 25, 3:09 am, Bruno Desthuilliers bruno.
[EMAIL PROTECTED] wrote:
 Aaron Castironpi Brady a écrit :

  A Python walks into a bar and orders a complex data structure.
  Bartender says, One line or two?

 I don't think that one will have much success in parties !-)

It doesn't go to any.  =P
--
http://mail.python.org/mailman/listinfo/python-list


Re: text processing

2008-09-25 Thread Marc 'BlackJack' Rintsch
On Thu, 25 Sep 2008 15:51:28 +0100, [EMAIL PROTECTED] wrote:

 I have string like follow
 12560/ABC,12567/BC,123,567,890/JK
 
 I want above string to group like as follow (12560,ABC)
 (12567,BC)
 (123,567,890,JK)
 
 i try regular expression i am able to get first two not the third one.
 can regular expression given data in different groups

Without regular expressions:

def group(string):
result = list()
for item in string.split(','):
if '/' in item:
result.extend(item.split('/'))
yield tuple(result)
result = list()
else:
result.append(item)

def main():
string = '12560/ABC,12567/BC,123,567,890/JK'
print list(group(string))

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


Lotus Domino and Python via DIIOP or similar?

2008-09-25 Thread Michael Ströder
HI!

Anybody here with experience in accessing Lotus Domino with Python via
DIIOP? In particular I'd like to be able to register Notes users with a
Python script. Preferrably without having to use Win32 COM although it
would be better than nothing.

Adding address Notes book entries via LDAP is possible but AFAIK does
not lead to full Notes users (with mailbox and Notes-ID file).

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


Re: is decorator the right thing to use?

2008-09-25 Thread Aaron Castironpi Brady
On Sep 25, 12:19 pm, Bruno Desthuilliers bruno.
[EMAIL PROTECTED] wrote:
 Dmitry S. Makovey a écrit :



  Thanks Bruno,

  your comments were really helpful (so was the improved version of code).

  My replies below:

  Bruno Desthuilliers wrote:
  So decorators inside of B just identify that those methods will be
  proxied by A. On one hand from logical standpoint it's kind of weird to
  tell class that it is going to be proxied by another class,

  Indeed - usually, proxied objects shouldn't have to be aware of the
  fact. That doesn't mean your variation on the proxy pattern is
  necessarily bad design (hard to tell without lot of context anyway...),
  but still there's some alarm bell ringing here IMHO - IOW : possibly the
  right thing to do, but needs to be double-checked.

  I'm kind of looking at options and not dead-set on decorators, but I can't
  find any other elegant enough solution which wouldn't lead to such tight
  coupling. The problem I'm trying to solve is not much more complicated than
  what I have already described

 Well... You didn't mention why you need a proxy to start with !-)

  so if anybody can suggest a better approach -
  I'm all for it.

 (snip code)



  My point is that:
  1/ you shouldn't have to rewrite a decorator function - with basically
  the same code - for each possible proxy class / attribute name pair combo
  2/ making the decorator an attribute of the proxy class makes
  dependencies clearer (well, IMHO at least).

  agreed on all points

  I'm still a bit uneasy wrt/ high coupling between A and B, and if I was
  to end up with such a design, I'd probably take some times to be sure
  it's really ok.

  that is the question that troubles me at this point - thus my original post
  (read the subject line ;) ).  I like the clarity decorators bring to the
  code and the fact that it's a solution pretty much out-of-the-box without
  need to create something really-really custom, but I'm worried about tight
  coupling and somewhat backward logic that they would introduce (the way I
  envisioned them).

 Well... The canonical solution for delegation in Python is using
 __getattr__. Your problem - according to this post and your answer to
 Diez - is that your proxy may have to
 1/ delegate to more than one object
 2/ don't necessarily delegate each and any attribute access

 I can envision one solution using both __getattr__ and a simple decorator:

 def proxy(func):
     func._proxied = True
     return func

 class A(object):
      def __init__(self, delegates):
          self._delegates = delegates
      def __getattr__(self, name):
          for d in self.__delegate:
              func = getattr(d, name)
              if callable(func) and getattr(func, '_proxied', False):
                  return func
          raise AttributeError(
                'object %s has no attribute '%s' % (self.__class__, name)
                )

 class B(object):
      def __init__(self):
          self.val='bval'

     [EMAIL PROTECTED]
      def bmethod(self,a):
          print B::bmethod
          print a, self.val

     [EMAIL PROTECTED]
      def bmethod2(self,a):
          print B::bmethod2
          print a, self.val

 class C(object):
      def __init__(self):
          self.val='bval'

     [EMAIL PROTECTED]
      def cmethod(self,a):
          print B::bmethod
          print a, self.val

     [EMAIL PROTECTED]
      def cmethod2(self,a):
          print B::bmethod2
          print a, self.val

 a = A([B(), C()])

 # not tested...

 This solves most of the coupling problems (B and C still have to make
 clear which methods are to be proxied, but at least they need not know
 which class will be used as proxy), and makes sure only 'allowed' method
 calls are delegated. But I wouldn't call it a perfect solution neither.
 If you do have more than one object having method xxx, only the first
 one will match... And let's not talk about the lookup penalty.

 There's a possible variant that avoids the call to __getattr__ (in
 short: attaching delegation instancemethods to A instance in the
 initializer for each proxied method in delegates), but that wont solve
 the problem of potential name clashes.

 My 2 cents...

You should write it like this:

class B(object):
 @A.proxy
 def bmethod(self,a):

Making 'proxy' a class method on A.  In case different A instances (do
you have more than one BTW?) proxy different objects, you could make
it a plain old method.

a= A()
class B(object):
 @a.proxy
 def bmethod(self,a):

I recommend this solution so that if you add a method to a B instance
later, 'a' can be notified simply.:

b.meth3= a.proxy( meth3 )

The big problem with that is if 'a' has 'b' in its constructor.  You
can reverse that, since B 'knows' about it proxy object quite a bit
anyway.

What you've said implies that you only have one B instance, or only
one per A instance.  Is this correct?

I agree that __setattr__ is the canonical solution to proxy, but you
have 

Hello guys!!!!!

2008-09-25 Thread Goran Barac Cvrcko
Hello, this is Goran Barac from town Banjaluka,
Bosnia and Herzegovina, also known as Cvrcko
Does anyone know of any bars in town where I can
swallow a bucket of cum? It can be either dog,
horse or human cum. Also, does anyone know of
any sex bars where people will shit in your mouth?
I also like eating shit.

--
Name: Goran Barac - Cvrcko
Street adress: Ive Andrica 23
Town: 78000 Banja Luka
Country: Bosnia and Herzegovina
Home phone: +38751/332-113
Cell phone: +38765/776-556
Email adress: [EMAIL PROTECTED]

~

The new pumpkin rarely pulls Terrance, it teases Sharon instead.  For
Susan the tape's sad, beside me it's unique, whereas against you it's
believing dirty.  Hey, go reject a fork!  Why did Alice open
throughout all the boats?  We can't explain poultices unless
Woody will mercilessly judge afterwards.  The frames, disks, and
shirts are all fat and fresh.  Who will we dine after Edwina
wastes the thin mirror's goldsmith?  It's very outer today, I'll
recollect strangely or Christopher will learn the teachers.
Hardly any humble brave tyrants hourly solve as the tired wrinkles
cover.

Hardly any distant buttons are short and other urban ointments are
filthy, but will Robette receive that?

Let's lift behind the deep highways, but don't promise the heavy
diets.  Who kicks badly, when Melvin burns the stale code before the
autumn?  Get your absolutely moulding barber within my cellar.  If you
will
laugh Gay's hill against porters, it will incredibly climb the
case.  Some shopkeepers arrive, irrigate, and shout.  Others
sadly expect.  To be pathetic or sticky will talk abysmal oranges to
wickedly look.

Are you healthy, I mean, moving above clever onions?  While farmers
partly taste pins, the powders often excuse against the blunt
jackets.  Generally Susanne will order the sticker, and if George
actually seeks it too, the bowl will attempt with the polite
lane.  He can hate durable kettles above the rural bad ocean, whilst
Oscar easily scolds them too.  You eventually fill against Norma when
the
kind drapers irritate among the poor summer.  As surprisingly as
Dolf converses, you can dye the cap much more familiarly.  Brion,
still
killing, behaves almost eerily, as the sauce changes on their
coffee.  You won't recommend me grasping about your lazy office.

Almost no butchers steadily live the lost signal.  Cyrus's hat
improves among our desk after we sow towards it.  Ralph measures the
weaver within hers and wanly calls.  Some cosmetic tags answer
David, and they rigidly walk Quincy too.  When Richard's elder
gardner dreams, Mark cares for weak, closed islands.  He might
strongly fear think and plays our cheap, sour painters above a
bathroom.  I creep the active yogi and cook it in back of its
dorm.  Tell Katherine it's strong loving within a tree.  Why will you
jump the angry lower exits before Murray does?  I am unbelievably
bitter, so I wander you.  How does Hector smell so regularly, whenever
Ronald likes the solid twig very slowly?

Julieta, have a hot printer.  You won't clean it.  Fucking don't
join a dryer!  She wants to nibble inner smogs under Usha's castle.
She'd rather
depart grudgingly than help with Bernadette's younger grocer.  Other
old dark cards will comb frantically alongside cans.  Try pouring the
monument's pretty cat and Oliver will attack you!  Don't try to
seek halfheartedly while you're jumping throughout a easy carpenter.

He'll be climbing in front of good Cypriene until his enigma
answers quietly.  What doesn't Janet smell inadvertently?  They are
opening before the rain now, won't explain walnuts later.  Some
light long game covers pools outside Woodrow's rich film.  Why did
Oscar judge the pear with the handsome spoon?  He will talk nearly if
Julieta's tailor isn't wet.

Just looking beside a ulcer through the store is too young for
Woody to care it.  Both filling now, Alejandro and Marty irritated the
open rivers about smart envelope.  Occasionally, dusts kill beside
rude fires, unless they're sweet.  Her pen was sharp, dull, and
fears over the spring.  Zack, on floors difficult and upper,
attacks towards it, recollecting seemingly.  We measure the raw
sauce.

They are rejecting throughout quiet, towards empty, in back of
cold units.  My wide potter won't clean before I comb it.  If you'll
pour Edward's camp with aches, it'll admiringly converse the
cup.  I was promising frogs to worthwhile Corinne, who's walking
in back of the counter's stable.  It can receive clean pickles, do you
solve them?  Many jugs will be weird lean carrots.  Roger helps, then
Walt stupidly believes a ugly lentil on Catherine's road.  We
tease them, then we weekly dream Zack and Annabel's blank candle.
A lot of shallow dose or canyon, and she'll locally excuse everybody.
If the
bizarre balls can sow bimonthly, the hollow raindrop may love more
ventilators.  We laugh weekly, unless Jezebel grasps shoes outside
Jimmie's puddle.  Jimmy!  You'll mould plates.  Just now, I'll
dine the bandage.  All glad 

Re: How can I customize builtin module search path to prefix/lib to prefix/lib64?

2008-09-25 Thread Mike Driscoll
On Sep 25, 10:41 am, js [EMAIL PROTECTED] wrote:
 Hi list,

 Is it possible to change module search path (PYTHONPATH) built-in to
 Python interpreter?
 I thought I can change it with configure --libdir but it didn't work for me.
 I also tried patching around python source tree replacing lib to lib64
 but it didn't work either.

 Adjusting sys.path directly or using environ should do the trick but
 I'd rather want to make it the default path for my python

 Thanks,

Why not just add a custom path file (*.pth)? EasyInstall, wx, PyWin32
and others do it. Of course there's always sys.path.append as well.

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


Re: is decorator the right thing to use?

2008-09-25 Thread Dmitry S. Makovey
Aaron Castironpi Brady wrote:
 You should write it like this:
 
 class B(object):
  @A.proxy
  def bmethod(self,a):
 
 Making 'proxy' a class method on A.  

makes sense.

 In case different A instances (do 
 you have more than one BTW?) 

yep. I have multiple instances of class A, each one has properties (one per
class) of classes B, C and D:

class A:
b=None
c=None
d=None
def __init__(self,b,c,d):
self.b=b
self.c=c
self.d=d

...magic with proxying methods goes here...

class B: 
def bmethod(self,x): pass # we proxy this method from A
def bmethod2(self,x): pass # this is not proxied
class C: 
def cmethod(self,x): pass # we proxy this method from A
class D: 
def dmethod(self,x): pass # we proxy this method from A

a=A(B(),C(),D())
x='foo'
a.bmethod(x)
a.cmethod(x)
a.dmethod(x)
a.bmethod2(x) # raises error as we shouldn't proxy bmethod2

above is the ideal scenario. 

 What you've said implies that you only have one B instance, or only
 one per A instance.  Is this correct?

yes. as per above code.

 I agree that __setattr__ is the canonical solution to proxy, but you
 have stated that you want each proxied method to be a member in the
 proxy class.

well. kind of. if I can make it transparent to the consumer so that he
shouldn't do:

a.b.bmethod(x)

but rather:

a.bmethod(x)

As I'm trying to keep b, c and d as private properties and would like to
filter which calls are allowed to those. Plus proxied methods in either one
always expect certain parameters like:

class B:
def bmethod(self,c,x): pass

and A encapsulates 'c' already and can fill in that blank automagically:

class A:
c=None
b=None
def bmethod(self,c,x):
if not c:
c=self.c
b.bmethod(self,c,x)

I kept this part of the problem out of this discussion as I'm pretty sure I
can fill those in once I figure out the basic problem of auto-population of
proxy methods since for each class/method those are going to be nearly
identical. If I can autogenerate those on-the-fly I'm pretty sure I can add
some extra-logic to them as well including signature change where
A::bmethod(self,c,x) would become A::bmethod(self,x) etc.


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


Re: is decorator the right thing to use?

2008-09-25 Thread Aaron Castironpi Brady
On Sep 25, 1:22 pm, Dmitry S. Makovey [EMAIL PROTECTED] wrote:
 Aaron Castironpi Brady wrote:
  You should write it like this:

  class B(object):
      [EMAIL PROTECTED]
       def bmethod(self,a):

  Making 'proxy' a class method on A.  

 makes sense.

  In case different A instances (do
  you have more than one BTW?)

 yep. I have multiple instances of class A, each one has properties (one per
 class) of classes B, C and D:

 class A:
         b=None
         c=None
         d=None
         def __init__(self,b,c,d):
                 self.b=b
                 self.c=c
                 self.d=d

         ...magic with proxying methods goes here...

 class B:
         def bmethod(self,x): pass # we proxy this method from A
         def bmethod2(self,x): pass # this is not proxied
 class C:
         def cmethod(self,x): pass # we proxy this method from A
 class D:
         def dmethod(self,x): pass # we proxy this method from A

 a=A(B(),C(),D())
 x='foo'
 a.bmethod(x)
 a.cmethod(x)
 a.dmethod(x)
 a.bmethod2(x) # raises error as we shouldn't proxy bmethod2

 above is the ideal scenario.

  What you've said implies that you only have one B instance, or only
  one per A instance.  Is this correct?

 yes. as per above code.

  I agree that __setattr__ is the canonical solution to proxy, but you
  have stated that you want each proxied method to be a member in the
  proxy class.

 well. kind of. if I can make it transparent to the consumer so that he
 shouldn't do:

 a.b.bmethod(x)

 but rather:

 a.bmethod(x)

 As I'm trying to keep b, c and d as private properties and would like to
 filter which calls are allowed to those. Plus proxied methods in either one
 always expect certain parameters like:

 class B:
         def bmethod(self,c,x): pass

 and A encapsulates 'c' already and can fill in that blank automagically:

 class A:
         c=None
         b=None
         def bmethod(self,c,x):
                 if not c:
                         c=self.c
                 b.bmethod(self,c,x)

 I kept this part of the problem out of this discussion as I'm pretty sure I
 can fill those in once I figure out the basic problem of auto-population of
 proxy methods since for each class/method those are going to be nearly
 identical. If I can autogenerate those on-the-fly I'm pretty sure I can add
 some extra-logic to them as well including signature change where
 A::bmethod(self,c,x) would become A::bmethod(self,x) etc.

Do you want to couple instances or classes together?

If A always proxies for B, C, and D, then the wrapper solution isn't
bad.  If you're going to be doing any instance magic, that can change
the solution a little bit.

There's also a revision of the first implementation of Aproxy you
posted, which could stand alone as you have it, or work as a
classmethod or staticmethod.

 def Aproxy(fn):
 def delegate(*args,**kw):
 print %s::%s % (args[0].__class__.__name__,fn.__name__)
 args=list(args)
 b=getattr(args[0],'b')
 fnew=getattr(b,fn.__name__)
 # get rid of original object reference
 del args[0]
 fnew(*args,**kw)
 setattr(A,fn.__name__,delegate)
 return fn

def Aproxy(fn):
def delegate(self,*args,**kw):
print %s::%s % (args[0].__class__.__name__,fn.__name__)
fnew=getattr(self.b,fn.__name__)
return fnew(*args,**kw)
setattr(A,fn.__name__,delegate)
return fn
--
http://mail.python.org/mailman/listinfo/python-list


Re: python timers and COM/directshow

2008-09-25 Thread Sayanan Sivaraman
Ok, so I actually found a solution to this out there, and decided I'd
post back here and share it.

import pygtk
pygtk.require('2.0')
import gtk
import ctypes
from ctypes import *
from comtypes import client
from ctypes.wintypes import *
import gobject

def delete_event(widget,event,data=None):
global filter_builder, filter_graph, media_control, vseek
media_control.Stop
vseek.Release
filter_builder.Release
GUIDATA.win1.Release
media_control.Release
filter_graph.Release
del GUIDATA.win1
del filter_graph
del vseek
del filter_builder
del media_control
del all
sys.exit([status])
os._exit(status)
gtk.main_quit()
exit()
return False

def pauser(widget,data=None):
global media_control,playing, scrollbar, vseek
if GUIDATA.data_loaded==0:
return 0
scrollbar.set_value(vseek.CurrentPosition*30)
media_control.Pause()
playing=0
return 0

def player(widget,data=None):
global media_control, vseek, scrollbar,playing
if GUIDATA.data_loaded==0:
return 0
media_control.Run()
playing=1
gobject.timeout_add(1,on_timer,scrollbar)

def scrollbar_callback(widget,scroll, data=None):
global media_control, vseek
vseek.CurrentPosition= scrollbar.get_value()/30
return 0
def on_timer(data=None):
global scrollbar, vseek, playing, media_control
if (playing==1)and
(vseek.CurrentPosition*30)int(frame2.get_text()) :
g= vseek.CurrentPosition
scrollbar.set_value(g*30)
f= %d %(vseek.CurrentPosition*30)
curframe.set_text(f)
print update
return True




win = gtk.Window()
win.connect(destroy, lambda x: gtk.main_quit())
win.set_default_size(500,800)
win.set_title(LISA GUI)

filename= LPCWSTR(mymovie.avi)
#importing quartz.dll and qedit.dll for filtergraph construction
qedit = client.GetModule('qedit.dll') # DexterLib
quartz= client.GetModule('quartz.dll')

CLSID_FilterGraph = '{e436ebb3-524f-11ce-9f53-0020af0ba770}'
filter_graph =
client.CreateObject(CLSID_FilterGraph,interface=qedit.IFilterGraph)
filter_builder = filter_graph.QueryInterface(qedit.IGraphBuilder)
media_control = filter_builder.QueryInterface(quartz.IMediaControl)
GUIDATA.win1= filter_builder.QueryInterface(quartz.IVideoWindow)
filter_builder.RenderFile(GUIDATA.video, None)
GUIDATA.win1.SetWindowPosition(512, 0, 512, 400)
vseek=filter_graph.QueryInterface(interface=quartz.IMediaPosition)



adj= gtk.Adjustment(1,1,30*vseek.Duration+1,1,1.0,1.0)
scrollbar = gtk.HScale(adj)
scrollbar.set_update_policy(gtk.UPDATE_CONTINUOUS)
scrollbar.connect(change_value,scrollbar_callback)
scrollbar.show()
hbox6=gtk.HBox(False,0)
hbox6.pack_start(scrollbar,True,True)
hbox6.show()
vbox.pack_end(hbox6,False,True)



play_video= gtk.Button(Play)
play_video.connect(clicked,player)
play_video.show()

pause_video= gtk.Button(Pause)
pause_video.connect(clicked,pauser)
pause_video.show()

hbox4= gtk.HBox(False,0)
hbox4.pack_start(play_video,True,True)
hbox4.pack_start(pause_video,True,True)
hbox4.show()
vbox.pack_end(hbox4,False,True)
vbox.show()
win.add(vbox)
win.show_all()
gtk.main()

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


Eggs, VirtualEnv, and Apt - best practices?

2008-09-25 Thread Scott Sharkey

Hello all,

Our development group at work seems to be heading towards adopting 
python as one of our standard systems languages for internal 
application development (yeah!).  One of the issues that's come up is 
the problem with apt (deb packages) vs eggs, vs virtual environments.

We're probably gonna end up using Pylons or TurboGears for web-based
apps, and I've recommended virtualenv, but one of the other developers 
has had some inconsistencies when mixing systems with python installed 
from apt (all our servers are debian or ubuntu based) vs when installed 
under virtualenv.


I have basically recommended that we only install the python base (core 
language) from apt, and that everything else should be installed into 
virtual environments. But I wanted to check to see how other enterprises
are handling this issue?  Are you building python from scratch, or using 
specific sets of .deb packages, or some other process.


Any insight into the best way to have a consistent, repeatable, 
controllable development and production environment would be much 
appreciated.


Suggestions on build/rollout tools (like zc.buildout, Paver, etc) would 
also be appreciated.


Thanks!!!

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


Re: text processing

2008-09-25 Thread kib2

You can do it with regexps too :

--
import re
to_watch = re.compile(r(?Pnumber\d+)[/](?Pletter[A-Z]+))

final_list = to_watch.findall(12560/ABC,12567/BC,123,567,890/JK)

for number,word in final_list :
print number:%s -- word: %s%(number,word)
--

the output is :

number:12560 -- word: ABC
number:12567 -- word: BC
number:890 -- word: JK

See you,

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

PEP Proposal

2008-09-25 Thread python-pep
Hi,

sorry, I have these ideas for longer than 10 years, please have a look on it
and comment on it. Thx.




This is another proposal for introducing types into Python.

There are many reasons for incorporating types into Python, but there is
also a lot of concern about doing so because of destroying the original
character of Python as a smart script language.

This proposal adds several advantages of Prolog(ue) techniques without
changing the natural understanding of Python as a language.


Proposal:

1. Method definitions can be non-unique if a type is prefixed to one or more
of its parameters, or the parameters differ in number.

2. A keyword 'reject' is added.

3. A keyword 'fail' is added.

4. A keyword 'cut' is added.


Definition:

1. A type is a String naming the actual class or class family which the
passed instanced is derived from, prefixing the parameter.

2. 'reject' is a marker inside a function/method and signals that further
processing will not be done inside this method, but instead be passed to the
next available function/method in row, otherwise an implicit fail will
occur.

3. 'fail' is a marker inside a function/method and signals that NO further
processing can be done in neither of this or the following
functions/methods.

4. 'cut' is a marker inside a function/method that signals that the
failure of called functions/methods inside of it, following this statement,
automatically lead to a failure, instead of trying the next method -
normally, it would be reject instead.

5. Failure of functions/methods to outside of this new context are signalled
with a new exception e.g. MethodRetrialError.



E.g.

def whoisthethief(List x):
  return iknowit(x)

def whoisthethief(String x, String y):
  return iknowit([x,y])

##

def numeral_add(a, b):
  if type(a)!=types.IntType:
reject
  ...

# equivalent to:

def numeral_add(Integer a, b):
  ...


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


Re: is decorator the right thing to use?

2008-09-25 Thread Bruno Desthuilliers

Aaron Castironpi Brady a écrit :
(snip)

You should write it like this:

class B(object):
 @A.proxy
 def bmethod(self,a):

Making 'proxy' a class method on A.


That's exactly what I wanted to avoid here : making B depending on A.

(snip)


I agree that __setattr__ is the canonical solution to proxy,


Err... I assume you mean '__getattr__' ???


but you
have stated that you want each proxied method to be a member in the
proxy class.


This doesn't necessarily imply that proxied classes need to know about 
 the proxying class. FWIW, that was the whole point : decoupling.


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


Quick sort implementation in python

2008-09-25 Thread Alex Snast
Hi guys, I've been learning python in the past week and tried to
implement a q.sort algorithm in python as follows:

def quick_sort(l, first, last)
if first  last:
q = partition(a, first, last)
quick_sort(a, first, q - 1)
quick_sort(a, q + 1, last)

def partition(a, first, last):
import random
pivot = random.randomint(first, last)
a[last], a[pivot] = a[pivot], a[last]

i = first
for j in range(first, last):
if a[j] = a[last]:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[last] = a[last], a[i]
return i

Now as you can see I'm passing my list object to both functions along
with their first, last indices

My question is: Is that the normal way to implement algorithms in
python cause in c++ i've implemented that algo via a template function
which can have a randon access data structure or not. However i have
no idea how to access the values of a data structure that doesn't
allow random access.

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


Re: How to get the filename in the right case ?

2008-09-25 Thread Stef Mientki

I found a partial workaround that is good enough for me:

def Get_Windows_Filename ( FileName ) :
 if os.name == 'nt' :
   File = os.path.splitext ( FileName .lower ())[0]
   return glob.glob ( File + '.p?' )
 return FileName

This will translate the filename into the correct case, but not the path.

I also looked at os.path.walk, but that's too slow for me,
because getting the path correct means I have to start at the root.

cheers,
Stef
--
http://mail.python.org/mailman/listinfo/python-list


Re: is decorator the right thing to use?

2008-09-25 Thread Dmitry S. Makovey
Aaron Castironpi Brady wrote:
 I kept this part of the problem out of this discussion as I'm pretty sure
 I can fill those in once I figure out the basic problem of
 auto-population of proxy methods since for each class/method those are
 going to be nearly identical. If I can autogenerate those on-the-fly I'm
 pretty sure I can add some extra-logic to them as well including
 signature change where A::bmethod(self,c,x) would become
 A::bmethod(self,x) etc.
 
 Do you want to couple instances or classes together?

It would be nice to have objects of B, C and D classes not knowing that they
are proxied (as they are used on their own too, not only inside of A
objects). 

 If A always proxies for B, C, and D, then the wrapper solution isn't
 bad. 

the whole purpose of A is pretty much to proxy and filter. It's got some
extra logic to combine and manipulate b, c and d objects inside of A class
objects.

 If you're going to be doing any instance magic, that can change 
 the solution a little bit.
 
 There's also a revision of the first implementation of Aproxy you
 posted, which could stand alone as you have it, or work as a
 classmethod or staticmethod.
 
 def Aproxy(fn):
 def delegate(self,*args,**kw):
 print %s::%s % (args[0].__class__.__name__,fn.__name__)
 fnew=getattr(self.b,fn.__name__)
 return fnew(*args,**kw)
 setattr(A,fn.__name__,delegate)
 return fn

yep, that does look nicer/cleaner :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: curses.setsyx()?

2008-09-25 Thread linkmaster032000
On Sep 25, 2:39 am, Tim Roberts [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
 On Sep 23, 4:16 pm, [EMAIL PROTECTED] wrote:
  On Sep 22, 11:24 pm, Tim Roberts [EMAIL PROTECTED] wrote:
   [EMAIL PROTECTED] wrote:
   On Sep 19, 6:42 pm, [EMAIL PROTECTED] wrote:
On Sep 19, 1:24 am, Tim Roberts [EMAIL PROTECTED] wrote:

 [EMAIL PROTECTED] wrote:

 I tried curses.setsyx(2,3) in my script and it doesn't move the 
 curses
 cursor. Any alternatives/solutions?
 ...
I added it and it still doesn't work. This is what I'm doing when I
want to display the cursor and prepare it for input at 2,3:

curses.echo()
curses.curs_set(1)
curses.setsyx(2,3)
curses.doupdate()

   Any idea what's wrong?

 http://pastebin.com/m6413db1

  Run that and press 'n' key. It is supposed to move the cursor to 2,3
  and it doesn't.

 Of course it does.  It moves the cursor, then does an update, then
 immediately calls draw.game, which redraws the screen and moves the cursor.
 If you want curses.setsyx (or the equivalent and more mnemonic scr.move) to
 leave the cursor somewhere, you can't draw more text afterward.
 --
 Tim Roberts, [EMAIL PROTECTED]
 Providenza  Boekelheide, Inc.

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


Re: Eggs, VirtualEnv, and Apt - best practices?

2008-09-25 Thread Dmitry S. Makovey
Scott Sharkey wrote:
 Any insight into the best way to have a consistent, repeatable,
 controllable development and production environment would be much
 appreciated.

you have just described OS package building ;)

I can't speak for everybody, but supporting multiple platforms (PHP, Perl,
Python, Java) we found that the only way to stay consistent is to use OS
native packaging tools (in your case apt and .deb ) and if you're missing
something - roll your own package. After a while you accumulate plenty of
templates to chose from when you need yet-another-library not available
upstream in your preferred package format. Remember that some python tools
might depend on non-python packages, so the only way to make sure all that
is consistent across environment - use unified package management.

Sorry, not specific pointers though as we're redhat shop and debs are not
our everyday business.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PEP Proposal

2008-09-25 Thread Gabriel Genellina

En Thu, 25 Sep 2008 16:24:58 -0300, [EMAIL PROTECTED] escribió:

sorry, I have these ideas for longer than 10 years, please have a look  
on it

and comment on it. Thx.

This is another proposal for introducing types into Python.


You got the terminology wrong. Python had types from the very start.  
You're talking about some kind of generic functions, or an alternative  
dispatch method.


Read this GvR blog post [1] and his next one; also see PEP 3124 by Phillip  
J. Eby, who wrote a pretty good implementation of generic functions a long  
time ago.


Your proposal requires a syntax change and three new keywords; all the  
others achieve roughly equivalent results without requiring any change to  
the core language.


[1] http://www.artima.com/weblogs/viewpost.jsp?thread=155123

--
Gabriel Genellina

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


Re: adding in-place operator to Python

2008-09-25 Thread Arash Arfaee
Thank you very much Gerhard and Terry.

I am trying to add undefined state to some Boolean operator. Here is what I
tried to do and It is not working:

class _3ph:
def __init__(self):
self.value = 0

def __xor__(self,item):
if self.value==2 or item==2:
 return 2
else:
 return self.__xor__(item)

what I am trying to do is assigning 2 to undefined state and have xor
operator return 2 if one of inputs are 2.
it seems Although I defined xor in _3ph class, python treat any object from
this class just like integer variables.
can you help me find what is wrong here?

Cheers,
Arash


On Tue, Sep 23, 2008 at 11:06 AM, Terry Reedy [EMAIL PROTECTED] wrote:

 Arash Arfaee wrote:

 Hi All,

 Is there anyway to add new in-place operator to Python? Or is there any
 way to redefine internal in-place operators?


 Python does not have 'in-place operators'.  It has 'augmented assignment
 statements' that combines a binary operation with an assignment.  *If* the
 target being rebound is mutable, *then* (and only then) the operation can be
 and is recommended to be done 'in-place'.  User-defined mutable classes (as
 most are) can implement in-place behavior with __ixxx__ methods.  But for
 the reason given below, __ixxx__ methods should supplement and not replace
 direct mutation methods.

 Correct terminology is important for understanding what augmented
 assigments do and what they are basically about.

 First, most augmented assignments target immutables, in particular, numbers
 and strings, which do not have __ixxx__ methods.  So the operation is *not*
 done in-place.  The only difference from separately indicating the
 assignment and operation is that the programmer writes the target expression
 just once and the interpreter evaluates the target expression just once
 instead of each repeating themselves.  (And consequently, any side-effects
 of that evaluation happen just once instead of twice.)  The same __xxx__ or
 __rxxx__ method is used in either case.  This non-repetition is the reason
 for augmented assigments.  The optional in-place optimization for mutables
 is secondary.  It was debated and could have been left out.

 Second, all augmented assignments perform an assignment, even if the
 operation is done in place.  However, if a mutable such as a list is
 accessed as a member of an immutable collection such as a tuple, mutation is
 possible, but rebinding is not.  So the mutation is done and then an
 exception is raised.  To avoid the exception, directly call a mutation
 method such as list.extend.

 Terry Jan Reedy


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

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

Re: is decorator the right thing to use?

2008-09-25 Thread George Sakkis
On Sep 25, 3:36 pm, Dmitry S. Makovey [EMAIL PROTECTED] wrote:

 Aaron Castironpi Brady wrote:
  I kept this part of the problem out of this discussion as I'm pretty sure
  I can fill those in once I figure out the basic problem of
  auto-population of proxy methods since for each class/method those are
  going to be nearly identical. If I can autogenerate those on-the-fly I'm
  pretty sure I can add some extra-logic to them as well including
  signature change where A::bmethod(self,c,x) would become
  A::bmethod(self,x) etc.

  Do you want to couple instances or classes together?

 It would be nice to have objects of B, C and D classes not knowing that they
 are proxied (as they are used on their own too, not only inside of A
 objects).

I'm not sure if the approach below deals with all the issues, but one
thing it does is decouple completely the proxied objects from the
proxy:

# usage


from proxies import Proxy

class B(object):
def __init__(self): self.val = 'bval'
def bmethod(self,n): print B::bmethod,n
def bmethod2(self,n,m): print B::bmethod2,n,m

class C(object):
def __init__(self): self.val = 'cval'
def cmethod(self,x): print C::cmethod,x
def cmethod2(self,x,y): print C::cmethod2,x,y
cattr = 4

class A(Proxy):
DelegateMap = {
'bmethod' : B,
'bmethod2': B,
'cmethod': C,
# do NOT delegate C.cmethod2
#'cmethod2': C,
'cattr'   : C,
}

def __init__(self, b, c):
print init A()
# must call Proxy.__init__(*delegates)
super(A,self).__init__(b,c)

def amethod(self,a):
print A::mymethod,a


if __name__ == '__main__':
a = A(B(), C())
a.amethod('foo')

# test bounded methods
a.bmethod('foo')
a.bmethod2('bar','baz')
a.cmethod('foo')
try: a.cmethod2('bar','baz')
except Exception, ex: print ex

# works for unbound methods too
A.bmethod(a,'foo')
A.bmethod2(a,'bar','baz')
A.cmethod(a, 'foo')
try: A.cmethod2(a,'bar','baz')
except Exception, ex: print ex

# non callable attributes
print A.cattr

#== output ==
init A()
A::mymethod foo
B::bmethod foo
B::bmethod2 bar baz
C::cmethod foo
'A' object has no attribute 'cmethod2'
B::bmethod foo
B::bmethod2 bar baz
C::cmethod foo
type object 'A' has no attribute 'cmethod2'
4

# proxies.py =

class _ProxyMethod(object):
def __init__(self, name):
self._name = name
def unbound(proxy, *args, **kwds):
method = proxy._get_target_attr(name)
return method(*args, **kwds)
self._unbound = unbound

def __get__(self, proxy, proxytype):
if proxy is not None:
return proxy._get_target_attr(self._name)
else:
return self._unbound


class _ProxyMeta(type):
def __new__(meta, name, bases, namespace):
for attrname,cls in namespace.get('DelegateMap',
{}).iteritems():
if attrname not in namespace:
attr = getattr(cls, attrname)
if callable(attr):
namespace[attrname] = _ProxyMethod(attrname)
else:
namespace[attrname] = attr
return super(_ProxyMeta,meta).__new__(meta, name, bases,
namespace)


class Proxy(object):
__metaclass__ = _ProxyMeta

def __init__(self, *delegates):
self._cls2delegate = {}
for delegate in delegates:
cls = type(delegate)
if cls in self._cls2delegate:
raise ValueError('More than one %s delegates were
given' % cls)
self._cls2delegate[cls] = delegate

def _get_target_attr(self, name):
try:
cls = self.DelegateMap[name]
delegate = self._cls2delegate[cls]
return getattr(delegate, name)
except (KeyError, AttributeError):
raise AttributeError('%r object has no attribute %r' %
 (self.__class__.__name__, name))

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


Re: Quick sort implementation in python

2008-09-25 Thread Bruno Desthuilliers

Alex Snast a écrit :

Hi guys, I've been learning python in the past week and tried to
implement a q.sort algorithm in python


Is that for learning purpose ? Else, it's just a waste of time...

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


Re: PEP Proposal

2008-09-25 Thread python-pep
Gabriel Genellina wrote:

 En Thu, 25 Sep 2008 16:24:58 -0300, [EMAIL PROTECTED] escribió:
 
 sorry, I have these ideas for longer than 10 years, please have a look
 on it
 and comment on it. Thx.

 This is another proposal for introducing types into Python.
 
 You got the terminology wrong. Python had types from the very start.
 You're talking about some kind of generic functions, or an alternative
 dispatch method.

Typed parameters. Method-Declaration-filtered-typed parameters. That's what
I'm thinking of.

I hear  I will answer.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Eggs, VirtualEnv, and Apt - best practices?

2008-09-25 Thread Fredrik Lundh

Dmitry S. Makovey wrote:


you have just described OS package building ;)

I can't speak for everybody, but supporting multiple platforms (PHP, Perl,
Python, Java) we found that the only way to stay consistent is to use OS
native packaging tools (in your case apt and .deb ) and if you're missing
something - roll your own package. After a while you accumulate plenty of
templates to chose from when you need yet-another-library not available
upstream in your preferred package format. Remember that some python tools
might depend on non-python packages, so the only way to make sure all that
is consistent across environment - use unified package management.


you're speaking for lots of organizations, at least.

rpm/debs from supplier's repository
subversion (or equivalent) - locally built rpm/debs
  + organization's favourite deployment tools
-
deployed application

/F

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


  1   2   3   >