Re: os.path.expanduser('~/foo') and MSWindows "My Documents"

2005-11-18 Thread dalius . dobravolskas
python

>>> import os
>>> help(os.path.expanduser)
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'XP'
>>>

:-)

Dalius

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


Re: Newbie question: does file("text.txt', "w").write("stuff") ever get closed?

2005-11-18 Thread Fredrik Lundh
"John Doe" <[EMAIL PROTECTED]> wrote:

> In an effort to avoid another potential mistake, I am wondering if the
> anonymous file object/class/thingy that I create when I do file("text.txt',
> "w").write("stuff") gets closed properly on exit or garbage collection or
> something

yes.

> or if I always need to hang on to these things and close them myself.

only if you want to 1) know exactly when the files are closed, or 2) are
using so many files that the garbage collector cannot keep up with you
(this never happens on CPython, but can, at least in theory, happen on
other Python implementations)

 



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


Announce: PythonD 2.4.2 r 1.0 for DJGPP/DOS/Windows

2005-11-18 Thread bdeck
Hello,

We have uploaded binary and source packages of PythonD 2.4.2 release
1.0 for DJGPP/MSDOS/Windows to the 'pythond' page at
http://www.caddit.net. All PythonD users are encouraged to upgrade.
There have been many enhancements, including:

Smaller & faster executable size.

Long Filename TSR under DOS and NT 4 is now mandatory!

$DJDIR/site_python is now searched as part of the default path
(provides room for deeper
packages under MSDOS 8-directory restriction.

Socket module has been upgraded to Watt-32 2.8 without SSL support.

An additional SSL (OpenSSL-based) library is provided separately.

Better/more stable thread support (library recompile under better env)

Limited-method release of the MS-specific 'msvcrt' module provides
DOS-specific API:
getch, getche, kbhit, putch, setmode, ungetch

Some Watt-32 specific socket errnos have been corrected from the 2.2
release.

The DB module has forked into 2 separate modules: bsddb (3.0+) and
bsddb185.
The DOS library has been recompiled based on sleepycat 3.17 release for
both.
Use of the 'bsddb' module (not 185) is prefered, although DBEnv will
not work.

Additional goodies (plenty!) have been provided under the
lib/python2.4/site-packeges
directory! Google if you don't know what they do. Dat's all folks!

#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!
The Python source itself has greatly improved. From Python website:
We are pleased to announce the release of Python 2.4, final on November
30, 2004. This is a final, stable release, and we can recommend that
Python users upgrade to this version.

Note: there's a security fix for SimpleXMLRPCServer.py - this fix is
included in 2.4.1
Python 2.4 is the result of almost 18 month's worth of work on top of
Python 2.3 and represents another stage in the careful evolution of
Python. New language features have been kept to a minimum, many bugs
have been fixed and a variety of improvements have been made.

Notable changes in Python 2.4 include improvements to the importing of
modules, function decorators, generator expressions, a number of new
modules (including subprocess, decimal and cookielib) and a host of bug
fixes and other improvements. See the (subjective) highlights or the
detailed release notes for more, or consult Andrew Kuchling's What's
New In Python for a detailed view of some of the new features of Python
2.4.


#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!
PYTHOND is now on IRC! Go to #pythond on irc.freenode.net!

Thanks

Ben

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


need help about time.sleep, timer

2005-11-18 Thread Sinan Nalkaya
hello,
i need a function like that,
wait 5 seconds:
(during wait) do the function
but function waits for keyboard input so if you dont enter any it waits 
forever.
i tried time.sleep() but when i used time.sleep in while, the function 
in while never executed.
then i found something about Timer but couldnt realize any algorithm in 
my mind.
i`ll use the function like remote controller. as you know in remote 
controllers, tv waits you for second number input. if you dont press 
any, executes the first number that you have entered.
thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Announce: PythonD 2.4.2 r 1.0 for DJGPP/DOS/Windows

2005-11-18 Thread Claudio Grondi
I have read the announcement and checked out the homepage, but I am still
missing the point.

May someone explain to me, what PythonD is good for?
In my eyes there is sufficient support for networking and OpenGL in Python,
so why another not compatible version?

Claudio

"bdeck" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> Hello,
>
> We have uploaded binary and source packages of PythonD 2.4.2 release
> 1.0 for DJGPP/MSDOS/Windows to the 'pythond' page at
> http://www.caddit.net. All PythonD users are encouraged to upgrade.
> There have been many enhancements, including:
>
> Smaller & faster executable size.
>
> Long Filename TSR under DOS and NT 4 is now mandatory!
>
> $DJDIR/site_python is now searched as part of the default path
> (provides room for deeper
> packages under MSDOS 8-directory restriction.
>
> Socket module has been upgraded to Watt-32 2.8 without SSL support.
>
> An additional SSL (OpenSSL-based) library is provided separately.
>
> Better/more stable thread support (library recompile under better env)
>
> Limited-method release of the MS-specific 'msvcrt' module provides
> DOS-specific API:
> getch, getche, kbhit, putch, setmode, ungetch
>
> Some Watt-32 specific socket errnos have been corrected from the 2.2
> release.
>
> The DB module has forked into 2 separate modules: bsddb (3.0+) and
> bsddb185.
> The DOS library has been recompiled based on sleepycat 3.17 release for
> both.
> Use of the 'bsddb' module (not 185) is prefered, although DBEnv will
> not work.
>
> Additional goodies (plenty!) have been provided under the
> lib/python2.4/site-packeges
> directory! Google if you don't know what they do. Dat's all folks!
>
>
#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!
#!#!#!#!
> The Python source itself has greatly improved. From Python website:
> We are pleased to announce the release of Python 2.4, final on November
> 30, 2004. This is a final, stable release, and we can recommend that
> Python users upgrade to this version.
>
> Note: there's a security fix for SimpleXMLRPCServer.py - this fix is
> included in 2.4.1
> Python 2.4 is the result of almost 18 month's worth of work on top of
> Python 2.3 and represents another stage in the careful evolution of
> Python. New language features have been kept to a minimum, many bugs
> have been fixed and a variety of improvements have been made.
>
> Notable changes in Python 2.4 include improvements to the importing of
> modules, function decorators, generator expressions, a number of new
> modules (including subprocess, decimal and cookielib) and a host of bug
> fixes and other improvements. See the (subjective) highlights or the
> detailed release notes for more, or consult Andrew Kuchling's What's
> New In Python for a detailed view of some of the new features of Python
> 2.4.
>
>
>
#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!
#!#!#!#!
> PYTHOND is now on IRC! Go to #pythond on irc.freenode.net!
>
> Thanks
>
> Ben
>



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


Ajax for the Developers

2005-11-18 Thread Sabin.A.K, Bangalore
Seen that AJAX makes the Python interfaces bit more User friendly. The
Page refresh problems for the huge applications has slashed down
extensively. Page reload has been faded out and eventually the Server
responses been printed out in the same page itself. The trendy XML HTTP
Request has really struck the way developers had adopted with the user
interfaces. But the major issuse are yet to be solved..

1. Changing state with links (GET requests)
2.Asynchronously performing batch operations
3.Breaking the back button

Will these get solved.



SABIN, Bangalore.

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


Re: Ajax for the Developers

2005-11-18 Thread Jean-Roch SOTTY
Le Vendredi 18 Novembre 2005 10:08, Sabin.A.K, Bangalore a écrit :
> 1. Changing state with links (GET requests)
> 2.Asynchronously performing batch operations
> 3.Breaking the back button
I'm looking for a response with Python MVC frameworks -- django, 
turbogears, 
etc. But you could consider looking at seaside[1] or wee[2] which are based 
on continuations.

[1] http://seaside.st/
[2] http://rubyforge.org/projects/wee


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


Column not updating in listbox in wxPython example ??

2005-11-18 Thread David Poundall
In the following example the phone number does not apear in the phone
column of the llistbox.  Can anybody tell me what I am doing wrong here
?

from wxPython.wx import *

class MyApp (wxApp) :
   def OnInit (self) :
  frame = MyFrame(NULL, -1, "Phone List")
  frame.Show(true)
  self.SetTopWindow (frame)
  return true

class MyFrame (wxFrame) :
   def __init__ (self, parent, ID, title) :

 self.lc = wxListCtrl(self,15,wxDLG_PNT(self,10,60),
   wxDLG_SZE(self,120,75),   style=wxLC_REPORT)
  EVT_LIST_ITEM_SELECTED(self,15,self.getSelect)
  self.lc.InsertColumn(0,"Name")
  self.lc.InsertColumn(1,"Phone")
  name = 'Peter'
  phone = '01753 865830'
  row = 1
  self.lc.InsertStringItem(row, name)
  self.lc.SetStringItem(row, 1, phone)

   def getSelect (self, event) :
  self.currentSel = event.m_itemIndex

app = MyApp(0)
app.MainLoop()

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


Re: sqlite utf8 encoding error

2005-11-18 Thread Manlio Perillo
On 17 Nov 2005 03:47:00 -0800, "Greg Miller" <[EMAIL PROTECTED]>
wrote:

>I have an application that uses sqlite3 to store job/error data.  When
>I log in as a German user the error codes generated are translated into
>German.  The error code text is then stored in the db.  When I use the
>fetchall() to retrieve the data to generate a report I get the
>following error:
>
>Traceback (most recent call last):
>  File "c:\Pest3\Glosser\baseApp\reportGen.py", line 199, in
>OnGenerateButtonNow
>self.OnGenerateButton(event)
>  File "c:\Pest3\Glosser\baseApp\reportGen.py", line 243, in
>OnGenerateButton
>warningresult = messagecursor1.fetchall()
>UnicodeDecodeError: 'utf8' codec can't decode bytes in position 13-18:
>unsupported Unicode code range
>
>does anyone have any idea on what could be going wrong?  The string
>that I store in the database table is:
>
>'Keinen Text für Übereinstimmungsfehler gefunden'
>
>I thought that all strings were stored in unicode in sqlite.
>


No, they are stored as UTF-8 in sqlite and pysqlite has no way to make
sure the string you insert into the database is really encoded in
UTF-8 (the only secure way is to use Unicode strings).

How did you insert that string?

As a partial solution, try to disable automatic conversion of text
fields in Unicode strings:


def convert_text(s):
# XXX do not use Unicode
return s


# Register the converter with SQLite
sqlite.register_converter("TEXT", convert_text)


...connect("...",
detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES
)




Regards  Manlio Perillo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Default method arguments

2005-11-18 Thread Gregory Petrosyan
Thanks Martin, you are right.

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


Re: Announce: PythonD 2.4.2 r 1.0 for DJGPP/DOS/Windows

2005-11-18 Thread Harald Armin Massa
Claudio,

maybe it's because PythonD is running within DOS?

(which, for archaelogical completeness, is an ancient operating system)

Harald

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


Re: Default method arguments

2005-11-18 Thread Peter Otten
Martin Miller wrote:

> Well, perhaps the same in the sense of name binding, but there's a
> subtle difference in replacing the 's = [n]'  with 'foo.s = n'.  Namely
> that in the former case (with the essay's original code) a separate
> container is created when foo() is first called and is what is used in
> subsequent calls to the function returned.  Whereas in the latter case
> where the foo object itself is used as the container, there's only a
> single container used by all returned objects -- which would cause
> problems if you try accumulating two or more different totals
> simultaneously.

[snip example using the outer foo() as a container]

You can easily get a unique container using the function attribute style, to
-- just use the inner function bar():

>>> def foo(n):
... def bar(i):
... bar.i += 1
... re
...
>>>
>>> def foo(n):
... def bar(i):
... bar.s += i
... return bar.s
... bar.s = n
... return bar
...
>>> a1 = foo(0)
>>> a2 = foo(0)
>>> a1(0), a2(0)
(0, 0)
>>> a1(1), a2(1)
(1, 1)

Peter

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


nanothreads: Want to use them from within wxPython app

2005-11-18 Thread F. GEIGER
I've def'ed a handler for EVT_IDLE in the app's main frame. There I'd like 
to call the nanothreads' __iter__ method, somehow.

When I copy the __iter__ method into a, say, runOnce() method and call the 
next() method of the generator returned by runOnce(), it works. But I can't 
get at the __iter__ method, which is already there and therefore should be 
used instead of messing up nanothreads with changes of mine.

Any hint welcome

Kind regards
Franz GEIGER


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


Re: Immutable instances, constant values

2005-11-18 Thread Bengt Richter
On Fri, 18 Nov 2005 14:32:46 +1100 (EST), Ben Finney <[EMAIL PROTECTED]> wrote:

>Howdy all,
>
>I've recently packaged 'enum' in PyPI. In its description, I make the
>claim that it creates "immutable" enumeration objects, and that the
>enumeration values are "constant" values.
>
>This raises questions.
>
>Is there any difference between a Python immutable value, and a
>constant? I suppose "constant" also implies that the *name* binds
>unchangeably to a particular value. Is that meaningful?
>
>How does one actually ensure an object is immutable? Is it a matter of
>overriding a bunch of methods, or is ther a neater way?
>
>Is it bad style to make a user-defined class that creates immutable
>objects? Why?
>
>In the case of 'enum', can anyone argue for or against an enumerated
>type being immutable? Its values being constant?
>
My notion of enum comes from (what I remember of) Pascal, which is
basically an ordered set of names of integers forming a type, and
ord(one_of_the_names) gets you the index value. Python's ord seems
to demand a string of length one, and doesn't seem to attempt coercion,
so that might not fly without a mod.

But what we have is named integers, much as True and False are built in
names for integer subtypes with value 1 and 0. So I'd say enums should
also be int subtypes...

Anyway, I would hope that the name->ord(name) mapping would be immutable
once defined (though not necessarily obsessively preventing the ususal end 
runs).
Hm, might as well be more concrete ...

 >>> def makeEnum(ename, names):
 ... names = names.split()
 ... top = len(names)
 ... # define method functions outside class so they'll be closures 
accessing nested names
 ... def __new__(cls, name=names[0]):
 ... try:
 ... i = names.index(name)
 ... return int.__new__(cls, i)
 ... except ValueError:
 ... if isinstance(name, int) and 0< name < top: return 
int.__new__(cls, name)
 ... raise ValueError, 'illegal %s enum value %r'%(cls.__name__, 
name)
 ... def __repr__(self): return '%s(%s)' %(self.__class__.__name__, 
names[self])
 ... # return names with names attribute of class or instance
 ... class getnames(object):
 ... def __set__(*ignore): raise AttributeError, 'names protected'
 ... getnames.__get__ = lambda *ignore: names[:]
 ... return type(ename, (int,),{'__new__':__new__, '__repr__':__repr__, 
'__str__':__repr__,
 ... 'names':getnames()})
 ...
 ...
 >>> Colors = makeEnum('Color', 'red green blue')
 >>> Colors
 
 >>> Colors()
 Color(red)
 >>> Colors(1)
 Color(green)
 >>> r,g,b = (Colors(name) for name in Colors.names)
 >>> r
 Color(red)
 >>> g
 Color(green)
 >>> b
 Color(blue)
 >>> 'ABC'[g]
 'B'
 >>> int(g)
 1
 >>> Colors(5)
 Traceback (most recent call last):
   File "", line 1, in ?
   File "", line 11, in __new__
 ValueError: illegal Color enum value 5
 >>> Colors('blue')
 Color(blue)
 >>> Colors(2)
 Color(blue)
 >>> Colors('orange')
 Traceback (most recent call last):
   File "", line 1, in ?
   File "", line 11, in __new__
 ValueError: illegal Color enum value 'orange'

Just some thoughts.
Oh, names are kind of protected by [:], but really should throw
an exception if you try to mutate.

 >>> Colors.names
 ['red', 'green', 'blue']
 >>> Colors.names[2]
 'blue'
 >>> Colors.names[2] = 'indigo'
 >>> Colors.names[2]
 'blue'

It would be easy to return a tuple.
It's not that easy to protect against Colors.names = something
since __metaclass__ skips factory local to global if not in class scope,
and passing a '__metaclass__': mcdefinition in the dict arg to type does
not result in a call, it just becomes another passive class variable.
Must be a way though. Too tired for now...

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


Re: Zope vs Php

2005-11-18 Thread Jorge Godoy
Mike Meyer <[EMAIL PROTECTED]> writes:

> Unfortunately, my tools don't - which is another one of the things I
> like about Cheetah: it doesn't interfere with my X/HTML tools. For
> instance, I edit attributes by asking the editor to let me edit the
> current tags attributes. It opens window with a list of valid
> attributes, along with type information about those attributes. I edit
> the list, close the window, and it inserts the required attributes,
> appropriately quoted, into the tag. I couldn't use that for py:*
> attributes without tweaking the DTD for each language I wanted to
> edit. Similar problems crop up with the other features that depend on
> information from the DTD.

What DTD do you use to write Python code?  ;-)

I can use my "HTML writing tool" with the XHTML, HTML, etc. DTD specified and
have it insert the tags for me.  The Python namespace allows me to insert
Python commands and still have valid (X)HTML output (at least tidy is very
happy with them).  After I have the mockup, with Python tags embedded, I send
the files to the webdesigners and they do their art. :-)

For one project we are using a lot of CSS and JavaScript.

But, as you can see with TurboGears, it's possible to do even more with it.

-- 
Jorge Godoy  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to write an API for a Python application?

2005-11-18 Thread Duncan Grisby
In article <[EMAIL PROTECTED]>, Cameron Laird <[EMAIL PROTECTED]> wrote:

[...]
>Indeed, Paul:  those who scorn CORBA often *do* re-create it,
>poorly.
>
>I still don't think it's the right answer for Mr. Kshepitzki.
>Pyro might be perfect.  My own instinct is to start even more
>primitively, with a minimal asynchat client and server.  I've
>looked through the *Cookbook*, and see that it doesn't have
>what I want.  Maybe it's time Phaseit donate one of the
>little models we use ...  

Pyro is definitely of no use to the original poster. He specifically
wants to access his Python server from languages other than Python.

To me, the situation sounds complex enough, especially with the need
for callbacks, that CORBA is an ideal solution. At the expense of a
small amount of boilerplate code, all the communication issues are
handled for you. In this day and age, why would you want to write code
that deals with sockets apart from the most specialist situations?

Cheers,

Duncan.

-- 
 -- Duncan Grisby --
  -- [EMAIL PROTECTED] --
   -- http://www.grisby.org --
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Importing a class without knowing the module

2005-11-18 Thread Franck PEREZ
On 11/18/05, Mike Meyer <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] (Alex Martelli) writes:
> > Mike Meyer <[EMAIL PROTECTED]> wrote:
> >...
> >> >> >> How about adding Foo.__file__ to the serialized data?
> >...
> >> >> depends on somewhere on it. You can use the module name if you have it
> >> >> available. If not, deriving the module name from the file name is
> >> >> about the best you can do.
> >> > I disagree with the last sentence.  From a filepath of
> >...
> >> You should read the next-to-last sentence, which says to use the
> >> module name if you have it. The last sentence starts "If not" -
> >> meaning you don't have the module name. *That's* the case for which
> >> the file name is about the best you can do.
> > I see!  Thanks for clarifying.  Could you please give me an example of a
> > Foo class which has a Foo.__file__ attribute but not a Foo.__module__
> > attribute?  Sorry, must be some moment of weakness on my mind's part
> > (quite possible, since I am recovering from recent surgery), but I
> > cannot think of a situation where that would be the case (while classes
> > with __module__ and w/o __file__ are the normal situation).  Were there
> > no case in which, given a class, you can learn about its file (by a
> > __file__ attribute) but not about its module (by a __module__
> > attribute), I would of course hope that my inability to parse that
> > sentence of yours, which would under such hypothetical circumstaces be
> > an absurd hypothesis, might be more forgivable.
>
> A classes __module__ attribute doesn't always tell you the name of the
> module - or at least, not a name that would be usefull for the the OPs
> use case. That's the case where you don't have the module name.  The
> reference to a classes __file__ attribute was meant to be to the
> modules __file__ attribute - I'm surprised that no one picked up on
> that. Again, assuming that the module has an __file__ attribute at
> all. Getting the __file__ attribute to a module you don't know the
> name of is a bit tricky, but possible.
>
>  --
> Mike Meyer <[EMAIL PROTECTED]>  
> http://www.mired.org/home/mwm/
> Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Thanks for your answers. And btw, sorry for top-posting, I'll be more
careful next time.
-- 
http://mail.python.org/mailman/listinfo/python-list


mysql connection

2005-11-18 Thread Python_it
How can I close more cursors at the END of my page,
after execute some scripts/functions.

example:
I use one DB connection and 5 cursor actions.

How can I close these connections/actions at the END of my page?


cursor.close() ==> 5 times??
db.close()

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


Re: Making a persistent HTTP connection

2005-11-18 Thread Piet van Oostrum
> "Alan Kennedy" <[EMAIL PROTECTED]> (AK) wrote:

>AK> http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.1

>AK> Some HTTP 1.0 clients supported persistent connections through the use
>AK> of the non-standard "keep-alive" header.

>>> And even if it works - what is the problem with connections being created?

>AK> The URL above describes the benefits of persistent connections. The
>AK> primary problem of the old style of one-request-per-connection is the
>AK> creation of more sockets than are necessary.

Maybe even more important (and just briefly mentioned in the section
referred to above) is the latency introduced by the TCP setup and the slow
startup phase of TCP's congestion control. This calculation is one of the
exercises the students have to make in my networks class.
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Behaviour of enumerated types (was: Re: Immutable instances, constant values)

2005-11-18 Thread Ben Finney
Bengt Richter <[EMAIL PROTECTED]> wrote:
> Ben Finney <[EMAIL PROTECTED]> wrote:
> >I've recently packaged 'enum' in PyPI.
> [...]
> My notion of enum comes from (what I remember of) Pascal

You might want to investigate the 'enum' package for my idea of how an
enumerated type can work.

> which is basically an ordered set of names of integers forming a
> type, and ord(one_of_the_names) gets you the index value.

Getting a numeric index might be useful in a language such as Pascal,
with no built-in dict or sequence types. In Python, where any
immutable object can be a dict key, and any sequence can be iterated,
it seems of no use.

> But what we have is named integers, much as True and False are built
> in names for integer subtypes with value 1 and 0.

That's an implementation detail; surely code shouldn't be expecting
any particular relationship between integers and boolean values?

> So I'd say enums should also be int subtypes...

Likewise, that seems best left as an implementation detail. Why expect
any particular mapping to int values? Doing arithmetic or boolean
logic on enumerated values seems against their purpose.

-- 
 \  "We tend to scoff at the beliefs of the ancients. But we can't |
  `\scoff at them personally, to their faces, and this is what |
_o__)  annoys me."  -- Jack Handey |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Announce: PythonD 2.4.2 r 1.0 for DJGPP/DOS/Windows

2005-11-18 Thread Florian Xaver
Hi!

I am very happy to hear this news! Thanks!!

Bye, Flo
-- 
Florian Xaver 
SWORD - a nice GUI library for DOS/DJGPP

Unofficial Dr-DOS page 
-- 
http://mail.python.org/mailman/listinfo/python-list


Yield in a wrapper function

2005-11-18 Thread [EMAIL PROTECTED]
This works exactly as you would expect::

 from time import sleep
 def foo(on='ABC'):
for e in list(on):
sleep(1)
yield e

When I run this on the command line It takes about 3 seconds to
complete and the first letter is shown after 1 second.
But, how do I wrap the function somewhere else::

 from time import sleep
 def foo(on):
for e in list(on):
sleep(1)
yield e

 def wrapper(x):
 if x < 0:
 return foo('ABC')
 else:
 return foo('XYZ')

When I run this, variable three letters are shown and it takes 3
seconds for the whole thing to complete. The problem is that the whole
iteration is glogged up in the wrapper() function because the first
letter is shown after 3 seconds and then all letters are shown at the
same time.

How do I wrap functions that return iterators? ...if possible.

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


Adding through recursion

2005-11-18 Thread [EMAIL PROTECTED]
There is problaly a really simple answer to this, but why does this
function print the correct result but return "None":

def add(x, y):
if x == 0:
print y
return y
else:
x -= 1
y += 1
add(x, y)

print add(2, 4)

result:
6
None

Martin

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


Re: Adding through recursion

2005-11-18 Thread [EMAIL PROTECTED]
any change you want to have :

"return add(x,y)" in the else ?


[EMAIL PROTECTED] wrote:
> There is problaly a really simple answer to this, but why does this
> function print the correct result but return "None":
>
> def add(x, y):
> if x == 0:
> print y
> return y
> else:
> x -= 1
> y += 1
> add(x, y)
> 
> print add(2, 4)
> 
> result:
> 6
> None
> 
> Martin

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


Python on linux

2005-11-18 Thread Amol Behl
Hi i wanted to know how can i find disk size on linux platform using
python. Also any info on how i can partition the hard disk, etc will be
welcome thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Choose meaningful subjects for posts [was: Re: newb ?]

2005-11-18 Thread Steve Holden
Fredrik Lundh wrote:
> Chad Everett wrote:
> 
> 
>>I am back.
> 
> 
>>No I am not a high school or college student.
> 
> 
> your subject lines still suck.  please read this
> 
> http://www.catb.org/~esr/faqs/smart-questions.html#bespecific
> 
> before you post your next question.
> 
> (the entire article is worth reading, if you haven't done so already)
> 
Note also that the subject line on an existing thread can be changed, 
though not everyone's software will track the changes, unfortunately. 
It's always worth taking the time to make sure the subject line really 
does describe the subject of your message - that way people with an 
interest in your problem are much more likely to read it instead of 
skipping over your posts.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Adding through recursion

2005-11-18 Thread Mark Jackson
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> There is problaly a really simple answer to this, but why does this
> function print the correct result but return "None":
> 
> def add(x, y):
> if x == 0:
> print y
> return y
> else:
> x -= 1
> y += 1
> add(x, y)
> 
> print add(2, 4)
> 
> result:
> 6
> None

Perhaps this hint will help:

>>> print add(0,6)
6
6

-- 
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
Of course a weed-puller isn't of much *use* in the Garden
of Eden, but it takes a while to figure that out.
- Tim Peters


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


Re: Yield in a wrapper function

2005-11-18 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> from time import sleep
> def foo(on):
> for e in list(on):

Just 

for e in on:
#...

is better. The list() constructor defeats much of the laziness you gain by
using a generator.

> sleep(1)
> yield e
> 
> def wrapper(x):
> if x < 0:
> return foo('ABC')
> else:
> return foo('XYZ')
> 
> When I run this, variable three letters are shown and it takes 3
> seconds for the whole thing to complete. The problem is that the whole
> iteration is glogged up in the wrapper() function because the first
> letter is shown after 3 seconds and then all letters are shown at the
> same time.
> 
> How do I wrap functions that return iterators? ...if possible.

The code you presented is OK. Your diagnosis is probably the result of a of
a misconstrued test case. Something like

for s in wrapper(1):
print s,

seems to work like you described because the text is buffered until the line
is complete. Try

for s in wrapper(1):
print s

or

import sys
for s in wrapper(1):
print s,
sys.stdout.flush() # explicitly flush the buffer

instead.

Peter






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


Re: Python on linux

2005-11-18 Thread Lars Kellogg-Stedman
> Hi i wanted to know how can i find disk size on linux platform using
> python.

You could use python to drive the 'sfdisk' command through a pipe, which
will probably do much of what you want.

-- Lars

-- 
Lars Kellogg-Stedman <[EMAIL PROTECTED]>
This email address will expire on 2005-11-23.

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


Re: Adding through recursion

2005-11-18 Thread Peter Tillotson
basically the other two points :-)

you create a string of add functions

add(2,4)--add(1,5)--add(0,6)

only in the last ( add(0,6) ) explicitly returns y, in the else of 
add(1,5) you ignor it. If you want the starting add to return something 
sensible you need to find a way to pass it back up the function chain.

not tested
  def add(x, y):
 if x == 0:
 sum = y
print sum
 else:
 x -= 1
 y += 1
sum = add(x, y)
 return sum

print add(2, 4)

[EMAIL PROTECTED] wrote:
> There is problaly a really simple answer to this, but why does this
> function print the correct result but return "None":
> 
> def add(x, y):
> if x == 0:
> print y
> return y
> else:
> x -= 1
> y += 1
> add(x, y)
> 
> print add(2, 4)
> 
> result:
> 6
> None
> 
> Martin
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding through recursion

2005-11-18 Thread Simon Brunning
On 18 Nov 2005 05:22:47 -0800, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> There is problaly a really simple answer to this, but why does this
> function print the correct result but return "None":
>
> def add(x, y):
> if x == 0:
> print y
> return y
> else:
> x -= 1
> y += 1
> add(x, y)
>
> print add(2, 4)
>
> result:
> 6
> None

Every function returns a value. If you don't use an explicit return
keyword, None is returned implicitly. You print the answer that you
are looking for from within your function, then print the return value
from that function, which, as I've explained, will be None.

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ajax for the Developers

2005-11-18 Thread Paul Boddie
SABIN wrote:
> The trendy XML HTTP Request has really struck the way developers had adopted
> with the user interfaces. But the major issuse are yet to be solved..
>
> 1. Changing state with links (GET requests)
> 2.Asynchronously performing batch operations
> 3.Breaking the back button
>
> Will these get solved.

It depends. Issue 3 presumably describes the way the back button
doesn't "undo" your last interaction but instead often takes you off
the page and back to what you were viewing before. Whether the back
button was "broken" before, for things like form-based applications, is
also an open issue.

I think you need to explain issue 2 in more detail for me (at least) to
understand what you're suggesting. As for issue 1, where your objection
presumably lies in the need to handle whole page updates in an
application as well as what I call "in-page updates" (thus ignoring the
Web 2.0 blogging community's tendency to overhype straightforward
concepts using catchy but obscure and inaccurate acronyms), strategies
certainly do exist to combine the two approaches without necessarily
ruining standard Web accessibility. There does appear to be a certain
Web 2.0 "scene" which seems hell bent on reinventing "old school
client/server" over HTTP; I intend to pay as little attention to such
endeavours as my RSS feed reader will allow.

Paul

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


Re: Python on linux

2005-11-18 Thread John Abel
Here's one I used a while back.  Returns a dict containing details per 
partition

def _getAvailPartitions():
validTypes = [ 'ufs', 'nfs', 'reiserfs' ]

mntTab = file( '/etc/mtab', 'r' )
drvDetails = {}

for mntLine in mntTab:
splitLine = mntLine.split()
if splitLine[2] in validTypes:
partDesc = splitLine[1]
mntPart = os.statvfs( partDesc )
totalSize, totalFree = mntPart[ statvfs.F_BLOCKS ] , 
mntPart[ statvfs.F_BFREE ]
totalInode, totalIFree = mntPart[ statvfs.F_FILES ] , 
mntPart[ statvfs.F_FFREE ]
drvDetails[ partDesc ] = [ mntPart[ statvfs.F_FRSIZE ], 
( totalSize, totalFree ), (totalInode, totalIFree) ]

return drvDetails


Amol Behl wrote:

>Hi i wanted to know how can i find disk size on linux platform using
>python. Also any info on how i can partition the hard disk, etc will be
>welcome thank you.
>  
>

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


Re: mysql connection

2005-11-18 Thread Steve Holden
Python_it wrote:
> How can I close more cursors at the END of my page,
> after execute some scripts/functions.
> 
> example:
> I use one DB connection and 5 cursor actions.
> 
> How can I close these connections/actions at the END of my page?
> 
> 
> cursor.close() ==> 5 times??
> db.close()
> 
If the five cursor actions are all performed on the same cursor then you 
only need one cursor.close().

Of course you may also need to delete (or otherwise make available for 
garbage collection) the results you have fetched with cursor.fetchall() 
and similar methods, but basically you just need to close each cursor 
you open once.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Adding through recursion

2005-11-18 Thread [EMAIL PROTECTED]
I still don't get it. I tried to test with x = 0 and found that to
work. How come since the value of y is right and it is printed right it
"turns into" None when returned by the return statement ?

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


Re: Adding through recursion

2005-11-18 Thread Simon Brunning
On 18 Nov 2005 06:30:58 -0800, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> I still don't get it. I tried to test with x = 0 and found that to
> work. How come since the value of y is right and it is printed right it
> "turns into" None when returned by the return statement ?

There is no return statement in your else block. That's where the
Nones are coming from.

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding through recursion

2005-11-18 Thread Gerard Flanagan

[EMAIL PROTECTED] wrote:

> I still don't get it. I tried to test with x = 0 and found that to
> work. How come since the value of y is right and it is printed right it
> "turns into" None when returned by the return statement ?


Martin,

-a function should either return something or not.  Your function has
two exit points, one explicitly returns a value, one doesn't (and so
defaults to returning None).

- trace through the function with pencil and paper for small values of
x and y

def add(x, y):
if x:
x -= 1
y += 1
add(x,y)
else:
print y


def ADD(x, y):
if x:
x -= 1
y += 1
return ADD(x,y)
else:
return y

>>>add(5,6)
11
>>>ADD(5,6)
11

>>>z = add(5,6)
11
>>>print z
None
>>>z = ADD(5,6)
>>>print z
11


Gerard

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


Re: Reinvent no more forever

2005-11-18 Thread Dave Hansen
On 17 Nov 2005 18:06:55 -0800 in comp.lang.python, "Phillip J. Eby"
<[EMAIL PROTECTED]> wrote:

[...]
>
>Okay, so call yours "SuperEnum" or "PowerEnum" or "UltraEnum" or
>"BetterEnum", "Enum-O-Matic", "Symbolitron"...

ITYM "EnumOMatic" or "Enum_O_Matic".  "Enum-O-Matic" is a syntax
error.  Or worse...

Regards,
-=Dave

-- 
Change is inevitable, progress is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


combine doxygen and doc-strings?

2005-11-18 Thread Gabriel Zachmann
Is there a way to combine doxygen comments, like this one


## Documentation for a function.
#  @var a - variable
#  More details.

def func( a ):
 pass


with the doc strings, like this one


def func( a ):
 """ Documentation for a function.
 More details.
 """
 pass


?
Obviously, one would like to write the documentaion only once.

Best regards,
Gabriel.

-- 
/---\
| Any intelligent fool can make things bigger, more complex,|
| or more violent. It takes a touch of genius - and a lot of courage -  |
| to move in the opposite direction. (Einstein) |
\---/
-- 
http://mail.python.org/mailman/listinfo/python-list


check if com api is still available

2005-11-18 Thread Hermann Maier
Hi,

i am using the com api of a program and if this program is shut down and 
my program calls a method of the api, it crashs. that means, i need to 
check, if the com server is still available, before i can call for it.

i already have a solution for this problem and it works quiet well, but 
i think, it is not that nice. my solution works that way, that i create 
a new thread, call a method of my com object and write back a value in 
my main object. that means, if the method call fails, only the thread 
crashes, not my whole program. if the method call succeeds, i can write 
back my value in my main object and so i know, if the thread crashes or 
not. the thing that is not nice about it is, that the thread remains in 
the memory.

perhaps there is a possibility to kill this thread, but i would prefer a 
solution that is more clean from the beginning. perhaps there is a 
windows event that can tell me, wenn the other application, that hosts 
the com server, is closed or perhaps i can do something with the guid of 
the com server, maybe there is a call where i can check, if a certain 
com server is available.

thank you for your help, Maier.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: different binding behavior

2005-11-18 Thread Gabriel Zachmann
> We've just had a HUGE thread arguing about this behaviour, just three or
> five days ago. Let's not start it again.

ok, could you please point me to it?

> In a nutshell, the behaviour is because ints are immutable and can't be
> changed in place, and lists are mutable and can be changed in place.
> 
> Imagine that ints could be changed in place. Then you could do this:

i don't see why there should be only one instance of Int with the value 0.
But if all this has already been debated (and, apparently, my point didn't 
succeed), there is no need to discuss all this over again.

In any case, thanks a lot for your response and summary.

Best regards,
Gabriel.

-- 
/---\
| Any intelligent fool can make things bigger, more complex,|
| or more violent. It takes a touch of genius - and a lot of courage -  |
| to move in the opposite direction. (Einstein) |
\---/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python obfuscation

2005-11-18 Thread Anton Vredegoor

Bengt Richter wrote:
> On Thu, 17 Nov 2005 10:53:24 -0800, [EMAIL PROTECTED] (Alex Martelli) wrote:
>
> >Anton Vredegoor <[EMAIL PROTECTED]> wrote:
> [...]
> >> The idea of using a webservice to hide essential secret parts of your
> >> application can only work well if one makes some random alterations to
> >> the results of the queries. Like GPS signals that are deliberately made
> >
> >I disagree on this general statement and I have already given two
> >counterexamples:
> I agree with your disagreement in general, but I think Antoon may be
> alluding to the "covert channel" problem, where sometimes randomization
> of an external observable is a defense. E.g., if a web site login process
> responds faster with a rejection of a bad user name (i.e. is not in the 
> authorized
> user list) than it does for a valid user name and a bad password, the timing
> difference can be used over time to eke out the private user name list, and
> make subsequent password attacks that much easier.

Pardon me, but I'm Anton, not Antoon (well maybe I am but lets keep
this distinction in order to avoid mental hash collisions)

I agree with Alex and Bengt that my statement was too general and I
even admit that as I wrote it down the thought of making it less
provocative crossed my mind . However I felt safe because I wrote 'only
work *well*' instead of 'only work *if*' and what is working well is
open for discussion isn't it? Further in my post I wrote something
about adding random fluctuations making it harder to reverse engineer a
procedure so I felt even safer. Not so with Alex's thorough analysis
though :-)

What was mostly on my mind (but I didn't mention it) is that for
something to be commercially viable there should be some kind of
pricing strategy (NB in our current economic view of the world) where a
better paying user gets a vip interface and poor people get the
standard treatment.

Since one has to have the optimal result anyway in order to sell it to
the best payers it would be impractical to recompute less accurate
values. Why not just add a random part to make it less valuable for the
unpaying user? I'm thinking about things like specifiying a real value
interval where the user can extract data from (this is also a data
compression method, see arithmetic coding for more info).



> Which perhaps gets towards Antoon's point (or my projection thereof ;-) -- 
> i.e.,
> that the anwers provided in an experimental probe of an algorithm are "signal"
> for what you want to detect, and randomization may put noise in the signal to
> defeat detection (even though enough noise might make the algorithm output 
> unsaleable ;-)
>

Yeah, sometimes people measure temperature fluctuactions in the CPU in
order to get clues about how an algorithm works :-) But in fact my mind
works more like some intuitive device that suggests that maybe some
point is safe enough to post or not, without always thinking through
all the details.

> >
> >a. a webservice which, for some amount X of money, gives an excellent
> >heuristic estimate of a good cutting-path for a woodcutting tool (for a
> >set of shapes to be cut out of standard-sized planks of wood by a
> >numerically driven cutter): this is a case where ESR, acting as a
> >consultant, advised his clients (who had developed a heuristic for this
> >task which saved a lot of wood compared to their competitors') to keep
> >their code closed-source, and it makes a good use case for the "hide
> >essential secret parts" in general;
> >

If the heuristic always gives the same answer to the same problem it
would be easier to predict the results. Oh no, now some mathematician
surely will prove me wrong :-)

> >b. a (hypothetical) website that, given time-space coordinates (and some
> >amount Y of money), produces and returns weather predictions that are
> >better than those you can get from its competitors.
> >
> >It appears to me that any application of this kind could work well
> >without at all "making random alterations" to whatever.  Point is, if
> >you develop a better algorithm (or, more likely, heuristic) for good
> >solutions to such problems, or predictions of just about anything which
> >might have economic value to somebody, using a webservice to hide the
> >essential secret parts of your discovery is an option, and it might be a
> >preferable alternative to relying on patents (since software patents may
> >not be enforceable everywhere in the world, and even where they're
> >nominally enforceable it could prove problematic and costly to actually
> >deter all would-be competitors from undercutting you).  I do not see
> >anything in your post that contradicts this, except the bare unsupported
> >assertion that a webservice "can only work well if one makes random
> >alterations".
> Yes, IMO that was an overgeneralization of an idea that may however have
> some actual narrow applicability.

Ok. Although it's a bit tricky to prove this by using an example where
the randomness is already i

Re: Adding through recursion

2005-11-18 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I still don't get it. I tried to test with x = 0 and found that to
> work. How come since the value of y is right and it is printed right it
> "turns into" None when returned by the return statement ?

because you're not returning the value to the print statement;
you're returning it to your own function, which throws it away.

if you add "raise Exception" to the "x == 0" path, you get this
traceback:

$ python add.py
6
Traceback (most recent call last):
  File "add.py", line 10, in ?
print add(2, 4)
  File "add.py", line 8, in add
add(x, y)
  File "add.py", line 8, in add
add(x, y)
  File "add.py", line 4, in add
raise Exception
Exception

which shows that you're a couple of levels down when you find
the right value.  and since the "add(x, y)" call at line 8 throws
away the result, the "print" statement at line 10 will never see
it.





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


Newbie question. Pyexpat fails on make

2005-11-18 Thread Matt
Hi

I want to build pyexpat and link it statically in Python. Im using
Python 2.4.2. This is just a straight forward build using ./configure
and then make

I change *shared* to *static* and then uncoment these two lines:

EXPAT_DIR=/usr/local/src/expat-1.95.2
pyexpat pyexpat.c -DHAVE_EXPAT_H -I$(EXPAT_DIR)/lib -L$(EXPAT_DIR) -lexpat

The directory /usr/local/src/expat-1.95.2 doesn't exist so I assume I
need to change it to the expat dir. One question will the libexpat.a
library be built and is this the one refered to -lexpat?

Modules/pyexpat.c: In function `call_with_frame':
Modules/pyexpat.c:387: warning: implicit declaration of function
`XML_StopParser'
Modules/pyexpat.c:387: error: `XML_FALSE' undeclared (first use in this
function)
Modules/pyexpat.c:387: error: (Each undeclared identifier is reported
only once
Modules/pyexpat.c:387: error: for each function it appears in.)
Modules/pyexpat.c: In function `my_ElementDeclHandler':
Modules/pyexpat.c:777: warning: implicit declaration of function
`XML_FreeContentModel'
Modules/pyexpat.c: In function `initpyexpat':
Modules/pyexpat.c:1966: error: `XML_ERROR_ENTITY_DECLARED_IN_PE'
undeclared (first use in this function)
Modules/pyexpat.c:1967: error: `XML_ERROR_FEATURE_REQUIRES_XML_DTD'
undeclared (first use in this function)
Modules/pyexpat.c:1968: error:
`XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING' undeclared (first use in
this function)
Modules/pyexpat.c:1970: error: `XML_ERROR_UNBOUND_PREFIX' undeclared
(first use in this function)
Modules/pyexpat.c:1972: error: `XML_ERROR_UNDECLARING_PREFIX' undeclared
(first use in this function)
Modules/pyexpat.c:1973: error: `XML_ERROR_INCOMPLETE_PE' undeclared
(first use in this function)
Modules/pyexpat.c:1974: error: `XML_ERROR_XML_DECL' undeclared (first
use in this function)
Modules/pyexpat.c:1975: error: `XML_ERROR_TEXT_DECL' undeclared (first
use in this function)
Modules/pyexpat.c:1976: error: `XML_ERROR_PUBLICID' undeclared (first
use in this function)
Modules/pyexpat.c:1977: error: `XML_ERROR_SUSPENDED' undeclared (first
use in this function)
Modules/pyexpat.c:1978: error: `XML_ERROR_NOT_SUSPENDED' undeclared
(first use in this function)
Modules/pyexpat.c:1979: error: `XML_ERROR_ABORTED' undeclared (first use
in this function)
Modules/pyexpat.c:1980: error: `XML_ERROR_FINISHED' undeclared (first
use in this function)
Modules/pyexpat.c:1981: error: `XML_ERROR_SUSPEND_PE' undeclared (first
use in this function)
make: *** [Modules/pyexpat.o] Error 1

Im sure this is something stupid im doing. Assistance apprecited

Cheers

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


Re: combine doxygen and doc-strings?

2005-11-18 Thread Daniel Evers
You're maybe searching for epydoc: http://epydoc.sourceforge.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: GTK for windows and Linux

2005-11-18 Thread Daniel Crespo
I prefer wxPython www.wxpython.org

Daniel

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


Re: Newbie question. Pyexpat fails on make

2005-11-18 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I want to build pyexpat and link it statically in Python. Im using
> Python 2.4.2. This is just a straight forward build using ./configure
> and then make
>
> I change *shared* to *static* and then uncoment these two lines:
>
> EXPAT_DIR=/usr/local/src/expat-1.95.2
> pyexpat pyexpat.c -DHAVE_EXPAT_H -I$(EXPAT_DIR)/lib -L$(EXPAT_DIR) -lexpat
>
> The directory /usr/local/src/expat-1.95.2 doesn't exist so I assume I
> need to change it to the expat dir. One question will the libexpat.a
> library be built and is this the one refered to -lexpat?

you probably need expat 1.95.8 to build with recent Pythons, and
you're supposed to build the expat library yourself before you build
pyexpat in this way.

(note that if you do an ordinary build, Python uses its own copy of
the expat sources, in Modules/expat)





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


Re: Python on linux

2005-11-18 Thread [EMAIL PROTECTED]
Partitioning a hard disk on linux can be done with parted, see
http://www.gnu.org/software/parted/parted.html - I don't know how good
the python-pated interface is, and what it's capable of

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


Re: HTML generation vs PSP vs Templating Engines

2005-11-18 Thread has
[EMAIL PROTECTED] wrote:

> Could someone that has used all the different ways mentioned above for
> dynamic HTML
> content, suggest what the pros and cons of the different methods are?

Not used them all - as you say, there's a plethora of options - but to
give you a general idea of the territory...

First choice you have is between HTML generators vs. HTML templating
systems:

- HTML generators create all markup from scratch. Useful when producing
arbitrary markup/layout whose entire structure must be determined
programmatically, e.g. applying paragraph and character styling to a
big chunk of text, creating arbitrary HTML form layouts based on other
input. Examples: htmlgen (crusty, HTML 3.1-era), Nevow's Stan engine.

- HTML templates insert individual items of data into a mostly static
block of HTML markup written in advance by e.g. a graphic designer.
Useful when creating documents that are fairly regular in structure -
most fall into this category - as it's much easier to create the
repetitious parts using standard HTML editing tools than write code to
produce it all programmatically.

Sometimes you might combine the two methods, using an HTML generator to
create sections of markup from arbitrary input which is then inserted
into a full-page template to produce the finished HTML document.


Assuming a templating-based solution is the appropriate choice for you
(which it most likely is), there are three general approaches to choose
from:

1. Systems that embed markup in code. This is a fairly small category.
It's fairly programmer-friendly since you've direct access to all
language features, but hostile to web designers as you have to pull
your HTML markup apart and insert it into program code to produce the
final template, making it a pain to modify that markup later. Examples:
ad-hoc solutions using Python's string interpolation, the Quixote
framework's built-in templating support, Karrigell (though it supports
some aspects of approach 2 as well).

2. Systems that embed code in markup. This is the most common category
with a fair amount of variety and capabilities to choose from. Lots of
obviously PHP/ASP-inspired designs. Two sub-categories: systems that
embed standard Python code, e.g. PSP, and systems that embed a custom
language, e.g. Cheetah. Some provide no restrictions on what you can
get up to within embedded code, others restrict functionality to
enforce a strict separation between presentation logic and model logic.
Embedding styles also vary: some mix code statements and markup
directly (e.g. Cheetah), some embed code statements in special <%...%>
style tags (e.g. PSP), some hide all code within HTML tag attributes
(e.g. TAL, Kid), providing varying degrees of designer-friendliness as
a result.

3. DOM-style systems. This is a more recent arrival and a smaller
category. These systems completely separate markup from presentation
logic. Selected HTML elements are flagged using specific named tag
attributes (e.g. id="somename") or simple compiler directives, e.g.
(nevow:render="somename"); the template is then compiled into a simple
templating-oriented (i.e. not w3c) DOM, allowing these elements to be
manipulated programmatically by standard Python scripts. Very designer
and developer friendly, although less experienced programmers may find
the higher level of abstraction involved a bit offputting. Examples:
PyMeld, HTMLTemplate [1], Nevow.Render.


For a fairly extensive list of available systems, see
. Unfortunately they're not
well categorised there, but I can't think of a better, up-to-date list
off the top of my head and most will provide decent overviews so it
shouldn't take too long to take a quick look at each.

Note that some templating engines are embedded into larger web
programming frameworks and may or may not be usable independently.
Conversely, some web frameworks may be coupled to a specific templating
system, while others allow you to choose your own.

HTH

has

--
[1] Disclaimer: I wrote HTMLTemplate. Also, shameless plug:


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


How to convert a "long in a string" to a "long"?

2005-11-18 Thread ondekoza
Hello,

I need to convert the string "" to a long. To convert this
string I tried the following:
>>> 0x
-1
>>> 0xL
4294967295L

OK, this is what I want, so I tried

s = long("0xL")
ValueError: invalid literal for long(): 0xL

s = long("0x")
ValueError: invalid literal for long(): 0xL

What can I do? 

Thank you in advance.
Stefan

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


Re: How to convert a "long in a string" to a "long"?

2005-11-18 Thread Carsten Haese
On Fri, 2005-11-18 at 11:04, [EMAIL PROTECTED] wrote:
> Hello,
> 
> I need to convert the string "" to a long. To convert this
> string I tried the following:
> >>> 0x
> -1
> >>> 0xL
> 4294967295L
> 
> OK, this is what I want, so I tried
> 
> s = long("0xL")
> ValueError: invalid literal for long(): 0xL
> 
> s = long("0x")
> ValueError: invalid literal for long(): 0xL
> 
> What can I do? 
> 
> Thank you in advance.
> Stefan

Leave out the "0x" prefix and tell long() that you're using base 16:

>>> long("", 16)
4294967295L

HTH,

Carsten.

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


Re: Choose meaningful subjects for posts [was: Re: newb ?]

2005-11-18 Thread Mike Meyer
Steve Holden <[EMAIL PROTECTED]> writes:
> Fredrik Lundh wrote:
>> Chad Everett wrote:
>>>I am back.
>>>No I am not a high school or college student.
>> your subject lines still suck.  please read this
>> http://www.catb.org/~esr/faqs/smart-questions.html#bespecific
>> before you post your next question.
>> (the entire article is worth reading, if you haven't done so already)
>>
> Note also that the subject line on an existing thread can be changed,
> though not everyone's software will track the changes,
> unfortunately. It's always worth taking the time to make sure the
> subject line really does describe the subject of your message

[Since we're giving posting advice.]

By the same token, don't use a reply to start a new thread. Some
software *will* keep it in the thread, and if they had killed the
thread, they won't see your posts.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


cannot install numarray

2005-11-18 Thread Andi Petculescu
Hi,

I'm trying to install numarray 1.4.1 on Darwin. When I run "python
setup.py install", everything seems to work until an error message
appears saying that there is no gcc.

I installed gcc-4.0 from the X11 package that came with Mac OS-X.
unable to execute gcc: No such file or directory>> error: command 'gcc' failed with exit status 1Many thanks in advance. Andi


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

Regular expressions and the global interpreter lock

2005-11-18 Thread Duncan Grisby
Hi,

I have encountered a problem with the re module. I have a
multi-threaded program that does lots of regular expression searching,
with some relatively complex regular expressions. Occasionally, events
can conspire to mean that the re search takes minutes. That's bad
enough in and of itself, but the real problem is that the re engine
does not release the interpreter lock while it is running. All the
other threads are therefore blocked for the entire time it takes to do
the regular expression search.

Is there any fundamental reason why the re module cannot release the
interpreter lock, for at least some of the time it is running?  The
ideal situation for me would be if it could do most of its work with
the lock released, since the software is running on a multi processor
machine that could productively do other work while the re is being
processed. Failing that, could it at least periodically release the
lock to give other threads a chance to run?

A quick look at the code in _sre.c suggests that for most of the time,
no Python objects are being manipulated, so the interpreter lock could
be released. Has anyone tried to do that?

Thanks,

Duncan.

-- 
 -- Duncan Grisby --
  -- [EMAIL PROTECTED] --
   -- http://www.grisby.org --
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert a "long in a string" to a "long"?

2005-11-18 Thread Klaus Alexander Seistrup
Carsten Haese wrote:

>> OK, this is what I want, so I tried
>> 
>> s = long("0xL")
>> ValueError: invalid literal for long(): 0xL
>> 
>> s = long("0x")
>> ValueError: invalid literal for long(): 0xL
>> 
>> What can I do? 
>> 
>> Thank you in advance.
>> Stefan
>
> Leave out the "0x" prefix and tell long() that you're using 
> base 16:
>
 long("", 16)
> 4294967295L

It's sufficient to tell long() that you're using base 16:

#v+

>>> long('0xL', 16)
65535L
>>> 

#v-

Cheers,

-- 
Klaus Alexander Seistrup
Copenhagen, Denmark
http://seistrup.dk/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert a "long in a string" to a "long"?

2005-11-18 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
0xL
> 
> 4294967295L
> 
> OK, this is what I want, so I tried
> 
> s = long("0xL")
> ValueError: invalid literal for long(): 0xL

 >>> int("0x", 0)
4294967295L

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


Re: Zope vs Php

2005-11-18 Thread bruno at modulix
Steve wrote:
> I am going to go the mod_python route.
> 
> as for why a person would go route one over route 2
> 
> is that the number of lines of html/output vs python code are usually
> 10 to 1 and it's much easier to encapsulate the python code than to
> quote and escape all the html/css/xml
> 
> 
> <%
> #python code
> %>
>  some title
> 
> and
> 
> print output(python-code) + " some title".
> 
> are equivalent.

Yes, but this was *not* what I suggested.

There are a lot of HTML templating languages for Python, some being more
or less PHP-like (PSP, Cheetah, ...), some being way more
presentation-oriented (TAL, Kid, ...). I prefer the second category. I
share your opinion about html in code, but I also dislike code in html...



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Zope vs Php

2005-11-18 Thread bruno at modulix
Mike Meyer wrote:
> Jorge Godoy <[EMAIL PROTECTED]> writes:
> 
>>Mike Meyer <[EMAIL PROTECTED]> writes:
>>
(snip)
>
> While I'm at it - how does KID do for things that aren't HTML?

It doesn't. Kid is explicitely for XML/HTML templating.


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding through recursion

2005-11-18 Thread Tim Williams (gmail)
On 18 Nov 2005 06:30:58 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]
> wrote:> I still don't get it. I tried to test with x = 0 and found that to

Informative print statements can help you to see and understand 
the program flow, especially if the problem is conceptual,  with
no *real*  errors in your "script"

def add(x, y):
    print 'P1:', x,y
    if x == 0:
    print 'P2:', y
    return y
    else:
    x -= 1
    y += 1
    print "P3:",x,y
    add(x, y)
    print "p4"
    print 'P5'
    #implied return is here, so I will add it 
    return # returns None **to the next level up**

print add(2, 4) 

>>> reload(addtest)
P1: 2 4
P3: 1 5
P1: 1 5
P3: 0 6
P1: 0 6
P2: 6
p4
P5
p4
P5
None
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Adding through recursion

2005-11-18 Thread Rocco Moretti
[EMAIL PROTECTED] wrote:
> There is problaly a really simple answer to this, but why does this
> function print the correct result but return "None":
> 
> def add(x, y):
> if x == 0:
> print y
> return y
> else:
> x -= 1
> y += 1
> add(x, y)
> 
> print add(2, 4)

One of the best things to do when you don't understand how a function is 
working is to geneously sprinkle the code with tracing print statements:

 >>> def add(x, y):
 params = (x, y)
 print "Starting Function", params
 if x == 0:
print "x is zero", params
 print y
 return y
print "After Return", params
 else:
print "Non-zero x", params
 x -= 1
 y += 1
 print "Updated x & y", params, '->', (x,y)
 add(x, y)
 print "Should I be here?", params
 print "Falling off end.", params


 >>> print add(2, 4)
Starting Function (2, 4)
Non-zero x (2, 4)
Updated x & y (2, 4) -> (1, 5)
Starting Function (1, 5)
Non-zero x (1, 5)
Updated x & y (1, 5) -> (0, 6)
Starting Function (0, 6)
x is zero (0, 6)
6
Should I be here? (1, 5)
Falling off end. (1, 5)
Should I be here? (2, 4)
Falling off end. (2, 4)
None
-- 
http://mail.python.org/mailman/listinfo/python-list


Speeding up multiple regex matches

2005-11-18 Thread Talin
I've run in to this problem a couple of times. Say I have a piece of
text that I want to test against a large number of regular expressions,
where a different action is taken based on which regex successfully
matched. The naive approach is to loop through each regex, and stop
when one succeeds. However, I am finding this to be too slow for my
application -- currently 30% of the run time is being taken up in the
regex matching.

I thought of a couple of approaches, but I am not sure how to make them
work:

1) Combine all of the regular expressions into one massive regex, and
let the regex state machine do all the discriminating. The problem with
this is that it gives you no way to determine which regex was the
matching one.

2) Use the first character of the text string to cut down the search
size. The problem here is that since I don't know the regex patterns in
advance, I would need to inspect each regex and determine the possible
set of starting characters that could be matched. This would require
creating my own regex parser.

3) Use a lexical scannner. This is probably overkill for what I want to
do.

4) Write my own regex system that does what I want. This is more work
than I want to do.

Any thoughts?

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


Re: Importing a class without knowing the module

2005-11-18 Thread Alex Martelli
Mike Meyer <[EMAIL PROTECTED]> wrote:
   ...
> A classes __module__ attribute doesn't always tell you the name of the
> module - or at least, not a name that would be usefull for the the OPs
> use case. That's the case where you don't have the module name.  The

How do you arrange a module so that its classes' __module__ attributes
don't tell you the name of the module "that would be useful", yet the
module's __file__ DOES give you information that you can usefully
process, heuristically I assume, to infer a module name that IS useful?

I just don't see it, which of course doesn't mean it can't be done, with
sufficient evil ingenuity.  But since you're the one arguing that this
case is important enough to be worth dwelling on, I'd rather see some
specific examples from you, to understand whether my gut reaction "if
possible at all, this has gotta be such a totally CORNER, ARTIFICIAL
case, that it's absurd to bend over backwards to cover it" is justified,
or whether I'm misjudging instead.

> reference to a classes __file__ attribute was meant to be to the
> modules __file__ attribute - I'm surprised that no one picked up on
> that. Again, assuming that the module has an __file__ attribute at
> all. Getting the __file__ attribute to a module you don't know the
> name of is a bit tricky, but possible.

If you have the module object, getting its __file__ isn't hard -- but
then, neither is getting its module name... m.__file__ and m.__name__
are just about as accessible as each other.  Of the two, the one more
likely to be useless would be the __file__ -- import hooks (zipimport or
more deviously sophisticated ones) might mean that string is not a file
path at all; __name__ is supposed to be the string key of that module
object within sys.modules, and it is, I think, far less likely that any
tricks will have been played wrt that -- plus, you can easily
doublecheck by scouring sys.modules.

I just cannot see ANY case where I would want to try heuristics on some
__file__ attribute (hopefully but not necessarily a filename) to try and
recover a __name__ that appears to be missing, mangled, or incorrect; my
instinct would be to raise exceptions informing the user that what
they're trying to marshal is too weird and strange for their own good,
and let them deal with the situation.  But as I said, that may depend on
a failure of the imagination -- if you can show me compelling use cases
in which heuristics on __file__ prove perfectly satisfactory where just
dealing with __name__ wouldn't, I'm quite ready to learn!


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


Re: Python obfuscation

2005-11-18 Thread Alex Martelli
Anton Vredegoor <[EMAIL PROTECTED]> wrote:
   ...
> What was mostly on my mind (but I didn't mention it) is that for
> something to be commercially viable there should be some kind of
> pricing strategy (NB in our current economic view of the world) where a
> better paying user gets a vip interface and poor people get the
> standard treatment.

Some fields work well with such market segmentation, but others work
perfectly well without it.  iTunes songs are 99 cents (for USA
residents; there IS some segmentation by national markets, imposed on
Apple by the music industry) whoever is buying them; I personally think
it would hurt iTunes' business model if the 99-cents song was a "cheap
version" and you could choose to "upgrade" to a better-sounding one for
extra money -- giving the mass-market the perception that they're
getting inferior goods may adversely hurt sales and revenue.

Market segmentation strategies and tactics are of course a huge field of
study, both theoretical and pragmatic (and it's as infinitely
fascinating in the theoretical view, as potentially lucrative or ruinous
in practical application).  It's definitely wrong to assume, as in your
statement above, that uniform pricing (no segmentation, at least not
along that axis) cannot work in a perfectly satisfactory way.


> If the heuristic always gives the same answer to the same problem it
> would be easier to predict the results. Oh no, now some mathematician
> surely will prove me wrong :-)

"Easier" need not be a problem; even assuming that the heuristic uses no
aspect whatever of randomness, you may easily think of real-world cases
where ``reverse engineering'' the heuristic from its results is
computationally unfeasible anyway.  Take the problem of controlling a NC
saw to cut a given set of shapes out of a standard-sized wood plank,
which is one of the real-world cases I mentioned.  It doesn't seem to me
that trying to reverse-engineer a heuristic is any better than trying to
devise one (which may end up being better) from ingenuity and first
principles, even if you had thousands of outputs from the secret
heuristic at hand (and remember, getting each of this output costs you
money, which you have to pay to the webservice with the heuristic).


> Ok. Although it's a bit tricky to prove this by using an example where
> the randomness is already in the problem from the start. If one groups
> very chaotic processes in the same category as random processes of
> course.

Well, economically interesting prediction problems do tend to deal with
systems that are rich and deep and complex enough to qualify as chaotic,
if not random -- from weather to the price of oil, etc etc.  But
problems of optimization under constraint, such as the NC saw one,
hardly qualify as such, it seems to me -- no randomness nor necessarily
any chaotic qualities in the problem, just utter computational
unfeasibility of algorithmic solutions and the attendand need to look
for "decently good" heuristics instead.

> > >Deliberately giving predictions worse than I could have given, in this
> > >context, seems a deliberate self-sabotage without any return.
> 
> Not always, for example with a gradient in user status according to how
> much they pay. Note that I don't agree at all with such practice, but
> I'm trying to explain how money is made now instead of thinking about
> how it should be made.

Money is made in many ways, essentially by creating (perceived) buyer
advantage and capturing some part of it -- but market segmentation is
just one of many ways.  IF your predictions are ENORMOUSLY better than
those the competition can make, then offering for free "slightly
damaged" predictions, that are still better than the competition's
despite the damage, MIGHT be a way to market your wares -- under a lot
of other assumptions, e.g., that there is actual demand for the best
predictions you can make, the ones you get paid for, so that your free
service doesn't undermine your for-pay one.  It just seems unlikely that
all of these preconditions would be satisfied at the same time; better
to limit your "free" predictions along other axes, such as duration or
location, which doesn't require your predictions' accuracy advantage to
be ENORMOUS _and_ gives you a lot of control on "usefulness" of what
you're supplying for free -- damaging the quality by randomization just
seems to be unlikely to be the optimal strategy here, even if you had
determined (or were willing to bet the firm that) marked segmentation is
really the way to go here.

Analogy: say you make the best jams in the world and want to attract
customers by showing them that's the case via free samples.  Your
randomization strategy seems analogous to: damage your jam's free
samples by adding tiny quantities of ingredients that degrade their
flavor -- if your degraded samples are still much better than the
competitors' jam, and there's effective demand for really "perfect" jam,
this strategy MIGHT work... but it seems a ver

Re: sqlite utf8 encoding error

2005-11-18 Thread Greg Miller
Thank you for all your suggestions.  I ended up casting the string to
unicode prior to inserting into the database.  

Greg Miller

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


Re: Speeding up multiple regex matches

2005-11-18 Thread Alex Martelli
Talin <[EMAIL PROTECTED]> wrote:
   ...
> 1) Combine all of the regular expressions into one massive regex, and
> let the regex state machine do all the discriminating. The problem with
> this is that it gives you no way to determine which regex was the
> matching one.

Place each regex into a parenthesized group, and check which groups have
matched on the resulting matchobject:

>>> x=re.compile('(aa)|(bb)')
>>> mo=x.search('zaap!')
>>> mo.groups()
('aa', None)

There's a limit of 99 groups, so if you have unbounded number of regexes
to start with you'll have to split them up 99-or-fewer at a time, but
that shouldn't be impossibly hard.


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


Re: os.path.expanduser('~/foo') and MSWindows "My Documents"

2005-11-18 Thread Tony Nelson
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] wrote:

> python
> 
> >>> import os
> >>> help(os.path.expanduser)
> >>> import platform
> >>> platform.system()
> 'Windows'
> >>> platform.release()
> 'XP'
> >>>

platform looks good.

TonyN.:'[EMAIL PROTECTED]
  '  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert a "long in a string" to a "long"?

2005-11-18 Thread Sion Arrowsmith
Steven Bethard  <[EMAIL PROTECTED]> wrote:
>[EMAIL PROTECTED] wrote:
>> s = long("0xL")
>> ValueError: invalid literal for long(): 0xL
> >>> int("0x", 0)
>4294967295L

So why does the base argument to int() (or long()) default to
10 and not 0?

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Los Angeles Python Users' Group, anyone?

2005-11-18 Thread mortenbagai
Hi,

I was rifling through python.org to see if there was an existing Python
user's group for the Los Angeles area. Doesn't seem like it, so maybe
we should start one? I'm interested in helping with the coordination of
activities etc.

Since everybody living in greater L.A. area is likely to have
superhuman tolerance for traffic and commuting times, I see no reason
why an L.A users' group couldn't cover the whole
LA/Valley/Burbank/Glendale/Pasadena/Long Beach/etc sprawl.

Anyone interested, please email me at: m AT bagai DOT com

Thanks!

/Morten

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


Re: How to convert a "long in a string" to a "long"?

2005-11-18 Thread Leif K-Brooks
Sion Arrowsmith wrote:
> Steven Bethard  <[EMAIL PROTECTED]> wrote:
> 
>>[EMAIL PROTECTED] wrote:
>>
>>>s = long("0xL")
>>>ValueError: invalid literal for long(): 0xL
>>>
>int("0x", 0)
>>
>>4294967295L
> 
> So why does the base argument to int() (or long()) default to
> 10 and not 0?

Because it's designed for numbers normal people provide, not for numbers
programmers provide. Normal people see 0123 as being equal to 123, not 83.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python obfuscation

2005-11-18 Thread Bengt Richter
On 18 Nov 2005 06:56:38 -0800, "Anton Vredegoor" <[EMAIL PROTECTED]> wrote:
[...]
>Pardon me, but I'm Anton, not Antoon (well maybe I am but lets keep
>this distinction in order to avoid mental hash collisions)
D'oh. I'm sorry. Please pardon _me_ ;-/

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


Re: Reinvent no more forever

2005-11-18 Thread Phillip J. Eby
Dave Hansen wrote:
> On 17 Nov 2005 18:06:55 -0800 in comp.lang.python, "Phillip J. Eby"
> <[EMAIL PROTECTED]> wrote:
>
> [...]
> >
> >Okay, so call yours "SuperEnum" or "PowerEnum" or "UltraEnum" or
> >"BetterEnum", "Enum-O-Matic", "Symbolitron"...
>
> ITYM "EnumOMatic" or "Enum_O_Matic".  "Enum-O-Matic" is a syntax
> error.  Or worse...

Not in a PyPI project name, it isn't.  Project names aren't limited to
being Python identifiers.

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


BisonGen parser generator. Newbie question

2005-11-18 Thread ishtar2020
Hello everybody!

I'm trying to run the calculator example included with the "BisonGen"
parser generator, but I've been unable to put it to work.

When I compile the xml file "simple.bgen" with the script
"BisonGen.bat", the only parser I get is a C file. I've heard BisonGen
generates also a python file, which is, I believe, the one used
imported by "test.py" to run the testing.

Does anybody know what I'm doing wrong here?

Thank you in advance!

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


Re: Python obfuscation

2005-11-18 Thread Serge Orlov
Ben Sizer wrote:
> Mike Meyer wrote:
> > "Ben Sizer" <[EMAIL PROTECTED]> writes:
> > > Decompyle (http://www.crazy-compilers.com/decompyle/ ) claims to be
> > > pretty advanced. I don't know if you can download it any more to test
> > > this claim though.
> >
> > No, it doesn't claim to be advanced. It claims to be good at what it
> > does. There's no comparison with other decompilers at all. In
> > particular, this doesn't give you any idea whether or not similar
> > products exist for x86 or 68k binaries.
>
> That's irrelevant. We don't require a citable source to prove the
> simple fact that x86 binaries do not by default contain symbol names
> whereas Python .pyc and .pyo files do contain them. So any
> decompilation of (for example) C++ code is going to lose all the
> readable qualities, as well as missing any symbolic constants,
> enumerations, templated classes and functions, macros,  #includes,
> inlined functions, typedefs, some distinctions between array indexing
> and pointer arithmetic, which inner scope a simple data variable is
> declared in, distinctions between functions/member functions declared
> as not 'thiscall'/static member functions, const declarations, etc.

If you protection is actually boils down to "if (licensed) ..."
everything you described will just slightly inconvinient an experienced
cracker. I've read a cracker's detailed walkthrough, it took him 26
minutes to crack a program that asks for a serial number. Basically it
looks like this: set breakpoint on event where "OK" button is pressed
after a serial number is entered, set watchpoint on memory where the
serial number is stored, study all places where this memory is read,
find the ultimate "jump if" instruction.



>
> > I've dealt with some very powerfull disassemblers and
> > decompilers, but none of them worked on modern architectures.
>
> You can definitely extract something useful from them, but without
> symbol names you're going to have to be working with a good debugger
> and a decent knowledge of how to use it if you want to find anything
> specific. Whereas Python could give you something pretty obvious such
> as:
>
>6 LOAD_FAST0 (licensed)
>9 JUMP_IF_FALSE9 (to 21)

I can suggest at least two methods to obfuscate python byte code:

1. Apply some function before writing byte code to file, apply reverse
function upon reading.

2. Take opcodes.h and assign new random numbers to opcodes, also take
ceval.c and reorder opcode handlers in the switch statement to make
reverse engeneering even harder.

I believe this will require at least several hours of manual work
before you can use stock python disassembler.


>
> My interest lies in being able to use encrypted data (where 'data' can
> also include parts of the code) so that the data can only be read by my
> Python program, and specifically by a single instance of that program.
> You would be able to make a backup copy (or 20), you could give the
> whole lot to someone else, etc etc. I would just like to make it so
> that you can't stick the data file on Bittorrent and have the entire
> world playing with data that was only purchased once.

This is doable even in python. Basic idea is that you need to spread
your obfuscation code and blend it with algorithm:

1. Generate user identity on your server and insert it inside your
distribution. Spread it all over the code, don't store it in a file,
don't store in one big variable, instead divide the user identity in
four bits part and spread their storage over different places. Note
this actually doesn't have anything to do with python, it's true for
C/C++. If you don't follow this your protection is vulnerable to replay
attack: crackers will just distribute data file + stolen user identity.

2. Generate custom data files for each user, using various parts of
user id as scrambling key for different parts of the data file. For
example: suppose you have data file for a game and you store initial
coordinates of characters as coordinates (0..65535,0..65535) as four
bytes. Normal code to load them from file would like like

x,y = buf[0]+256*buf[1], buf[2]+256*buf[3]

obfuscated would look like

x,y = buf[0]+c*((buf[1]+ t + 7)&c), buf[2]+c*((buf[1]+ t + 7)&c)

where t contains some bits from user id and c==256



I hope it's not very vague description. I think this approach will do
what you want. Don't forget that you will also need to bind you program
to hardware, or users will just distribute your program + data file
together. I hope they won't mind that your program is tied to one
computer :)

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


examining python objects

2005-11-18 Thread rurpy
Is there a function/class/module/whatever I can use to
look at objects?  I want something that will print the object's
value (if any) in pretty-printed form, and list all it's attributes
and their values.  And do all that recursively.
I want to be able to find out everything about an object that
Python can introspectively find out.

Something like the 'x' command does in the Perl debugger.

Anything like this exist?  (And why isn't something like this
already in pdb?)

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


the PHP ternary operator equivalent on Python

2005-11-18 Thread Daniel Crespo
Hi!

I would like to know how can I do the PHP ternary operator/statement
(... ? ... : ...) in Python...

I want to something like:

a = {'Huge': (quantity>90) ? True : False}

Any suggestions?

Thanks

Daniel

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


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread Simon Brunning
On 18 Nov 2005 10:53:04 -0800, Daniel Crespo <[EMAIL PROTECTED]> wrote:
> I would like to know how can I do the PHP ternary operator/statement
> (... ? ... : ...) in Python...

Wait for Python 2.5 - .

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


How to do "new_variable = (variable) ? True : False; " (php) on python?

2005-11-18 Thread Daniel Crespo
Hello to all,

How can I do

new_variable = (variable) ? True : False;

in Python in one line?

I want to do something like this:

dic = {'item1': (variable) ? True-part : False-part}

Any suggestions?

Daniel

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


Re: Importing a class without knowing the module

2005-11-18 Thread Mike Meyer
[EMAIL PROTECTED] (Alex Martelli) writes:
> Mike Meyer <[EMAIL PROTECTED]> wrote:
>...
>> A classes __module__ attribute doesn't always tell you the name of the
>> module - or at least, not a name that would be usefull for the the OPs
>> use case. That's the case where you don't have the module name.  The
> How do you arrange a module so that its classes' __module__ attributes
> don't tell you the name of the module "that would be useful", yet the
> module's __file__ DOES give you information that you can usefully
> process, heuristically I assume, to infer a module name that IS useful?

So what module name do you import if C.__module__ is __main__?

> I just don't see it, which of course doesn't mean it can't be done, with
> sufficient evil ingenuity.  But since you're the one arguing that this
> case is important enough to be worth dwelling on,

I'm not dwelling on it, you are.  All I did was recommend using the
module name if you had one, and if not then the file name was your
best bet. You chose to ignore part of my statement to focus on the
part you disagreed with, because you thought what I had suggested in
the first place was a better idea. I pointed out this oversight on
your part, and you've been dwelling on it ever since.

Frankly, I thought you were brighter than that, have no idea why
you're acting like this, and frankly don't think you need a tutor.  I
figured this out by fooling around with the interpreter before posting
in the first place, you certainly know enough to do the same.

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


SnakeCard on sourceforge

2005-11-18 Thread Philippe C. Martin
Dear all,

The SnakeCard product line is now hosted on sourceforge.net:

SCFB - http://sourceforge.net/projects/sctoolkits
SC-ID - http://sourceforge.net/projects/sc-id


I will keep posting the snapshots on www.snakecard.com as well as SCLOGON
and SCWEB until they take shape ;-)


Regards,

Philippe

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


Re: path module / class

2005-11-18 Thread [EMAIL PROTECTED]
Hi Neil,

Neil Hodgson wrote:
[snip]
> There is no PEP yet but there is a wiki page.
> http://wiki.python.org/moin/PathClass
> Guido was unenthusiastic so a good step would be to produce some
> compelling examples.

I guess it depends on what is "compelling" :)

I've been trying to come up with some cases that I've run into where
the path module has helped.  One case I just came across was trying to
do the equivalent of 'du -s *' in python, i.e. get the size of each of
a directory's subdirectories.  My two implemenations are below:

import os
import os.path
from path import path

def du_std(d):
"""Return a mapping of subdirectory name to total size of files in
that subdirectory, much like 'du -s *' does.

   This implementation uses only the current python standard
   libraries"""
retval = {}
# Why is os.listdir() and not os.path.listdir()?
# Yet another point of confusion
for subdir in os.listdir(d):
subdir = os.path.join(d, subdir)
if os.path.isdir(subdir):
s = 0
for root, dirs, files in os.walk(subdir):
s += sum(os.path.getsize(os.path.join(root,f)) for f in
files)
retval[subdir] = s
return retval

def du_path(d):
"""Return a mapping of subdirectory name to total size of files in
   that subdirectory, much like 'du -s *' does.

   This implementation uses the proposed path module"""
retval = {}
for subdir in path(d).dirs():
retval[subdir] = sum(f.getsize() for f in subdir.walkfiles())
return retval

I find the second easier to read, and easier to write - I got caught
writing the first one when I wrote os.path.listdir() instead of
os.listdir().

Cheers,
Chris

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


Re: How to do "new_variable = (variable) ? True : False; " (php) on python?

2005-11-18 Thread Peter Otten
Daniel Crespo wrote:

> How can I do
> 
> new_variable = (variable) ? True : False;
> 
> in Python in one line?

new_variable = variable

:-)

Peter
 

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


Web-based client code execution

2005-11-18 Thread Paul Watson
What are the options?

The user to hits a web page, downloads code (Python I hope), execute it, 
and be able to return the results.  It needs to be able to go through 
standard HTTP so that it could be run from behind a corporate firewall 
without any other ports being opened.

Am I stuck doing an ActiveX control?

Yes, I know that downloading code and executing on the client machine is 
a security risk.  This will be for the employee's computers to connect. 
  This will not be a publicly available web page.

I have read some about AJAX.  Is there an APAX coming for Python?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread David Wahler
Daniel Crespo wrote:
> I would like to know how can I do the PHP ternary operator/statement
> (... ? ... : ...) in Python...
>
> I want to something like:
>
> a = {'Huge': (quantity>90) ? True : False}

Well, in your example the '>' operator already returns a boolean value
so you can just use it directly. Hoewver, I agree that there are
situations in which a ternary operator would be nice. Unfortunately,
Python doesn't support this directly; the closest approximation I've
found is:

>>> (value_if_false, value_if_true)[boolean_value]

This exploits the fact that False and True are converted to integers as
zero and one, respectively. The downside is that it's really ugly.
Also, it doesn't use minimal evaluation; in other words, if you try an
expression like:

>>> (None, func())[callable(func)]

You might think this would return the value of func() if it's callable,
and None otherwise. Unfortunately, func() is evaluated no matter what,
even if the condition is false.

Of course, you can always get around this by doing really cryptic stuff
with lambdas:

>>> (lambda: None, lambda: func())[callable(func)]()

... but by that point, you're better off just using an if/then/else.

-- David

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


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread Mike Meyer
"Daniel Crespo" <[EMAIL PROTECTED]> writes:

> Hi!
>
> I would like to know how can I do the PHP ternary operator/statement
> (... ? ... : ...) in Python...
>
> I want to something like:
>
> a = {'Huge': (quantity>90) ? True : False}
>
> Any suggestions?

Lots of ways, depending on your exact needs. What's best for what you
suggest is "a = {Huge : (False, True)[quantity > 90]}". Googling  the
python newsgroup will turn up lots of others.

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python on linux

2005-11-18 Thread Sybren Stuvel
John Abel enlightened us with:
> Here's one I used a while back.  Returns a dict containing details per 
> partition

This only gives information about actually mounted partitions. It
could be improved by checking /proc/partitions as well.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread gene tani

Mike Meyer wrote:
> "Daniel Crespo" <[EMAIL PROTECTED]> writes:
>
> > Hi!
> >
> > I would like to know how can I do the PHP ternary operator/statement
> > (... ? ... : ...) in Python...
> >
> > I want to something like:
> >
> > a = {'Huge': (quantity>90) ? True : False}
> >
> > Any suggestions?
>
> Lots of ways, depending on your exact needs. What's best for what you
> suggest is "a = {Huge : (False, True)[quantity > 90]}". Googling  the

http://www.python.org/doc/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator

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


Controlling windows gui applications from python

2005-11-18 Thread tim
Hi all, I'm almost as new to this list as to python so I hope I don't 
get a "this has been answered a 100 times before" or anything...

Currently I am using a program named 'Macro Scheduler' for automating 
programs that don't have a command line version.
Its a simple scripting language that allows you to automate button 
clicks, mouse movement, starting programs, checking the state of a 
window, changing the focus, type text into an input field...etc.
Is there a way to do these things from within Python?

Thanks
Tim

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


Re: Choose meaningful subjects for posts [was: Re: newb ?]

2005-11-18 Thread Grant Edwards
On 2005-11-18, Mike Meyer <[EMAIL PROTECTED]> wrote:

>>> http://www.catb.org/~esr/faqs/smart-questions.html#bespecific
>>> before you post your next question.

If I can't tell from the subject line what the thread is about, I almost
never read it.

>> Note also that the subject line on an existing thread can be changed,
>> though not everyone's software will track the changes, unfortunately. It's
>> always worth taking the time to make sure the subject line really does
>> describe the subject of your message
>
> [Since we're giving posting advice.]
>
> By the same token, don't use a reply to start a new thread. Some software
> *will* keep it in the thread, and if they had killed the thread, they won't
> see your posts.

They don't even have to kill the original thread. By just not expanding the
thread they won't see the "new" thread hidden inside the old one.

This problem seems to be especially prevelent in c.l.p. (as are fractured
threads). I think it's due to people who read the group via an e-mail
gateway (particularly the ones who get the digest service).

Obligatory aside: I'm completely baffled why anybody would choose the
mailing list format over Usenet.  I don't even read mailing lists via
mailing lists.  I recommend gmane.org's NNTP server for all your mailing
list needs.

-- 
Grant Edwards   grante Yow!  It's so OBVIOUS!!
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web-based client code execution

2005-11-18 Thread Steve
AJAX works because browsers can execute javascript.  I don't know of a
browser that can execute python.  Basically your stuck with java or
javascript because everything else really isn't cross platform.

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


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread Daniel Crespo
Oh... Well, thanks for that information.

I'll do this then:

def TernaryOperation(condition,true_part,false_part):
if condition:
return True-part
else:
return False-part

a = {'Huge': TernaryOperation(quantity>90,True,False)}

Thank you

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


Re: How to do "new_variable = (variable) ? True : False; " (php) on python?

2005-11-18 Thread Sam Pointon
Daniel Crespo wrote:
> Hello to all,
>
> How can I do
>
> new_variable = (variable) ? True : False;
>
> in Python in one line?
>
> I want to do something like this:
>
> dic = {'item1': (variable) ? True-part : False-part}
>
> Any suggestions?
>
> Daniel

There's a trick using the short-circuiting boolean logic operators to
emulate the ternary operator in Python. Basically, you do
TEST and TRUE_PART or FALSE_PART

However, this fails if TRUE_PART evaluates to a False value; you end up
with FALSE_PART's value instead.

This is a trick/hack, though, and shouldn't really be used much - use
an if statement instead, or wait til 2.5 when an if expression is
coming in.

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


Re: Controlling windows gui applications from python

2005-11-18 Thread Simon Brunning
On 18/11/05, tim <[EMAIL PROTECTED]> wrote:
> Hi all, I'm almost as new to this list as to python so I hope I don't
> get a "this has been answered a 100 times before" or anything...
>
> Currently I am using a program named 'Macro Scheduler' for automating
> programs that don't have a command line version.
> Its a simple scripting language that allows you to automate button
> clicks, mouse movement, starting programs, checking the state of a
> window, changing the focus, type text into an input field...etc.
> Is there a way to do these things from within Python?



--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Controlling windows gui applications from python

2005-11-18 Thread Paul Watson
tim wrote:
> Hi all, I'm almost as new to this list as to python so I hope I don't 
> get a "this has been answered a 100 times before" or anything...
> 
> Currently I am using a program named 'Macro Scheduler' for automating 
> programs that don't have a command line version.
> Its a simple scripting language that allows you to automate button 
> clicks, mouse movement, starting programs, checking the state of a 
> window, changing the focus, type text into an input field...etc.
> Is there a way to do these things from within Python?
> 
> Thanks
> Tim

If there is a Microsoft COM interface to your 'Macro Scheduler' program, 
then you can drive it from Python code.  See the win32com interface and 
get Mark Hammond's book "Programming Python on Win32," or something like 
that, from O'Reilly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread Peter Otten
Daniel Crespo wrote:

> Oh... Well, thanks for that information.
> 
> I'll do this then:
> 
> def TernaryOperation(condition,true_part,false_part):
> if condition:
> return True-part
> else:
> return False-part
> 
> a = {'Huge': TernaryOperation(quantity>90,True,False)}

By the time it compiles it will do the same as

a = {"Huge": quantity>90}

Consider describing your actual problem and keep in mind that the "ternary
operator" is a means, not an end.

Peter

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


Re: Web-based client code execution

2005-11-18 Thread Paul Watson
Steve wrote:
> AJAX works because browsers can execute javascript.  I don't know of a
> browser that can execute python.  Basically your stuck with java or
> javascript because everything else really isn't cross platform.

Well, I guess the Grail browser could run Python, but I do not think I 
can go there.

I need READ access to the users local disk storage.  Can I do this in 
Javascript, or should I bite the bullet and turn to ActiveX?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread Grant Edwards
On 2005-11-18, Daniel Crespo <[EMAIL PROTECTED]> wrote:

> I would like to know how can I do the PHP ternary operator/statement
> (... ? ... : ...) in Python...

The _PHP_ ternary operator (x?y:z)!  

Kids these days!

-- 
Grant Edwards   grante Yow!  It's so OBVIOUS!!
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web-based client code execution

2005-11-18 Thread Steve
You universally won't be able to do that with javascript, only with and
extension on firefox.  ActiveX will limit you to windows only with ie.
Which isn't bad you still get a 80% market share.

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


Re: Choose meaningful subjects for posts [was: Re: newb ?]

2005-11-18 Thread skip

Grant> Obligatory aside: I'm completely baffled why anybody would choose
Grant> the mailing list format over Usenet.  I don't even read mailing
Grant> lists via mailing lists.  I recommend gmane.org's NNTP server for
Grant> all your mailing list needs.

For the same reason I don't like web forums as a means of communication.  I
would much rather operate in an interrupt-driven mode than have to remember
to poll some external service to get my daily helping of information.

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


Type-checking unpickled objects

2005-11-18 Thread Gordon Airporte
I have this class, and I've been pickling it's objects as a file format 
for my program, which works great. The problems are a.) how to handle 
things when the user tries to load a non-pickled file, and b.) when they 
load a pickled file of the wrong class.

a. I can handle with a general exception I guess. I just tried to 
pickle.load() a .pyc and it failed with a 'KeyError' exception - however 
that works. It might do that every time, it might not.

Regarding b., if I type check I simply get the 'instance' type, which 
doesn't get me all of the way there because I might have an instance of 
the wrong class. I can't find any sort of __type__ attribute to set in 
the objects. Perhaps I should use __str__?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yield in a wrapper function

2005-11-18 Thread Bengt Richter
On 18 Nov 2005 05:08:39 -0800, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

>This works exactly as you would expect::
>
> from time import sleep
> def foo(on='ABC'):
>for e in list(on):
>sleep(1)
>yield e
>
>When I run this on the command line It takes about 3 seconds to
>complete and the first letter is shown after 1 second.
>But, how do I wrap the function somewhere else::
>
> from time import sleep
> def foo(on):
>for e in list(on):
>sleep(1)
>yield e
>
> def wrapper(x):
> if x < 0:
> return foo('ABC')
> else:
> return foo('XYZ')
>
>When I run this, variable three letters are shown and it takes 3
>seconds for the whole thing to complete. The problem is that the whole
>iteration is glogged up in the wrapper() function because the first
>letter is shown after 3 seconds and then all letters are shown at the
>same time.
>
>How do I wrap functions that return iterators? ...if possible.
>
Make the wrapper itself an iterable? E.g., is this the effect you wanted?

 >>> from time import sleep
 >>> def foo(on):
 ... for e in on:
 ... sleep(1)
 ... yield e
 ...
 >>> def wrapper(x):
 ... if x < 0:
 ... for e in foo('ABC'): yield e
 ... else:
 ... for e in foo('XYZ'): yield e
 ...
 >>> wrapper(-1)
 
 >>> import sys
 >>> for c in wrapper(-1): sys.stdout.write(c); sys.stdout.flush()
 ...
 ABC>>>
 >>> for c in wrapper(+1): sys.stdout.write(c); sys.stdout.flush()
 ...
 XYZ>>>

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


  1   2   >