How do I set a callback in Python?

2008-09-08 Thread catsclaw
I can't for the life of me figure out how to set a callback in
Python.  I have a class, which wraps another class.  The second class
needs a callback assigned.  I don't want to use globals for it.
Here's what I'd like to do:

class MyWrapper:
def get_login(self, username):
return self.user, self.pass

def __init__(self, user, pass):
self.user = user
self.pass = pass

self.client = Client("connection string")
self.client.callback_login = get_login

... but obviously, the Client class, when it calls the callback,
doesn't pass a reference to the "self" object.  How do I do this?

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


Re: How do I set a callback in Python?

2008-09-08 Thread Rob Williscroft
catsclaw wrote in news:d797403a-e492-403f-933a-bd18ef53d5c0
@k13g2000hse.googlegroups.com in comp.lang.python:

> I can't for the life of me figure out how to set a callback in
> Python.  I have a class, which wraps another class.  The second class
> needs a callback assigned.  I don't want to use globals for it.
> Here's what I'd like to do:
> 
> class MyWrapper:
> def get_login(self, username):
> return self.user, self.pass
> 
> def __init__(self, user, pass):
> self.user = user
> self.pass = pass
> 
> self.client = Client("connection string")
> self.client.callback_login = get_login
> 
> ... but obviously, the Client class, when it calls the callback,
> doesn't pass a reference to the "self" object.  How do I do this?


use:
 self.client.callback_login = self.get_login


Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I set a callback in Python?

2008-09-08 Thread Diez B. Roggisch

catsclaw schrieb:

I can't for the life of me figure out how to set a callback in
Python.  I have a class, which wraps another class.  The second class
needs a callback assigned.  I don't want to use globals for it.
Here's what I'd like to do:

class MyWrapper:
def get_login(self, username):
return self.user, self.pass

def __init__(self, user, pass):
self.user = user
self.pass = pass

self.client = Client("connection string")
self.client.callback_login = get_login

... but obviously, the Client class, when it calls the callback,
doesn't pass a reference to the "self" object.  How do I do this?



Do self.get_login. The difference is that this creates a so-called 
"bound method". Google for that, and play around in the interpreter with 
an object and references to it's methods, either through the class or 
the instance to see the difference.


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


Re: How do I set a callback in Python?

2008-09-08 Thread Gary Herron

catsclaw wrote:

I can't for the life of me figure out how to set a callback in
Python.  I have a class, which wraps another class.  The second class
needs a callback assigned.  I don't want to use globals for it.
Here's what I'd like to do:

class MyWrapper:
def get_login(self, username):
return self.user, self.pass

def __init__(self, user, pass):
self.user = user
self.pass = pass

self.client = Client("connection string")
self.client.callback_login = get_login
  


Make that list line:

   self.client.callback_login = self.get_login


Then you are passing a "bound" method (meaning bound to a particular instance).
The client class calls its callback_login as a normal function with parameters,
and the Wrapper get_login will be called on the proper instance of MyWrapper.

This is a very common thing for many uses, including callbacks.


Hoping I understood what you wanted correctly,
Gary Herron 






... but obviously, the Client class, when it calls the callback,
doesn't pass a reference to the "self" object.  How do I do this?

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


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


Re: Spotlight Searching in Python - Mac OSX

2008-09-08 Thread Diez B. Roggisch

[EMAIL PROTECTED] schrieb:

Hi all, I'm having some issues getting a spotlight search to work
similar to the program demonstrated here:
http://pyobjc.sourceforge.net/examples/pyobjc-framework-Cocoa/AppKit/PredicateEditorSample/


Here is my class, complete with the code I am trying to use it with at
the end.


import objc, sys, os, osax, time
from Foundation import *
from ScriptingBridge import *
from appscript import *


class SystemBridge(NSObject):
"""Class to use the scripting bridge to interact with the system"""
_hideapp = objc.ivar(u"hideapp")
_volume = objc.ivar(u"volume")
_filename = objc.ivar(u"filename")
_filetype = objc.ivar(u"filetype")
_auth = objc.ivar(u"auth")
_logout = objc.ivar(u"logout")
query = objc.ivar(u"query")
StdAdditions = osax.ScriptingAddition()

def init(self):
super(SystemBridge, self).init()
# create and initalize our query
self.query = NSMetadataQuery.alloc().init()

# setup our Spotlight notifications
nf = NSNotificationCenter.defaultCenter()
nf.addObserver_selector_name_object_(self,
'queryNotification:', None, self.query)



# XXX: this framework isn't wrapped yet!
 
self.query.setSortDescriptors_([NSSortDescriptor.alloc().initWithKey_ascending_('kMDItemDisplayName',

True)])
self.query.setDelegate_(self)



return self

def hideApplication_(self, _hideapp):
app(u'System Events').processes[_hideapp].visible.set(False)

def loadResultsFromQuery_(self, notif):
results = notif.object().results()

NSLog("search count = %d", len(results))

# iterate through the array of results, and match to the
existing stores
for item in results:
nameStr = item.valueForAttribute_('kMDItemDisplayName')
print nameStr


def queryNotification_(self, note):
# the NSMetadataQuery will send back a note when updates are
happening.
# By looking at the [note name], we can tell what is happening
if note.name() ==
NSMetadataQueryDidStartGatheringNotification:
# the query has just started
NSLog("search: started gathering")


elif note.name() ==
NSMetadataQueryDidFinishGatheringNotification:
# at this point, the query will be done. You may recieve
an update
# later on.
NSLog("search: finished gathering");
self.loadResultsFromQuery_(note)

elif note.name() ==
NSMetadataQueryGatheringProgressNotification:
# the query is still gathering results...
NSLog("search: progressing...")

elif note.name() == NSMetadataQueryDidUpdateNotification:
# an update will happen when Spotlight notices that a file
as
# added, removed, or modified that affected the search
results.
NSLog("search: an update happened.")


def spotlightFriendlyPredicate_(self, predicate):
if predicate == NSPredicate.predicateWithValue_(True) or
predicate == NSPredicate.predicateWithValue_(False):
return False

elif isinstance(predicate, NSCompoundPredicate):

type = predicate.compoundPredicateType()
cleanSubpredicates = []
for dirtySubpredicate in predicate.subpredicates():
cleanSubpredicate =
self.spotlightFriendlyPredicate_(
dirtySubpredicate)
if cleanSubpredicate:

cleanSubpredicates.append(cleanSubpredicate)

if len(cleanSubpredicates) == 0:
return None

else:
if len(cleanSubpredicates) == 1 and type !=
NSNotPredicateType:
return cleanSubpredicates[0]

else:
return
NSCompoundPredicate.alloc().initWithType_subpredicates_(type,
cleanSubpredicates)

else:
return predicate

def createNewSearchForPredicate_(self, predicate):

# Format search file type
thePredicate = NSPredicate.predicateWithFormat_(
"(kMDItemContentType =
'com.apple.iwork.keynote.key')")
tempPredicate = NSPredicate.predicateWithFormat_(
"(kMDItemDisplayName IN[c] 'preso')")
predicate = NSCompoundPredicate.andPredicateWithSubpredicates_(
[thePredicate, tempPredicate])


   

Hey guys!

2008-09-08 Thread [EMAIL PROTECTED]
hey guys! I have this site www.drachensee.info and i keep posting on
the ubuntu, the latest open soruce buzz.. i post on stuff like editing
the grub menu and other linux related stuff.. so drop in and drop ur
comments ;-]
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] pysqlite 2.5.0 released

2008-09-08 Thread Gerhard Häring

Matthias Huening wrote:

Hi,


- - Connection.enable_load_extension(enabled) to allow/disallow extension
  loading. Allows you to use fulltext search extension, for example ;-)


The following code (from the docs) produces an error:

from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect(":memory:")
# Load the fulltext search extension
con.enable_load_extension(True)
con.execute("select load_extension('./fts3.so')")
con.enable_load_extension(False)


Error is:

con.execute("select load_extension('./fts3.so')")
pysqlite2._sqlite.OperationalError: Das angegebene Modul wurde nicht 
gefunden.


Where should I look for the module?


The sources are in ext/fts3 in the SQLite source tree. I haven't found 
any Makefile, so I it myself using this gcc command:


$ cd .../ext/fts3
$ gcc -shared -o ~/src/gh/pysqlite/build/lib.linux-i686-2.5/fts3.so *.c 
-lsqlite3


-- Gerhard

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


String to hexadecimal conversion

2008-09-08 Thread Praveena P
Hi folks,

I am new to Python... so am not too sure about how the type conversion
works.

I have to read a file that contains hexadecimal data and use the data
further to do some arithmetic calculations.
A sample of the input is : 20E032F8400022005E
The problem I am facing is this:
I am using f.read(2) to read a byte at a time, but the data that is
read is a string rather than a number. So it kind of hampers any
arithmetic operations I perform on this data...

Could you please suggest some method I could use for this?

Thanks guys!
Praveena
--
http://mail.python.org/mailman/listinfo/python-list


Re: Updating python dictionary

2008-09-08 Thread John Machin
On Sep 8, 10:47 am, MK Bernard <[EMAIL PROTECTED]> wrote:
> On Sep 7, 3:37 pm, John Machin <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On Sep 8, 7:51 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
> > > Hello...
>
> > > I have a dict of key/values and I want to change the keys in it, based
> > > on another mapping dictionary. An example follows:
>
> > > MAPPING_DICT = {
> > >     'a': 'A',
> > >     'b': 'B',
>
> > > }
>
> > > my_dict = {
> > >     'a': '1',
> > >     'b': '2'
>
> > > }
>
> > > I want the finished my_dict to look like:
>
> > > my_dict = {
> > >     'A': '1',
> > >     'B': '2'
>
> > > }
>
> > > Whereby the keys in the original my_dict have been swapped out for the
> > > keys mapped in MAPPING_DICT.
>
> > > Is there a clever way to do this, or should I loop through both,
> > > essentially creating a brand new dict?
>
> > Is this homework?
>
> > There seems to be an implicit assumption in the answers so far that
> > your mapping is a 1:1 mapping of all possible input keys.
>
> > If it doesn't include all possible input keys, answers will crash with
> > a KeyError. If there are any many:1 elements in the mapping (for
> > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code
> > in some checks for this.
>
> Thats exactly why I did an explicit check in my post, so as to make
> sure that such a collision could not occur. It would seem that
> something along what I posted would be safer, if less elegant, than
> the others.

I noted two problems:
(1) not covering all input keys: your code explicitly sweeps this
problem under the carpet, and does it laboriously ...
if x in my_dict.keys():
instead of
if x in my_dict:
(2) not a 1:1 mapping -- for example, 'a' and 'b' both map to 'A' (the
only "collision" that I can see), but you don't address that.

Here's some code which attempts to cover the bases:

new_dict = {}
for key in my_dict:
if key not in MAPPING_DICT:
raise NoMapError('blah %r' % key)
else:
new_key = MAPPING_DICT[key]
if new_key in new_dict:
raise ManyToOneError('gurgle %r waffle %r' % (key, new_key))
else:
new_dict[new_key] = my_dict[key]

Having considered what is actually required under the checked-for
conditions, one or both raise statements may be replaced by other
code, and then simplified e.g. the first 4 lines in the loop may end
up being replaced by
new_key = MAPPING_DICT.get(key, key)
as already suggested by one respondent.

Note that useful use-cases for any variety of this key-change exercise
may have many more items in MAPPING_DICT than there are in my_dict (a
big language dictionary and a few fragments of text to be
"translated"), or vice versa (a small synonym dictionary (color ->
colour, center -> centre) and a big input to be "standardised") so
it's a good idea to inquire which is likely to be the smaller and
iterate over that if the requirements permit it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: universal unicode font for reportlab

2008-09-08 Thread Ben Finney
Laszlo Nagy <[EMAIL PROTECTED]> writes:

> I could not find any free TTF font that can do latin1, latin2,
> arabic, chinese and other languages at the same time. Is there a
> single font that is able to handle these languages?

The GNU Unifont http://en.wikipedia.org/wiki/GNU_Unifont>
http://unifoundry.com/unifont.html> covers an impressive range of
the Unicode Basic Multilingual Plane.

Unifont is originally a bitmap font, but was recently made available
in TrueType format 
http://www.lgm.cl/trabajos/unifont/index.en.html>.

Both are available in Debian 'lenny'; the 'unifont' and 'ttf-unifont'
packages, respectively.

-- 
 \“Science doesn't work by vote and it doesn't work by |
  `\authority.” —Richard Dawkins, _Big Mistake_ (The Guardian, |
_o__)  2006-12-27) |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Syntax Problem with strptime in Python 2.4

2008-09-08 Thread W. eWatson
Apparently, use of strptime of datetime needs a workaround in Python 2.4 to 
work properly. The workaround is d = 
datetime.datetime(*(time.strptime(date_string, format)[0:5])). However, when 
I try to use it, or even use it the regular way, it fails with

AttributeError: type object 'datetime.datetime' has no attribute 'datetime'.
From the following code code segment:

format = '%Y%m%d_%H%M%S'
#d=datetime.strptime('20080321_113405', format)-- typical use
print time.strptime('20080321_113405', format)[0:5]
d = datetime.datetime(*time.strptime('20080321_113405', format)[0:5])

Does anyone know how to make this work in 2.4? If not, is there a way to 
achieve the same result?

--
   W. eWatson

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

Web Page: 

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


Re: [ANN] pysqlite 2.5.0 released

2008-09-08 Thread Matthias Huening

Gerhard Häring (08.09.2008 10:12):



Error is:

con.execute("select load_extension('./fts3.so')")
pysqlite2._sqlite.OperationalError: Das angegebene Modul wurde nicht 
gefunden.


Where should I look for the module?


The sources are in ext/fts3 in the SQLite source tree. I haven't found 
any Makefile, so I it myself using this gcc command:


$ cd .../ext/fts3
$ gcc -shared -o ~/src/gh/pysqlite/build/lib.linux-i686-2.5/fts3.so *.c 
-lsqlite3




Thanks!
Will fts3 be integrated in the Python 2.6 release?

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


Re: Updating python dictionary

2008-09-08 Thread John Machin
On Sep 8, 9:14 am, "James Mills" <[EMAIL PROTECTED]> wrote:
> On Mon, Sep 8, 2008 at 8:59 AM, John Machin <[EMAIL PROTECTED]> wrote:
> > What do you mean by "this right"? Perhaps the Divine Right of OPs,
> > managers, examiners, business analysts, etc never to give a complete
> > spec up front and never to contemplate the consequences of Murphy's
> > Law?
>
> Now you're being silly.
>
Only in so far as I followed the habit of OPs and suchlike by using
"never" instead of "rarely".

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


Re: Error importing mxTidy

2008-09-08 Thread M.-A. Lemburg
On 2008-09-07 15:00, Mike Hostetler wrote:
> I built and installed mx-experimental 3.0.0 from source and it seemed to go
> fine.  But when I try to import it, I get this:
> 
> localhost% python -c "import mx.Tidy"
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "mx/Tidy/__init__.py", line 7, in ?
> from Tidy import *
>   File "mx/Tidy/Tidy.py", line 7, in ?
> from mxTidy import *
>   File "mx/Tidy/mxTidy/__init__.py", line 7, in ?
> from mxTidy import *
> ImportError: No module named mxTidy
> 
> This seems strange to me, since it found the mx.Tidy module but not the mxTidy
> module underneath it.  But I guess I don't know how the mx-experimental 
> classes
> are put together, so I can't really guess what is happening.  Thus I am 
> posting
> here. :)

Which platform are you using ?

-- 
Marc-Andre Lemburg
eGenix.com

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


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


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list


Unable to start a process with subprocess Popen()

2008-09-08 Thread dudeja . rajat
Hi,

I'm using the subprocess module's Popen() to start a batch file. This
batch file basically calls an exe which also gets started.
Unfortunately, this does not produce any results. I looked into the
Task bar that this exe has started but it does not consume and cpu so
I believet that this exe is not working.


I used the following command to start the batch fiile:

testing = subprocess.Popen([batchFilePath], \
   shell = True, \
   stdout = subprocess.PIPE, \
   stderr = subprocess.PIPE).communicate()[0]


batchFilePath is the path of the batch file.



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


Re: Syntax Problem with strptime in Python 2.4

2008-09-08 Thread skip

>> Apparently, use of strptime of datetime needs a workaround in Python
>> 2.4 to work properly. The workaround is d =
>> datetime.datetime(*(time.strptime(date_string,
>> format)[0:5])). However, when I try to use it, or even use it the
>> regular way, it fails with AttributeError: type object
>> 'datetime.datetime' has no attribute 'datetime'.

Works for me:

>>> import datetime
>>> format = '%Y%m%d_%H%M%S'
>>> import time
>>> print time.strptime('20080321_113405', format)[0:5]
(2008, 3, 21, 11, 34)
>>> d = datetime.datetime(*time.strptime('20080321_113405', format)[0:5])
>>> d
datetime.datetime(2008, 3, 21, 11, 34)

Python 2.4.4, Mac OS X 10.5.4.

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


Re: String to hexadecimal conversion

2008-09-08 Thread Praveena P
On Sep 8, 2:31 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On Sep 8, 7:05 pm, Praveena P <[EMAIL PROTECTED]> wrote:
>
> > Hi folks,
>
> > I am new to Python... so am not too sure about how the type conversion
> > works.
>
> > I have to read a file that contains hexadecimal data and use the data
> > further to do some arithmetic calculations.
> > A sample of the input is : 20E032F8400022005E
> > The problem I am facing is this:
> > I am using f.read(2) to read a byte at a time, but the data that is
> > read is a string rather than a number. So it kind of hampers any
> > arithmetic operations I perform on this data...
>
> > Could you please suggest some method I could use for this?
>
> *IF* all the data consists of unsigned 8-bit integers
> a_byte = f.read(2)
> uint8 = int(a_byte, 16)
>
> But I doubt it and that would be rather slow anyway. If your data is
> homogenous, look at the array module. Otherwise, once you've worked
> out how to break your file down into records, and what the layout of
> each record is, you'll need the struct module.
>
> HTH,
> John

Hey John,

Thanks! That was useful...
I am still putting the code together with all the operations... will
probably have loads more queries... :-)

Have a good day!
Praveena
--
http://mail.python.org/mailman/listinfo/python-list


how to use execfile with input parameters

2008-09-08 Thread Shi, Shaozhong
I have a Python script expecting 11 or 12 input parameters.  How do I
use execfile to execute the Python script in my new Python script?  How
do I pass in the input parameters?

 

Yours sincerely,

 

David


This email has been scanned for all viruses by the MessageLabs Email
Security System.--
http://mail.python.org/mailman/listinfo/python-list

Re: Unable to start a process with subprocess Popen()

2008-09-08 Thread dudeja . rajat
On Mon, Sep 8, 2008 at 11:50 AM,  <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm using the subprocess module's Popen() to start a batch file. This
> batch file basically calls an exe which also gets started.
> Unfortunately, this does not produce any results. I looked into the
> Task bar that this exe has started but it does not consume and cpu so
> I believet that this exe is not working.
>
>
> I used the following command to start the batch fiile:
>
> testing = subprocess.Popen([batchFilePath], \
>   shell = True, \
>   stdout = subprocess.PIPE, \
>   stderr = subprocess.PIPE).communicate()[0]
>
>
> batchFilePath is the path of the batch file.
>
>
>
> --
> Regrads,
> Rajat
>

Ok, I re-phrase my question:

there is a batch file that executes a exe file. The batch just works
if run from command prompt and produces output to standard output and
the file.

Now, I try to call the same batch file from subprocess.Pope() call.
The batch file gets called and that internally also calls the exe
file.

But, the exe just runs forever i.e. hangs and does not produces output
, atleast not to the file.

Please suggest is there is something wrong with the above code.

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


Re: [ANN] pysqlite 2.5.0 released

2008-09-08 Thread Gerhard Häring

Matthias Huening wrote:

Gerhard Häring (08.09.2008 10:12):



Error is:

con.execute("select load_extension('./fts3.so')")
pysqlite2._sqlite.OperationalError: Das angegebene Modul wurde nicht 
gefunden.


Where should I look for the module?


The sources are in ext/fts3 in the SQLite source tree. I haven't found 
any Makefile, so I it myself using this gcc command:


$ cd .../ext/fts3
$ gcc -shared -o ~/src/gh/pysqlite/build/lib.linux-i686-2.5/fts3.so 
*.c -lsqlite3


Thanks!
Will fts3 be integrated in the Python 2.6 release?


No (only relevant on win32, where we also ship the SQLite DLL). Neither 
will be the ability to load extensions modules. It's just too late to 
add features now.


But AFAIK it's possible to compile a custom SQLite with appropriate 
flags to ./configure that will include the fulltext search extension.


-- Gerhard

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


Where does the command "ls" in some doctest files come from ?

2008-09-08 Thread KLEIN Stéphane
Hi,

for example, in http://svn.zope.org/zc.buildout/trunk/src/zc/buildout/
tests.py?rev=89831&view=auto test file, there is this doctests :

def develop_verbose():
"""
We should be able to deal with setup scripts that aren't setuptools based.

>>> mkdir('foo')
>>> write('foo', 'setup.py',
... '''
... from setuptools import setup
... setup(name="foo")
... ''')

>>> write('buildout.cfg',
... '''
... [buildout]
... develop = foo
... parts = 
... ''')

>>> print system(join('bin', 'buildout')+' -vv'), # doctest: +ELLIPSIS
Installing...
Develop: '/sample-buildout/foo'
...
Installed /sample-buildout/foo
...

>>> ls('develop-eggs')
-  foo.egg-link
-  zc.recipe.egg.egg-link

>>> print system(join('bin', 'buildout')+' -vvv'), # doctest: 
+ELLIPSIS
Installing...
Develop: '/sample-buildout/foo'
in: '/sample-buildout/foo'
... -q develop -mxN -d /sample-buildout/develop-eggs/...


"""

I wonder where does the "ls('develop-eggs')" command come from ?

It is doctest buildin command ? Where can I found some documentation 
about that ? I see this page http://docs.python.org/lib/module-
doctest.html and I found nothing about that subject.

Thanks for your help,
Stephane
http://docs.python.org/lib/module-doctest.html

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


Re: tracking collection modification

2008-09-08 Thread usenet . tolomea
On Sep 7, 8:54 pm, [EMAIL PROTECTED] wrote:
> I'm working on a remote object system, something kinda like Pyro.
> For the purposes of caching I need to be able to tell if a given
> dict / list / set has been modified.
> Ideally what I'd like is for them to have a modification count
> variable that increments every time the particular collection is
> modified. Unfortunately I can't find anything like that and since this
> needs to work for the regular normal list / dict / set objects
> subclassing them to add the modification count isn't useful.
> I realize I could take a copy and then compare the copy to the
> original, but that's a fairly heavy handed approach and I was hoping
> for something light and fast.
> Does anyone have any suggestions on best to approach this?

additionally I don't need to know if the things the list (etc)
references have changed, only the list itself
--
http://mail.python.org/mailman/listinfo/python-list


Re: Test if list contains another list

2008-09-08 Thread James Mills
Hi,

>>> a = [1,2,3]
>>> b = [3,2,1,4]
>>> a = set(a)
>>> b = set(b)
>>> a.intersection(b)
set([1, 2, 3])

Is this what you want ?

cheers
James

On 9/8/08, mathieu <[EMAIL PROTECTED]> wrote:
> Hi there,
>
>   I am trying to write something very simple to test if a list
>  contains another one:
>
>  a = [1,2,3]
>
>  b = [3,2,1,4]
>
>  but 'a in b' returns False. How do I check that a is indeed contained
>  in b ?
>
>  thanks
>
> --
>  http://mail.python.org/mailman/listinfo/python-list
>


-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: universal unicode font for reportlab

2008-09-08 Thread Laszlo Nagy



Laszlo Nagy <[EMAIL PROTECTED]> writes:

  

I could not find any free TTF font that can do latin1, latin2,
arabic, chinese and other languages at the same time. Is there a
single font that is able to handle these languages?



The GNU Unifont http://en.wikipedia.org/wiki/GNU_Unifont>
http://unifoundry.com/unifont.html> covers an impressive range of
the Unicode Basic Multilingual Plane.

Unifont is originally a bitmap font, but was recently made available
in TrueType format 
http://www.lgm.cl/trabajos/unifont/index.en.html>.


Both are available in Debian 'lenny'; the 'unifont' and 'ttf-unifont'
packages, respectively.
  
I found out that dejavu is what I need. It covers the languages I need 
and more:


http://dejavu.svn.sourceforge.net/viewvc/dejavu/tags/version_2_26/dejavu-fonts/langcover.txt


Thanks four your help!

  L

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


Re: tracking collection modification

2008-09-08 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> On Sep 7, 8:54 pm, [EMAIL PROTECTED] wrote:
>> I'm working on a remote object system, something kinda like Pyro.
>> For the purposes of caching I need to be able to tell if a given
>> dict / list / set has been modified.
>> Ideally what I'd like is for them to have a modification count
>> variable that increments every time the particular collection is
>> modified. Unfortunately I can't find anything like that and since this
>> needs to work for the regular normal list / dict / set objects
>> subclassing them to add the modification count isn't useful.
>> I realize I could take a copy and then compare the copy to the
>> original, but that's a fairly heavy handed approach and I was hoping
>> for something light and fast.
>> Does anyone have any suggestions on best to approach this?
> 
> additionally I don't need to know if the things the list (etc)
> references have changed, only the list itself

No chance. E.g. ZODB is faced with the same problem and requires you to use
certain collection implementations to make this work.

And don't forget that such a scheme is hard to implement in the face of
concurrent access by various clients - as client connection has to keep
track of the last-modified-state separately.

I'd say that for small to medium-sized collections, it's faster to just
marshal them each time. Beyond that, make the heavy-handed checking - and
offer dirty-state-aware collection classes one can use to optimize specific
cases.

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

Re: Read and write binary data

2008-09-08 Thread Mars creature
On Sep 7, 8:55 pm, Patrick Maupin <[EMAIL PROTECTED]> wrote:
> On Sep 7, 5:41 pm, Mars creature <[EMAIL PROTECTED]> wrote:
>
> > Hi guys,
> >   I am new to Python, and thinking about migrating to it from matlab
> > as it is a really cool language. Right now, I am trying to figure out
> > how to control read and write binary data, like
> > 'formatted','stream','big-endian','little-edian' etc.. as in fortran.
> > I googled, but can not find a clear answer. Anyone has clue where can
> > I learn it? Thanks!!
> > Jinbo
>
> Start by looking at the array module.
>
> Regards,
> Pat

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


Re: Syntax Problem with strptime in Python 2.4

2008-09-08 Thread Diez B. Roggisch
W. eWatson wrote:

> Apparently, use of strptime of datetime needs a workaround in Python 2.4
> to work properly. The workaround is d =
> datetime.datetime(*(time.strptime(date_string, format)[0:5])). However,
> when I try to use it, or even use it the regular way, it fails with
> AttributeError: type object 'datetime.datetime' has no attribute
> 'datetime'.
>  From the following code code segment:
> 
> format = '%Y%m%d_%H%M%S'
> #d=datetime.strptime('20080321_113405', format)-- typical use
> print time.strptime('20080321_113405', format)[0:5]
> d = datetime.datetime(*time.strptime('20080321_113405', format)[0:5])
> 
> Does anyone know how to make this work in 2.4? If not, is there a way to
> achieve the same result?

This is not what you think it is. All your problem is that you do

from datetime import datetime

which imports the datetime-class, but then try to access

datetime.datetime

as if you had done

import datetime.


This actually is a wart in the datetime-module - it would be better if the
classes in there would follow PEP-8.

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


universal unicode font for reportlab

2008-09-08 Thread Laszlo Nagy
I need to create multi lingual invoices from reportlab. I think it is 
possible to use UTF 8 strings but there is a problem with the font. I 
could not find any free TTF font that can do latin1, latin2, arabic, 
chinese and other languages at the same time. Is there a single font 
that is able to handle these languages? (Most of our invoices will be 
for EN, FR, DE, HU, SK, CZ, RO but some of them needs to be in Chinese.)


Thanks,

  Laszlo

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


Re: Where does the command "ls" in some doctest files come from ?

2008-09-08 Thread Steven D'Aprano
On Mon, 08 Sep 2008 12:15:15 +, KLEIN Stéphane wrote:

> Hi,
> 
> for example, in http://svn.zope.org/zc.buildout/trunk/src/zc/buildout/
> tests.py?rev=89831&view=auto test file, there is this doctests :

[snip]

> >>> ls('develop-eggs')


> I wonder where does the "ls('develop-eggs')" command come from ?
> 
> It is doctest buildin command ? 

Easy to find out: import doctest and see for yourself:

>>> import doctest
>>> doctest.ls
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute 'ls'

You found the ls() function in a docstring from Zope. The doctest seems 
to be testing ls(). That suggests to me that ls() is defined in Zope, not 
doctest.

Why do you ask?



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

Dictionaries and loops

2008-09-08 Thread Mike P
Hi All
i have a CSV file that i'm reading in and each line has the look of
the below

{None: ['User-ID', 'Count']}
{None: ['576460847178667334', '1']}
{None: ['576460847178632334', '8']}

i want to make a dictionary of items in the form
{576460847178667334:1, 576460847178632334:8, . } for all rows in
the datafile

my code so far is thus:

dict1={}
j=1
for row in reader1:
  if j==1:
j+=1
continue #thus allowing me to skip the first row
  if j>1:
for element in row.values():
  for item in element:
if int(item)%2==0:
  dict1[int(item)] = int(item)+1
# i know this is the problem line as it's not picking the second item
up just finding the first and increasing it, but i can't figure out
how to correct this?
  j+=1

I get one dictionary from this but not the correct data inside, can
anyone help?

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


Re: Test if list contains another list

2008-09-08 Thread Bruno Desthuilliers

mathieu a écrit :

Hi there,

  I am trying to write something very simple to test if a list
contains another one:

a = [1,2,3]

b = [3,2,1,4]

but 'a in b' returns False.


Indeed. Lists are not sets, and the fact that all elements of list a 
happens to also be part of list b doesn't make the list a itself an 
element of list b.


>>> a = [1, 2, 3]
>>> b = [3,2,1,4]
>>> c = [b, a]
>>> a in c
True
>>> b in c
True
>>> c
[[3, 2, 1, 4], [1, 2, 3]]
>>>



How do I check that a is indeed contained
in b ?


But that's what you did - you *did* checked if a was contained in b, and 
this is not the case. What you want is to check if *all elements* of a 
are contained in b, which is quite another problem. Now the answer to 
your question : use sets.


>>> set(a).issubset(set(b))
True
>>>

HTH

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


Re: Test if list contains another list

2008-09-08 Thread Christian Heimes

mathieu wrote:

Hi there,

  I am trying to write something very simple to test if a list
contains another one:

a = [1,2,3]

b = [3,2,1,4]

but 'a in b' returns False. How do I check that a is indeed contained
in b ?


Use sets:

>>> a = [1,2,3]
>>> b = [3,2,1,4]
>>> set(a).issubset(set(b))
True


Christian

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


Re: Test if list contains another list

2008-09-08 Thread mathieu
On Sep 8, 9:32 am, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> mathieu a écrit :
>
> > Hi there,
>
> >   I am trying to write something very simple to test if a list
> > contains another one:
>
> > a = [1,2,3]
>
> > b = [3,2,1,4]
>
> > but 'a in b' returns False.
>
> Indeed. Lists are not sets, and the fact that all elements of list a
> happens to also be part of list b doesn't make the list a itself an
> element of list b.
>
>  >>> a = [1, 2, 3]
>  >>> b = [3,2,1,4]
>  >>> c = [b, a]
>  >>> a in c
> True
>  >>> b in c
> True
>  >>> c
> [[3, 2, 1, 4], [1, 2, 3]]
>  >>>
>
> > How do I check that a is indeed contained
> > in b ?
>
> But that's what you did - you *did* checked if a was contained in b, and
> this is not the case. What you want is to check if *all elements* of a
> are contained in b, which is quite another problem. Now the answer to
> your question : use sets.
>
>  >>> set(a).issubset(set(b))
> True
>  >>>

thanks all !
--
http://mail.python.org/mailman/listinfo/python-list


Re: String to hexadecimal conversion

2008-09-08 Thread Praveena P
On Sep 8, 2:05 pm, Praveena P <[EMAIL PROTECTED]> wrote:
> Hi folks,
>
> I am new to Python... so am not too sure about how the type conversion
> works.
>
> I have to read a file that contains hexadecimal data and use the data
> further to do some arithmetic calculations.
> A sample of the input is : 20E032F8400022005E
> The problem I am facing is this:
> I am using f.read(2) to read a byte at a time, but the data that is
> read is a string rather than a number. So it kind of hampers any
> arithmetic operations I perform on this data...
>
> Could you please suggest some method I could use for this?
>
> Thanks guys!
> Praveena

I was thinking of using dictionary like this:
hex_to_decimal = {"1":"1", "2":"2", "3":"3", "4":"4", "5":"5",
"6":"6", "7":"7", "8":"8", "9":"9", "A":"10", "B":"11", "C":"12",
"D":"13", "E":"14", "F":"15", "0":"0"}

Extracting one character at a time and converting to decimal, and then
using the decimal numbers generated for the further calculations

Would there be a simpler way to do it?
--
http://mail.python.org/mailman/listinfo/python-list


Test if list contains another list

2008-09-08 Thread mathieu
Hi there,

  I am trying to write something very simple to test if a list
contains another one:

a = [1,2,3]

b = [3,2,1,4]

but 'a in b' returns False. How do I check that a is indeed contained
in b ?

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


Clearing a session and reload() problem (with repro error)

2008-09-08 Thread Rafe
Hi,

This seems to be an old question, and I've read back a bit, but rather
than assume the answer is "you can't do that", I'd thought I'd post my
version of the question along with a reproducible error to illustrate
my confusion.

My problem is that I'm using Python inside XSI (a 3D graphics
application). If I want to restart Python, I have to restart XSI. This
is no small amount of time wasted.

The solution would be to somehow unload modules and all references and
allow my imports to rebuild the cache. I suppose it would be great to
clear the python session completely, but the 3D application might have
added something to the session at startup (I doubt this though as I
don't see any imported modules outside the norm).

I've tried to use reload with a very simple algorithm. Simply run
through every imported module, ignoring anything that is "None" or on
the C: drive (all of our python is on a network drive so this hack
works for me for now) and reload() it. I've come to realize that this
isn't near intelligent enough to handle sub-packages.

Before I post the repro, my questions are:
1) Does anyone have a work-flow for my situation that doesn't use
Reload, and doesn't involve restarting the app for every edit/fix

2) Can anyone help point me in the right direction to build a
dependable algorithm to cleanly reload all loaded modules? NOTE: I
don't need to maintain anything in memory (i.e. instances, pointers,
etc.) Everything will be initialized again each time. I'm not asking
for code. Just some ideas or pseudo-code would do nicely.

Here is a "simple" repro...

Package Structure:
---
inheritRepro
__init__.py
baseLib.py
child
__init__.py


__init__.py:

import sys, os

def reloadModules():
"""
Reload all imported modules that are not on the C: drive.
"""
print "Reloading Python Modules..."

# Iterate over all IMPORTED modules
modules = sys.modules
for modName in modules:
mod = modules[modName]

# Skip None types and other itesm we don't care about
if modName == "__main__" or not hasattr(mod,"__file__"):
continue

# Get the drive and skip anything on the C: drive
drive = os.path.splitdrive(mod.__file__)[0]
if drive != "C:":
reload(mod)
print "Reloaded %s" % mod


baseLib.py:
---
class BaseClassA(object):
pass

class BaseClassB(BaseClassA):
def __init__(self):
super(BaseClassB, self).__init__()


child.__init__.py:

import inheritRepro.baseLib as baseLib

class ChildClass(baseLib.BaseClassB):
def __init__(self):
super(ChildClass, self).__init__()


RUN:
---
>>> import inheritRepro
>>> import inheritRepro.child as child
>>> obj = child.ChildClass()
>>> print obj

>>> inheritRepro.reloadModules()# Output omitted, but this worked.
>>> import inheritRepro
>>> import inheritRepro.child as child
>>> obj = child.ChildClass()
Traceback (most recent call last):
  File "", line 0, in 
  File "\\nas6tb\PROJECTS\tech\users\rafe.sacks\python\inheritRepro
\child\__init__.py", line 5, in __init__
super(ChildClass, self).__init__()
  File "\\nas6tb\PROJECTS\tech\users\rafe.sacks\python\inheritRepro
\baseLib.py", line 6, in __init__
super(BaseClassB, self).__init__()
TypeError: super(type, obj): obj must be an instance or subtype of
type


NOTE: this works if I don't use a sub-package for 'child' (child.py
instead). Is it overly simple to assume reloading by file structure
might work?

Right now I'm getting around this by reload()-ing the right package
after running reloadModules() if an error occurs. It's a bit
frustrating that it cost me two days of work before I realized it was
reload() causing this error and not super() or some other unknown-to-
me inheritance/package structure problem. I rebuilt my code module by
module until I noticed, quite by accident, that the thing worked once
and then never again! oh well, these are the joys of learning the
hard way.

I know this was a long one. If you made it this far, thanks for
reading,

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


Re: String to hexadecimal conversion

2008-09-08 Thread John Machin
On Sep 8, 7:05 pm, Praveena P <[EMAIL PROTECTED]> wrote:
> Hi folks,
>
> I am new to Python... so am not too sure about how the type conversion
> works.
>
> I have to read a file that contains hexadecimal data and use the data
> further to do some arithmetic calculations.
> A sample of the input is : 20E032F8400022005E
> The problem I am facing is this:
> I am using f.read(2) to read a byte at a time, but the data that is
> read is a string rather than a number. So it kind of hampers any
> arithmetic operations I perform on this data...
>
> Could you please suggest some method I could use for this?

*IF* all the data consists of unsigned 8-bit integers
a_byte = f.read(2)
uint8 = int(a_byte, 16)

But I doubt it and that would be rather slow anyway. If your data is
homogenous, look at the array module. Otherwise, once you've worked
out how to break your file down into records, and what the layout of
each record is, you'll need the struct module.

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


Re: universal unicode font for reportlab

2008-09-08 Thread Laszlo Nagy




The GNU Unifont http://en.wikipedia.org/wiki/GNU_Unifont>
http://unifoundry.com/unifont.html> covers an impressive range of
the Unicode Basic Multilingual Plane.

Unifont is originally a bitmap font, but was recently made available
in TrueType format 
http://www.lgm.cl/trabajos/unifont/index.en.html>.


Both are available in Debian 'lenny'; the 'unifont' and 'ttf-unifont'
packages, respectively.
I found out that dejavu is what I need. It covers the languages I need 
and more:


http://dejavu.svn.sourceforge.net/viewvc/dejavu/tags/version_2_26/dejavu-fonts/langcover.txt
Sorry, this did not work either. Dejavu does support cyrillic and greek 
characters but I have to load a different ttf for that. They are no 
unified. :-( The only one that worked so far was "unifont.tff" but it is 
very ugly above point size=10.


Can you tell me what kind of font Geany is using on my Ubuntu system? 
The preferences tells that it is "monospace" but when I load 
VeraMono.ttf in reportlab, it will not even display latin2 characters. 
In contrast, please look at this example that show my test program in Geany:


http://www.shopzeus.com/geany.jpg

It is a real scalable truetype font, displaying latin 1, latin2, 
chinese, russian and japanese characters. Is it the same font? Does this 
mean that reportlab is buggy? If I could load the same font that geany 
uses, it would probably solve my problem forever.


Thanks,

Laszlo

# -*- coding: UTF-8 -*-
import os,sys
import copy

from reportlab.pdfgen import canvas
from reportlab.lib import pagesizes


# we know some glyphs are missing, suppress warnings
import reportlab.rl_config
reportlab.rl_config.warnOnMissingFontGlyphs = 0
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
#pdfmetrics.registerFont(TTFont('wpsu', 'vera/VeraMono.ttf '))
pdfmetrics.registerFont(TTFont('wpsu', 'VeraMono.ttf'))


xsize,ysize = PAGESIZE = pagesizes.A4

lines = [
"ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP",
"雑誌のベストセラー",
"中国的网页",
"Сайт в разработке",
]

c = canvas.Canvas('labels.pdf', pagesize=PAGESIZE)
for idx,line in enumerate(lines):
textobject = c.beginText()
textobject.setFont('wpsu',10)
textobject.setTextOrigin(100, 700 - 50*idx)
textobject.textLine(line)
c.drawText(textobject)
c.save()

if sys.platform=='win32':
os.system("labels.pdf")
else:
os.system("evince labels.pdf &")
--
http://mail.python.org/mailman/listinfo/python-list

flock trouble

2008-09-08 Thread Seb
I'm trying to implement a file server using the code below. However
the locking doesn't work. I can delete while put'ing a file.

Anyone got an idea about why?

best regards,
seb




#! /usr/bin/env python

import Pyro.core, Pyro.naming
from Pyro.errors import PyroError, NamingError
import sys
import urllib
import os
import fcntl

class fileServer(Pyro.core.ObjBase):
basePath = "/home/snot/diku/dist/opg2/files_to_serve"

def __init__(self):
Pyro.core.ObjBase.__init__(self)
self.basePath = self.basePath.strip("..")
if not os.path.isdir(self.basePath) or
os.path.islink(self.basePath):
raise "invalid path"

def get(self, uri):
f = open(self.basePath + uri, 'r+')
fcntl.flock(f, fcntl.LOCK_SH)
data = f.read()
fcntl.flock(f, fcntl.LOCK_UN)
f.close()
return data

def put(self, uri, payload):
f = open(self.basePath + urllib.unquote_plus(uri), 'w')
fcntl.flock(f, fcntl.LOCK_EX)
f.truncate()
f.write(payload)
fcntl.flock(f, fcntl.LOCK_UN)
f.close()

def delete(self, uri):
f = open(self.basePath + urllib.unquote_plus(uri), 'w')
fcntl.flock(f, fcntl.LOCK_EX)
os.unlink(self.basePath + uri)
fcntl.flock(f, fcntl.LOCK_UN)
f.close()

try:
Pyro.core.initServer()
daemon = Pyro.core.Daemon()
locator = Pyro.naming.NameServerLocator()
print 'Searching for Name Server...'
try:
ns = locator.getNS()
except Pyro.errors.PyroError, message:
print message
sys.exit(1)

daemon.useNameServer(ns)

try:
ns.unregister("fileServer")
except NamingError:
pass

uri = daemon.connect(fileServer(), "fileServer")

print "The daemon runs on port:", daemon.port
print "The object's uri is:", uri

daemon.requestLoop()
except KeyboardInterrupt:
ns.unregister("fileServer")
print "ctrl + c pressed"

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


Re: Learning Python

2008-09-08 Thread Alan G Isaac

On 9/6/2008 5:17 AM James Pilling apparently wrote:

Hi im currently starting to learn python in sixth form at school any tips?


The books suggestions of others are quite good.
Here is another approach: pick an easily understandable
application, and work doing things with it.

Perhaps immodestly, I think that as soon as you
understand how to define a function and a class,
you can treat this paper
http://jasss.soc.surrey.ac.uk/11/3/8.html
as an introduction to applied Python programming.
The application area is very specific---game theoretic
simulations---but the illustrated techniques are
meant to be more general.

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


Re: tracking collection modification

2008-09-08 Thread Paul Boddie
On 7 Sep, 12:54, [EMAIL PROTECTED] wrote:
> I'm working on a remote object system, something kinda like Pyro.
> For the purposes of caching I need to be able to tell if a given
> dict / list / set has been modified.
> Ideally what I'd like is for them to have a modification count
> variable that increments every time the particular collection is
> modified. Unfortunately I can't find anything like that and since this
> needs to work for the regular normal list / dict / set objects
> subclassing them to add the modification count isn't useful.

What you appear to need here is some kind of proxying solution - a
layer which records accesses to the objects, distinct from the objects
themselves. I believe that the PyPy project provides something of this
nature:

http://codespeak.net/pypy/dist/pypy/doc/objspace-proxies.html

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


Re: Dictionaries and loops

2008-09-08 Thread Bruno Desthuilliers

Mike P a écrit :

Hi All
i have a CSV file that i'm reading in and each line has the look of
the below

{None: ['User-ID', 'Count']}
{None: ['576460847178667334', '1']}
{None: ['576460847178632334', '8']}


This doesn't look like a CSV file at all... Is that what you actually 
have in the file, or what you get from the csv.reader ???



i want to make a dictionary of items in the form
{576460847178667334:1, 576460847178632334:8, . } for all rows in
the datafile

my code so far is thus:

dict1={}
j=1
for row in reader1:
  if j==1:
j+=1
continue #thus allowing me to skip the first row
  if j>1:


Drop this, and call reader1.next() before entering the loop.


for element in row.values():
  for item in element:
if int(item)%2==0:
  dict1[int(item)] = int(item)+1


You're repeating the same operation (building an int from a string) 
three time, where one would be enough:


   for item in element:
 item = int(item)
 if item %2 == 0: # or : if not item % 2:
   dict1[item] = item + 1

But this code is not going to yield the expected result...


# i know this is the problem line as it's not picking the second item
up just finding the first and increasing it, but i can't figure out
how to correct this?


Mmm... What about learning Python instead of trying any random code ? 
Programming by accident won't take you very far, and you can't expect 
this neswgroup to do your own work.



Ok, assuming your CSV file looks like this - and you never have 
duplicate values for the User-id column:


# source.csv
"User-ID", "Count"
576460847178667334, 1
576460847178632334, 8'

Here's a possible solution:

result = {}
src = open("source.csv", "rb")
try:
  reader = csv.reader(src)
  reader.next()
  for row in reader:
  user_id, count = int(row[0]), int(row[1])
  result[user_id] = count
finally:
  src.close()

or more tersely:

src = open("source.csv", "rb")
try:
  reader = csv.reader(src)
  reader.next()
  result = dict(map(int, row) for row in reader)
finally:
  src.close()

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


Re: max(), sum(), next()

2008-09-08 Thread Boris Borcic

David C. Ullrich wrote:


(ii) If A is a subset of B then we should have
max(A) <= max(B). This requires that max(empty set)
be something that's smaller than everything else.
So we give up on that.



Er, what about instances of variations/elaborations on

class Smaller(object) : __cmp__ = lambda *_ : -1

?

Cheers, BB

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


Re: Dictionaries and loops

2008-09-08 Thread bearophileHUGS
Few solutions, not much tested:

data = """{None: ['User-ID', 'Count']}
{None: ['576460847178667334', '1']}
{None: ['576460847178632334', '8']}"""

lines = iter(data.splitlines())
lines.next()

identity_table = "".join(map(chr, xrange(256)))
result = {}
for line in lines:
parts = line.translate(identity_table, "'[]{},").split()
key, val = map(int, parts[1:])
assert key not in result
result[key] = val
print result

(With Python 3 finally that identity_table can be replaced by None)

# --

import re

patt = re.compile(r"(\d+).+?(\d+)")

lines = iter(data.splitlines())
lines.next()

result = {}
for line in lines:
key, val = map(int, patt.search(line).groups())
assert key not in result
result[key] = val
print result

# --

from itertools import groupby

lines = iter(data.splitlines())
lines.next()

result = {}
for line in lines:
key, val = (int("".join(g)) for h,g in groupby(line,
key=str.isdigit) if h)
assert key not in result
result[key] = val
print result

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


Re: Dictionaries and loops

2008-09-08 Thread bearophileHUGS
Bruno Desthuilliers:
> This doesn't look like a CSV file at all... Is that what you actually
> have in the file, or what you get from the csv.reader ???

I presume you are right, the file probably doesn't contain that stuff
like I have assumed in my silly/useless solutions :-)

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


Re: Dictionaries and loops

2008-09-08 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

Bruno Desthuilliers:

This doesn't look like a CSV file at all... Is that what you actually
have in the file, or what you get from the csv.reader ???


I presume you are right, the file probably doesn't contain that stuff
like I have assumed in my silly/useless solutions :-)


Yeps. I suspect the OP found a very creative way to misuse 
csv.DictReader, but I couldn't figure out how he managed to get such a mess.

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


Re: firefox timestamp

2008-09-08 Thread Fredrik Lundh

abhilash pp wrote:


I don't know if this question will fit on this section,
any way my query is , i have used one script demork.py to extract 
details from Firefox history.dat file
and now the problem is how to convert the TIMESTAMP given by that to 
normal date and time.

example timestams are like this,

1202919771609375
1213874676203125
1215693263859375

i have used datetime module for this but it gave me error


a quick googling indicates that the file contains microseconds, not 
seconds.  dividing by 1e6 should do the trick:


>>> t = 1202919771609375
>>> datetime.datetime.fromtimestamp(t / 1e6)
datetime.datetime(2008, 2, 13, 17, 22, 51, 609375)



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


Re: Dictionaries and loops

2008-09-08 Thread Mike P
Thanks for the solution above,

The raw data looked like
User-ID,COUNTS
576460840144207854,6
576460821700280307,2
576460783848259584,1
576460809027715074,3
576460825909089607,1
576460817407934470,1

and i used

CSV_INPUT1 = "C:/Example work/Attr_model/Activity_test.csv"
fin1 = open(CSV_INPUT1, "rb")
reader1 = csv.DictReader((fin1), [], delimiter=",")
for row in reader1:
print row

with the following outcome.
{None: ['User-ID', 'COUNTS']}
{None: ['576460840144207854', '6']}
{None: ['576460821700280307', '2']}
{None: ['576460783848259584', '1']}
{None: ['576460809027715074', '3']}
{None: ['576460825909089607', '1']}

So i can see csv.reader is what i should have been using

Thanks for the help


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


Catching subprocess stdout stream

2008-09-08 Thread Thomas Jansson
Dear all

I have tkinkter based frontend to a Fortran based program. I use
subprocess to launch the fortran program as a child process and I wish
to see the output of the fortran program as it is created in the
console.

The fortran program can take up to 20 minuttes to finish and at the
moment the I will first see any output after the fortran program is
done. How make my function write the output of the process as it
comes?

def runprogram(Icommand, Ijobfile, Ioutput):
if os.name == "posix":
os.system(pythonpath+"/bin/"+Icommand+"< "+Ijobfile+" | tee
"+Ioutput)
elif os.name == "nt":
import subprocess
ofile = open(Ioutput, 'w')
p = subprocess.Popen([os.path.join(pythonpath, "bin", Icommand
+ '.exe')],
 stdin=open(Ijobfile,
"rb"),bufsize=1024,shell=False,
 stdout=subprocess.PIPE)

while p.poll() is None: #Check if child process has terminated.
o = p.stdout.readline()
ofile.writelines(o)
print o,
ofile.close

Kind regards
Thomas Jansson
--
http://mail.python.org/mailman/listinfo/python-list


Re: Files application architecture

2008-09-08 Thread Benjamin Watine

Bruno Desthuilliers a écrit :

Benjamin Watine a écrit :

Hi,

I'm about to develop a small python application and I wonder how to 
organize files in this application.

I'm familar to java, so I'm tempted to use the same convention


http://dirtsimple.org/2004/12/python-is-not-java.html


: 1 file per class and 1 folders per package.


Don't. This is a waste of time and a pain to maintain, and more over it 
doesn't make any sense since Python doesn't force you to put everything 
in classes.



I know that packages doesn't exists in python,


Did you actually read the doc ? While Python's packages are not the same 
thing as Java's, they do exist.


http://docs.python.org/tut/node8.html#SECTION00840

they are modules instead. May I create specific module for each "group 
of class" ?


The usual way to get cohesive modules is indeed to group closely related 
objects (classes, functions, etc) in a same module.


My application follow the MVC paradigm, so basically, I've a package 
Model, a package View, and a package Controller.


If your app is small, having _modules_ models, views and controllers 
should be enough.


So, what are best practices for organizing files and folders in a 
small python project ?


The best practice is to keep things simple, as usual.



Thank you all for your good advices and links. I'm new to python and I 
have yet a lot of things to learn !


Now, I would like to take a look to a well coded wxPython application. 
Could anybody indicate a project that I could take as reference for 
standard python coding style ?


Regards,

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


Re: Unable to start a process with subprocess Popen()

2008-09-08 Thread aha
On Sep 8, 7:23 am, [EMAIL PROTECTED] wrote:
> On Mon, Sep 8, 2008 at 11:50 AM,  <[EMAIL PROTECTED]> wrote:
> > Hi,
>
> > I'm using the subprocess module's Popen() to start a batch file. This
> > batch file basically calls an exe which also gets started.
> > Unfortunately, this does not produce any results. I looked into the
> > Task bar that this exe has started but it does not consume and cpu so
> > I believet that this exe is not working.
>
> > I used the following command to start the batch fiile:
>
> > testing = subprocess.Popen([batchFilePath], \
> >                                   shell = True, \
> >                                   stdout = subprocess.PIPE, \
> >                                   stderr = subprocess.PIPE).communicate()[0]
>
> > batchFilePath is the path of the batch file.
>
> > --
> > Regrads,
> > Rajat
>
> Ok, I re-phrase my question:
>
> there is a batch file that executes a exe file. The batch just works
> if run from command prompt and produces output to standard output and
> the file.
>
> Now, I try to call the same batch file from subprocess.Pope() call.
> The batch file gets called and that internally also calls the exe
> file.
>
> But, the exe just runs forever i.e. hangs and does not produces output
> , atleast not to the file.
>
> Please suggest is there is something wrong with the above code.
>
> Regards,
> Rajat

Hello Rajat,
  I would take a look at the thread below, it might help it might not:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/4505613f014fdec7/3ee15c9c88a5efdc?hl=en#3ee15c9c88a5efdc

Also, if you post a larger section of the code I might be able to give
you a hand. Once you've run the testing = subprocess.Popen()

make sure you use a testing.wait()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionaries and loops

2008-09-08 Thread Bruno Desthuilliers

Mike P a écrit :

Thanks for the solution above,

The raw data looked like
User-ID,COUNTS
576460840144207854,6
576460821700280307,2
576460783848259584,1
576460809027715074,3
576460825909089607,1
576460817407934470,1

and i used

CSV_INPUT1 = "C:/Example work/Attr_model/Activity_test.csv"
fin1 = open(CSV_INPUT1, "rb")
reader1 = csv.DictReader((fin1), [], delimiter=",")


This should have been:
  reader1 = csv.DictReader(fin1, delimiter=",")

or even just csv.DictReader(fin1), since IIRC ',' is the default 
delimiter (I'll let you check this by yourself...).


with which you would have:
[
  {'User-ID':'576460840144207854', 'count':'6'},
  {'User-ID':'576460821700280307', 'count':'2'},
  # etc...
]

with the following outcome.
{None: ['User-ID', 'COUNTS']}
{None: ['576460840144207854', '6']}
{None: ['576460821700280307', '2']}
{None: ['576460783848259584', '1']}
{None: ['576460809027715074', '3']}
{None: ['576460825909089607', '1']}


And you didn't noticed anything strange ???


So i can see csv.reader is what i should have been using


With only 2 values, DictReader is probably a bit overkill, yes.


Thanks for the help


You're welcome. But do yourself a favour: take time to *learn* Python - 
at least the very basic (no pun) stuff like iterating over a sequence.

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


Re: lacking follow-through

2008-09-08 Thread Eric Wertman
> Perhaps the wrong idea of what the group is.  I would have thought
> that
> if one had a sufficiently developed idea and wanted to have it /
> formally/
> rejected, rather than merely sniped at, then writting a PEP would be
> more
> apposite than posting to c.l.py.
>
> It's fine to post your not sufficiently developed ideas here merely
> to
> have them discussed.  But I don't know what makes you feel that you,
> or
> your ideas, are /entitled/ to any response at all, much less
> "follow-through."


To expand on this a little bit,  I've been subscribed to this group
for a couple of months, but there seems to be a bit more gray area
between what would go to a 'python-dev'  group and a 'python-user'
group.   Long debates about language features and abstract ideas would
appeal to the former, but not the latter.  Certainly I fall into the
user category..  I'm pretty happy with python, and generally just
adjust to it's design and features, rather than spend lots of time on
whether they are 'right' or could be 'better'.  /shrug
--
http://mail.python.org/mailman/listinfo/python-list


Re: lacking follow-through

2008-09-08 Thread Dan Upton
On Sun, Sep 7, 2008 at 10:59 PM, castironpi <[EMAIL PROTECTED]> wrote:
> On Sep 7, 7:34 pm, MRAB <[EMAIL PROTECTED]> wrote:
>> On Sep 7, 11:28 pm, "Eric Wertman" <[EMAIL PROTECTED]> wrote:
>>
>> > +1 Bot
>>
>> I think it's like duck typing: it doesn't matter whether he's actually
>> a bot, only whether he behaves like one.
>
> Do you support the bot interface and methods?
> --

And this is an example of why you get +1 bot.
--
http://mail.python.org/mailman/listinfo/python-list


Trying to make a spider using mechanize

2008-09-08 Thread [EMAIL PROTECTED]
Hi,

I can read the home page using the mechanize lib.  Is there a way to
load in web pages using filename.html instad of servername/
filename.html.  Lots of time the links just have the file name.  I'm
trying to read in the links name and then vsit those pages.

here is the sample code I am ussing.


import ClientForm
import mechanize


#get home page
request = mechanize.Request("http://www.activetechconsulting.com";)
response = mechanize.urlopen(request)
print response.read()

#sub page (this does note work)
request = mechanize.Request("service.html")
response = mechanize.urlopen(request)
print response.read-Ted
--
http://mail.python.org/mailman/listinfo/python-list


Re: Test if list contains another list

2008-09-08 Thread Matimus
On Sep 8, 12:32 am, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> mathieu a écrit :
>
> > Hi there,
>
> >   I am trying to write something very simple to test if a list
> > contains another one:
>
> > a = [1,2,3]
>
> > b = [3,2,1,4]
>
> > but 'a in b' returns False.
>
> Indeed. Lists are not sets, and the fact that all elements of list a
> happens to also be part of list b doesn't make the list a itself an
> element of list b.
>
>  >>> a = [1, 2, 3]
>  >>> b = [3,2,1,4]
>  >>> c = [b, a]
>  >>> a in c
> True
>  >>> b in c
> True
>  >>> c
> [[3, 2, 1, 4], [1, 2, 3]]
>  >>>
>
> > How do I check that a is indeed contained
> > in b ?
>
> But that's what you did - you *did* checked if a was contained in b, and
> this is not the case. What you want is to check if *all elements* of a
> are contained in b, which is quite another problem. Now the answer to
> your question : use sets.
>
>  >>> set(a).issubset(set(b))
> True
>  >>>
>
> HTH

Just to clarify, doing it using sets is not going to preserve order OR
number of elements that are the same.

That is:

>>> a = [1,1,2,3,4]
>>> b = [4,5,3,7,2,6,1]
>>> set(a).issubset(set(b))
True

This will return True if b contains at least on of each element found
in a. If the OP wanted to check that list `a` appeared in order
somewhere in list `b` then sets won't work.

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


Re: Unable to start a process with subprocess Popen()

2008-09-08 Thread dudeja . rajat
On Mon, Sep 8, 2008 at 4:43 PM, aha <[EMAIL PROTECTED]> wrote:
> On Sep 8, 7:23 am, [EMAIL PROTECTED] wrote:
>> On Mon, Sep 8, 2008 at 11:50 AM,  <[EMAIL PROTECTED]> wrote:
>> > Hi,
>>
>> > I'm using the subprocess module's Popen() to start a batch file. This
>> > batch file basically calls an exe which also gets started.
>> > Unfortunately, this does not produce any results. I looked into the
>> > Task bar that this exe has started but it does not consume and cpu so
>> > I believet that this exe is not working.
>>
>> > I used the following command to start the batch fiile:
>>
>> > testing = subprocess.Popen([batchFilePath], \
>> >   shell = True, \
>> >   stdout = subprocess.PIPE, \
>> >   stderr =
subprocess.PIPE).communicate()[0]
>>
>> > batchFilePath is the path of the batch file.
>>
>> > --
>> > Regrads,
>> > Rajat
>>
>> Ok, I re-phrase my question:
>>
>> there is a batch file that executes a exe file. The batch just works
>> if run from command prompt and produces output to standard output and
>> the file.
>>
>> Now, I try to call the same batch file from subprocess.Pope() call.
>> The batch file gets called and that internally also calls the exe
>> file.
>>
>> But, the exe just runs forever i.e. hangs and does not produces output
>> , atleast not to the file.
>>
>> Please suggest is there is something wrong with the above code.
>>
>> Regards,
>> Rajat
>
> Hello Rajat,
>  I would take a look at the thread below, it might help it might not:
>
>
http://groups.google.com/group/comp.lang.python/browse_thread/thread/4505613f014fdec7/3ee15c9c88a5efdc?hl=en#3ee15c9c88a5efdc
>
> Also, if you post a larger section of the code I might be able to give
> you a hand. Once you've run the testing = subprocess.Popen()
>
> make sure you use a testing.wait()
> --
> http://mail.python.org/mailman/listinfo/python-list
>
Hi Aaquil,

Thanks for helping me out with this piece of information.
My Original code is :

testing = subprocess.Popen([batchFilePath], \
   shell = True, \
   stdout = subprocess.PIPE, \
   stderr = subprocess.PIPE)

result = testing.wait()

if result < 0:
childError = testing.stderr.read()
tkMessageBox._show("Error", \
   icon='error', \
   message ="Error: %s" % childError)
return None

else:
print result
My child process was unresponsive. Later I got to know with the below code
that there were some errors coming from the child process which I was not
able to detect with this code.

I googled for some solution and found the below code :-

print "ttt", batchFilePath
   #print os.listdir(batchFilePath)
   try:
   cmd = subprocess.Popen([batchFilePath], \
  shell = True, \
  stdin = subprocess.PIPE,
  stdout = subprocess.PIPE, \
  stderr = subprocess.PIPE \
  )
   cmd.stdin.close()
   outPipe, errPipe = PipeThread(cmd.stdout), PipeThread(cmd.stderr)

   outPipe.run(), errPipe.run()
   retcode = cmd.wait()
   out, err = outPipe.getOutput(), errPipe.getOutput()
   if retcode != 0 and err != '':
   raise ExecutionFailed, os.path.basename(batchFilePath) + "
exited with error code " + str(retcode) + " and errors:\n" + err
   elif retcode != 0:
   raise ExecutionFailed, os.path.basename(batchFilePath) + "
exited with error code " + str(retcode) + " and output:\n" + out
   elif err != '':
   return out + "\n" + os.path.basename(batchFilePath) + " gave
warnings:\n" + err
   else:
   return out
   except Exception, e:
   if isinstance(e, ExecutionFailed):
   raise
   else:
   raise ExecutionFailed, "Error while executing " +  ":\n" +
str(e)
   Here are the Exception  and the PipeThread Classes:

class PipeThread(threading.Thread):
def __init__(self, fin):
self.fin = fin
self.sout = ""
threading.Thread.__init__(self)
def run(self):
self.sout = self.fin.read()
def getOutput(self):
return self.sout

class ExecutionFailed(Exception):
def __init__(self, value):
self.parameter = value
def __str__(self):
return str(self.parameter)

Although, this solved my problem. But I know there is no need for using
threading in this problem. This problem could've been solved just by the
subprocess module.

I'm unnecessarily using the threading module.

Regards,
Rajat





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

Calling Common Lisp Game Developers

2008-09-08 Thread jobs
We are currently seeking talented Lisp Game Developers who are
passionate about game development and want to play a major role in
developing and maintaining new features for one of our persistent
browser games.

This particular title uses Hunchentoot, but all other code has been
developed in house using the Mnesia database for persistence. This
particular game is not released yet but has already generated interest
from over 35,000 players globally.

If you’re interested in developing Persistent Browser Games using SBCL
and want to know more then send us an email at [EMAIL PROTECTED]

The preferred location for this role is in Dublin, Ireland but we are
also open to hearing from anyone who prefers to work remotely.

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


Calling Common Lisp Game Developers

2008-09-08 Thread jobs
We are currently seeking talented Lisp Game Developers who are
passionate about game development and want to play a major role in
developing and maintaining new features for one of our persistent
browser games.

This particular title uses Hunchentoot, but all other code has been
developed in house using the Mnesia database for persistence. This
particular game is not released yet but has already generated interest
from over 35,000 players globally.

If you’re interested in developing Persistent Browser Games using SBCL
and want to know more then send us an email at [EMAIL PROTECTED]

The preferred location for this role is in Dublin, Ireland but we are
also open to hearing from anyone who prefers to work remotely.

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


Problems downloading and installing win32api

2008-09-08 Thread brianrpsgt1
I have attempted downloading and installing several different version
of the win32api from Source Forge, however, each time I try to install
I get the following error message:

"Only part of a ReadProcessMemory or WriteProcessMemory request was
completed"

This occurred with the following files:
pywin32-212.win32-py2.4.exe
pywin32-212.win32-py2.5.exe
pywin32-212.win32-py2.6.exe

I am using WinXP SP2.  Any assistance on getting this downloaded and
installed would be great.

Thanks

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


Re: Read and write binary data

2008-09-08 Thread Kurt Smith
On Sun, Sep 7, 2008 at 5:41 PM, Mars creature <[EMAIL PROTECTED]> wrote:
> Hi guys,
>  I am new to Python, and thinking about migrating to it from matlab
> as it is a really cool language. Right now, I am trying to figure out

If you're trying to migrate from matlab to python I'd take a look at numpy:

http://numpy.scipy.org/

And scipy which is built on top of numpy:

http://www.scipy.org/

There is a plotting/numerical computation package known as matplotlib
that does its best to parallel matlab commands:

http://matplotlib.sourceforge.net/

There is support for reading and writing binary data, even fortran records.

And last but not least, you can always take a look at the scipy and
numpy mailing lists.

Good luck,

Kurt

> how to control read and write binary data, like
> 'formatted','stream','big-endian','little-edian' etc.. as in fortran.
> I googled, but can not find a clear answer. Anyone has clue where can
> I learn it? Thanks!!
> Jinbo
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python

2008-09-08 Thread James Matthews
I like two 1. www.diveintopython.com and 2. Core Python Programming.

On Mon, Sep 8, 2008 at 6:15 AM, Alan G Isaac <[EMAIL PROTECTED]> wrote:

> On 9/6/2008 5:17 AM James Pilling apparently wrote:
>
>> Hi im currently starting to learn python in sixth form at school any tips?
>>
>
> The books suggestions of others are quite good.
> Here is another approach: pick an easily understandable
> application, and work doing things with it.
>
> Perhaps immodestly, I think that as soon as you
> understand how to define a function and a class,
> you can treat this paper
> http://jasss.soc.surrey.ac.uk/11/3/8.html
> as an introduction to applied Python programming.
> The application area is very specific---game theoretic
> simulations---but the illustrated techniques are
> meant to be more general.
>
> Alan Isaac
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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

Re: universal unicode font for reportlab

2008-09-08 Thread Laszlo Nagy

Iain Dalton wrote:

Why don't you want to use multiple typefaces?  Many programs that deal
with multilingual strings use multiple fonts (cf. any Web browser and
Emacs).
  
You are right, but these PDF documents will show mixed strings. The end 
user can enter arbitrary strings into the database, and they must be 
presented. For example, the name of a product can be arabic or german. 
It might be possible to guess the language used from the unicode string, 
and then select a different font. But I don't want to go into that trouble.


It would be a great idea to use pango. Apparently pango is able to 
change fonts on the fly and render the requested glyph. However, if I 
use pango then I loose the much higher level of abstraction that comes 
with reportlab and platypus: I need automatic page headers and footers, 
I need to be able to repeat table headers on each page automatically 
(when the table doesn't fit one page) etc. Developing my own "platypus" 
like engine for pango and PDF rendering is a nightmare.


Better than that, I can develop my own flowable object for platypus: a 
special paragraph that changes the used true type font on the fly. 
(Split input string into parts, determine language for the parts and 
display each part with its own font.) But of course this is a lot of 
extra programming.


The simplest solution would be to use a font that is able to handle all 
encodings that I need.


Thanks,

Laszlo

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


shelve file name extention

2008-09-08 Thread Monu
Hi All,
When I am using shelve on my local machine it generates the db file as
given filename. But in another machine it's generating .dat
and .dir.
can anyone tell me how can I force sheve module to write the db in
.dir and .dat, instead of ? Do I have to
install a specific version of the python?

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


Re: Read and write binary data

2008-09-08 Thread Mohamed Yousef
I don't know if this is going to help you
but a free&open alternative to Matlap is FreeMat just search for it
--
http://mail.python.org/mailman/listinfo/python-list


Re: shelve file name extention

2008-09-08 Thread skip

Monu> When I am using shelve on my local machine it generates the db
Monu> file as given filename. But in another machine it's generating
Monu> .dat and .dir.  can anyone tell me how can I force sheve
Monu> module to write the db in .dir and .dat,
Monu> instead of ? Do I have to install a specific version of
Monu> the python?

Shelve is just a thin layer on top of a concrete db file module.  Sounds
like on your two machines there are different underlying db file modules
available.  You're pretty much at the mercy of those modules as to file
naming.  All you are giving it when opening a shelve file is the prefix.

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


Re: [ANN] pysqlite 2.5.0 released

2008-09-08 Thread Petite Abeille


On Sep 8, 2008, at 1:56 PM, Gerhard Häring wrote:

But AFAIK it's possible to compile a custom SQLite with appropriate  
flags to ./configure that will include the fulltext search extension.


It's indeed rather straightforward to integrate FTS, e.g.:

% CFLAGS="-DSQLITE_ENABLE_FTS3=1" ./configure
% sudo make install

"Full-Text Search on SQLite"
http://blog.michaeltrier.com/tags/fts

Here is an example of FTS at work:

http://svr225.stepx.com:3388/search?q=chicago

Cheers,

--
PA.
http://alt.textdrive.com/nanoki/

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


exit()

2008-09-08 Thread Gary Robinson
In Python 2.5.2, I notice that, in the interpreter or in a script, I can exit 
with:

exit()

But I don't see exit() mentioned as a built-in function; rather the Python 
Library Reference says we should use sys.exit(). Also, the reference says 
sys.exit() is like raising SystemExit. But so is just calling exit(). For 
instance,

exit('some error message')

has the same apparent effect as 

raise SystemExit, 'some error message'.

Both return a status code of 1 and print the error string on the console.

Is exit() documented somewhere I haven't been able to find? Is there any reason 
to use sys.exit() given exit()'s availability?

If there is an advantage to sys.exit() over exit(), then does sys.exit() have 
any advantage over "raise SystemExit, 'some error message'" in cases where a 
module has no other reason to import sys?

-- 

Gary Robinson
CTO
Emergent Music, LLC
personal email: [EMAIL PROTECTED]
work email: [EMAIL PROTECTED]
Company: http://www.emergentmusic.com
Blog:http://www.garyrobinson.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: exit()

2008-09-08 Thread Christian Heimes

Gary Robinson wrote:

In Python 2.5.2, I notice that, in the interpreter or in a script, I can exit 
with:

exit()


The exit callable is defined in the site module. Check out site.py! It 
shouldn't be used in code. It was added to help newbies to 'escape' from 
an interactive Python shell.


Christian

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


Re: lacking follow-through

2008-09-08 Thread Chris Rebert
On Mon, Sep 8, 2008 at 9:03 AM, Eric Wertman <[EMAIL PROTECTED]> wrote:
>> Perhaps the wrong idea of what the group is.  I would have thought
>> that
>> if one had a sufficiently developed idea and wanted to have it /
>> formally/
>> rejected, rather than merely sniped at, then writting a PEP would be
>> more
>> apposite than posting to c.l.py.
>>
>> It's fine to post your not sufficiently developed ideas here merely
>> to
>> have them discussed.  But I don't know what makes you feel that you,
>> or
>> your ideas, are /entitled/ to any response at all, much less
>> "follow-through."
>
>
> To expand on this a little bit,  I've been subscribed to this group
> for a couple of months, but there seems to be a bit more gray area
> between what would go to a 'python-dev'  group and a 'python-user'
> group.   Long debates about language features and abstract ideas would
> appeal to the former, but not the latter.  Certainly I fall into the
> user category..  I'm pretty happy with python, and generally just
> adjust to it's design and features, rather than spend lots of time on
> whether they are 'right' or could be 'better'.  /shrug

Yeah, suggestions about changing the language are much better suited
to the more-specific Python-ideas or Python-3000 mailinglists than the
general-purpose c.l.p
- Chris

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

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: exit()

2008-09-08 Thread Jean-Paul Calderone

On Mon, 08 Sep 2008 21:03:48 +0200, Christian Heimes <[EMAIL PROTECTED]> wrote:

Gary Robinson wrote:
In Python 2.5.2, I notice that, in the interpreter or in a script, I can 
exit with:


exit()


The exit callable is defined in the site module. Check out site.py! It 
shouldn't be used in code. It was added to help newbies to 'escape' from an 
interactive Python shell.




It works.  Why shouldn't it be used?

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


Re: max(), sum(), next()

2008-09-08 Thread castironpi
On Sep 8, 8:54 am, Boris Borcic <[EMAIL PROTECTED]> wrote:
> David C. Ullrich wrote:
>
> > (ii) If A is a subset of B then we should have
> > max(A) <= max(B). This requires that max(empty set)
> > be something that's smaller than everything else.
> > So we give up on that.
>
> Er, what about instances of variations/elaborations on
>
> class Smaller(object) : __cmp__ = lambda *_ : -1
>
> ?
>
> Cheers, BB

You still don't have the property max(X) is in X.

And it's the equivalent of a special builtin constant for max on the
empty set.
--
http://mail.python.org/mailman/listinfo/python-list


Re: lacking follow-through

2008-09-08 Thread castironpi
On Sep 8, 11:23 am, "Dan Upton" <[EMAIL PROTECTED]> wrote:
> On Sun, Sep 7, 2008 at 10:59 PM, castironpi <[EMAIL PROTECTED]> wrote:
> > On Sep 7, 7:34 pm, MRAB <[EMAIL PROTECTED]> wrote:
> >> On Sep 7, 11:28 pm, "Eric Wertman" <[EMAIL PROTECTED]> wrote:
>
> >> > +1 Bot
>
> >> I think it's like duck typing: it doesn't matter whether he's actually
> >> a bot, only whether he behaves like one.
>
> > Do you support the bot interface and methods?
> > --
>
> And this is an example of why you get +1 bot.

I took Eric's comment to be a joke and mine was too.  I don't get the
feeling yours is, no offense.
--
http://mail.python.org/mailman/listinfo/python-list


Re: lacking follow-through

2008-09-08 Thread castironpi
On Sep 8, 2:04 pm, "Chris Rebert" <[EMAIL PROTECTED]> wrote:
> On Mon, Sep 8, 2008 at 9:03 AM, Eric Wertman <[EMAIL PROTECTED]> wrote:
> >> Perhaps the wrong idea of what the group is.  I would have thought
> >> that
> >> if one had a sufficiently developed idea and wanted to have it /
> >> formally/
> >> rejected, rather than merely sniped at, then writting a PEP would be
> >> more
> >> apposite than posting to c.l.py.
>
> >> It's fine to post your not sufficiently developed ideas here merely
> >> to
> >> have them discussed.  But I don't know what makes you feel that you,
> >> or
> >> your ideas, are /entitled/ to any response at all, much less
> >> "follow-through."
>
> > To expand on this a little bit,  I've been subscribed to this group
> > for a couple of months, but there seems to be a bit more gray area
> > between what would go to a 'python-dev'  group and a 'python-user'
> > group.   Long debates about language features and abstract ideas would
> > appeal to the former, but not the latter.  Certainly I fall into the
> > user category..  I'm pretty happy with python, and generally just
> > adjust to it's design and features, rather than spend lots of time on
> > whether they are 'right' or could be 'better'.  /shrug
>
> Yeah, suggestions about changing the language are much better suited
> to the more-specific Python-ideas or Python-3000 mailinglists than the
> general-purpose c.l.p
> - Chris
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> --
> Follow the path of the Iguana...http://rebertia.com

Some of the core devs from Python-Ideas have suggested that I get some
of my ideas started on c.l.py.  Also, I'm looking for people to
connect with and interact with about Python and none of the core devs
have time, which makes c.l.py the place.  I'm starting to get
discouraged, as though there's no one really interested in this cool
thing I'm thinking of.  Or did I just not describe it well?  It would
be safe to assume that people read my post, understood it, and weren't
interested, except that a few replies came, and then it was dropped
without any obvious explanation.

Further, and I'm sad to report this, I found tempers really high
strung on the Ideas list, so c.l.py may have more potential anyway,
with more young and flexible users.  Not to say that the core devs are
old or brittle or anything, just that their time is already devoted
and they don't have time for people like me.

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


Re: lacking follow-through

2008-09-08 Thread Grant Edwards
On 2008-09-08, Chris Rebert <[EMAIL PROTECTED]> wrote:
> On Mon, Sep 8, 2008 at 9:03 AM, Eric Wertman <[EMAIL PROTECTED]> wrote:
>
>> To expand on this a little bit, I've been subscribed to this
>> group for a couple of months, but there seems to be a bit more
>> gray area between what would go to a 'python-dev' group and a
>> 'python-user' group.  Long debates about language features and
>> abstract ideas would appeal to the former, but not the latter.
>> Certainly I fall into the user category..  I'm pretty happy
>> with python, and generally just adjust to it's design and
>> features, rather than spend lots of time on whether they are
>> 'right' or could be 'better'.  /shrug
>
> Yeah, suggestions about changing the language are much better
> suited to the more-specific Python-ideas or Python-3000
> mailinglists than the general-purpose c.l.p

I don't think anybody here in c.l.p minds reading suggestions
for language features/changes, but often what the poster in
question writes is just an incomprehensible collection of
vaguely philosophical-sounding metaphores and similes
reminiscent of a hoax paper submitted as a joke to a
post-modern "journal" of some pretend science or other.

-- 
Grant Edwards   grante Yow! Used staples are good
  at   with SOY SAUCE!
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to run PyOS_InputHook from python code (i.e. yield to event loops)

2008-09-08 Thread Sean DiZazzo
On Sep 6, 1:00 pm, [EMAIL PROTECTED] (Ville M. Vainio) wrote:
> Background: PyOS_InputHook is something that gets run when python is
> doing raw_input. TkInter and friends use it to run their event loops,
> so that their events are handled while python is doing raw_input.
>
> What I'd like to do is run the same function without having to do
> raw_input. I.e. I'd like to run whatever event loop is available,
> without incorporating any gui-specific code (PyOS_InputHook seems like
> a nifty way to accomplish this).
>
> My actual use case is to keep a tkinter application responsive while
> launching a background process (and waiting for it to complete!).
>
> My eventual code would be something like:
>
> launch_process_in_thread('bzr pull')
>
> while not is_done:
>   pyos_inputhook()
>   time.sleep(0.1)
>
> print "Done!"

I'm still recovering from a hangover, so don't quote me.  I think you
want the "after" function:

launch_process_in_thread('bzr pull')
self.update()

def update(self):
while not self.is_done:
self.after(2000, self.update)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems downloading and installing win32api

2008-09-08 Thread Emile van Sebille

brianrpsgt1 wrote:

I have attempted downloading and installing several different version
of the win32api from Source Forge,


Whe win32 tools come bundled with ActiveState's python distribution.

Maybe that'll move you forward...

Emile


 however, each time I try to install

I get the following error message:

"Only part of a ReadProcessMemory or WriteProcessMemory request was
completed"

This occurred with the following files:
pywin32-212.win32-py2.4.exe
pywin32-212.win32-py2.5.exe
pywin32-212.win32-py2.6.exe

I am using WinXP SP2.  Any assistance on getting this downloaded and
installed would be great.

Thanks

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



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


finding the parent class (not superclass) of the currently executing method derived from a Borg class

2008-09-08 Thread seanacais
I want to create a class derived from a Borg class that can
instantiated as part of a script or be contained in other classes.
When methods from the Borg class are called, I would  like to know the
name of the class that contains the Borg class.

I've played a bit with inspect and _getframe from the sys module but
get inconsistent results.  The main problem is if the Borg class is
instantiated outside a containing class, then I need to go up a
different number of stack frames.  But this information isn't
available till after I've run out of stack frames.

Hopefully the following code better describes what I'm looking to do.

import sys

class Borg:
_shared_state = {}
def __init__(self):
self.__dict__=self._shared_state

class Assimilated(Borg):
valueByCaller = {}

def __init__(self, setupvalue):
print "In Assimilated.__init__()"
print "setupvalue is: " + str(setupvalue)

# would like  key to  be name of class (or module) that
# contins Assimilated
callerID =  sys._getframe(1).f_code.co_name

self.valueByCaller[callerID] =  setupvalue

print self.valueByCaller

def action(self, calledvalue):
print "In Assimilated.action()"
print "self.__classname__: " + self.__class__.__name__
print "calledvalue is: " + str(calledvalue)

print "self.valueByCaller"
print self.valueByCaller

# need to get proper key depending on which class (or module)
# made the call
#print "0: " + sys._getframe(0).f_code.co_name
#print "1: " + sys._getframe(1).f_code.co_name
#print "2: " + sys._getframe(2).f_code.co_name
#print "3: " + sys._getframe(3).f_code.co_name
callerID =  sys._getframe(2).f_code.co_name
print "callerID"
print callerID

if(self.valueByCaller[callerID] <= calledvalue):
print "doing the action"


class A:
assim_object = Assimilated(2)

def __init__(self):
self.assim_object.action(2)
self.assim_object.action(3)

class B:
assim_object = Assimilated(3)

def __init__(self):
self.assim_object.action(3)
self.assim_object.action(4)

class C:
assim_object = Assimilated(4)

def __init__(self):
self.assim_object.action(4)
self.assim_object.action(5)


a=A()
b=B()
c=C()

obj=Assimilated(3)
#obj.action(3)


When I run this, I get the following output:

In Assimilated.__init__()
setupvalue is: 2
{'A': 2}
In Assimilated.__init__()
setupvalue is: 3
{'A': 2, 'B': 3}
In Assimilated.__init__()
setupvalue is: 4
{'A': 2, 'C': 4, 'B': 3}
In Assimilated.action()
self.__classname__: Assimilated
calledvalue is: 2
self.valueByCaller
{'A': 2, 'C': 4, 'B': 3}
callerID

Traceback (most recent call last):
  File "\CallerID.py", line 67, in 
a=A()
  File "\CallerID.py", line 49, in __init__
self.assim_object.action(2)
  File "\CallerID.py", line 41, in action
if(self.valueByCaller[callerID] <= calledvalue):
KeyError: ''

What I found most peculiar when I started this was that the
valueByCaller dictionary was completely populated before the __init__
method of a was executed.  I'm pretty sure that this has to do with
the difference between when the object gets instanced and when it gets
initialized, but I need to do some more research and reading to be
able to explain it to myself.

Thanks for any help you can give me.

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


Re: Updating python dictionary

2008-09-08 Thread [EMAIL PROTECTED]
On Sep 8, 10:20 am, John Machin <[EMAIL PROTECTED]> wrote:
> On Sep 8, 10:47 am, MK Bernard <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Sep 7, 3:37 pm, John Machin <[EMAIL PROTECTED]> wrote:
>
> > > On Sep 8, 7:51 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
> > > > Hello...
>
> > > > I have a dict of key/values and I want to change the keys in it, based
> > > > on another mapping dictionary. An example follows:
>
> > > > MAPPING_DICT = {
> > > >     'a': 'A',
> > > >     'b': 'B',
>
> > > > }
>
> > > > my_dict = {
> > > >     'a': '1',
> > > >     'b': '2'
>
> > > > }
>
> > > > I want the finished my_dict to look like:
>
> > > > my_dict = {
> > > >     'A': '1',
> > > >     'B': '2'
>
> > > > }
>
> > > > Whereby the keys in the original my_dict have been swapped out for the
> > > > keys mapped in MAPPING_DICT.
>
> > > > Is there a clever way to do this, or should I loop through both,
> > > > essentially creating a brand new dict?
>
> > > Is this homework?
>
> > > There seems to be an implicit assumption in the answers so far that
> > > your mapping is a 1:1 mapping of all possible input keys.
>
> > > If it doesn't include all possible input keys, answers will crash with
> > > a KeyError. If there are any many:1 elements in the mapping (for
> > > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code
> > > in some checks for this.
>
> > Thats exactly why I did an explicit check in my post, so as to make
> > sure that such a collision could not occur. It would seem that
> > something along what I posted would be safer, if less elegant, than
> > the others.
>
> I noted two problems:
> (1) not covering all input keys: your code explicitly sweeps this
> problem under the carpet, and does it laboriously ...
>     if x in my_dict.keys():
> instead of
>     if x in my_dict:
> (2) not a 1:1 mapping -- for example, 'a' and 'b' both map to 'A' (the
> only "collision" that I can see), but you don't address that.
>
> Here's some code which attempts to cover the bases:
>
> new_dict = {}
> for key in my_dict:
>     if key not in MAPPING_DICT:
>         raise NoMapError('blah %r' % key)
>     else:
>         new_key = MAPPING_DICT[key]
>     if new_key in new_dict:
>         raise ManyToOneError('gurgle %r waffle %r' % (key, new_key))
>     else:
>         new_dict[new_key] = my_dict[key]
>
> Having considered what is actually required under the checked-for
> conditions, one or both raise statements may be replaced by other
> code, and then simplified e.g. the first 4 lines in the loop may end
> up being replaced by
>     new_key = MAPPING_DICT.get(key, key)
> as already suggested by one respondent.
>
> Note that useful use-cases for any variety of this key-change exercise
> may have many more items in MAPPING_DICT than there are in my_dict (a
> big language dictionary and a few fragments of text to be
> "translated"), or vice versa (a small synonym dictionary (color ->
> colour, center -> centre) and a big input to be "standardised") so
> it's a good idea to inquire which is likely to be the smaller and
> iterate over that if the requirements permit it.

In the interests of academia (although this isn't homework :)) I'll
answer some of those questions:

- Yes, the mapping dict doesn't necessarily have the same number of
entries as the my_dict. It may have less than it or more than it.
- There will never be dupes of key or value in the mapping. Though
there maybe in my_dict.

And, for extra credit, it may be useful to be able to 'translate' the
my_dict back again using the same mapping_dict. ie, using the values
in mapping dict as the new keys in my_dict, and the keys as the new
values.

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


Re: lacking follow-through

2008-09-08 Thread Terry Reedy



Chris Rebert wrote:

On Mon, Sep 8, 2008 at 9:03 AM, Eric Wertman <[EMAIL PROTECTED]> wrote:



To expand on this a little bit,  I've been subscribed to this group
for a couple of months, but there seems to be a bit more gray area
between what would go to a 'python-dev'  group and a 'python-user'
group.   Long debates about language features and abstract ideas would
appeal to the former, but not the latter.


The py-dev mailing list, and its gmane.comp.python.devel mirror, is for 
concrete discussion, mostly by developers, of how to develop the current 
and next release.  The current focus in on finishing 2.6 for release.


Almost nothing that has appeared here recently belongs there.  It is 
much more common for people to post there usage questions that belong 
here or speculative issues that could also go to python-ideas.


>>  Certainly I fall into the

user category..  I'm pretty happy with python, and generally just
adjust to it's design and features, rather than spend lots of time on
whether they are 'right' or could be 'better'.  /shrug


Long rehashes of decided issues, like the name of subprocess.popen, or 
the default of sum(), belong here better than anywhere else, if anywhere 
;-).



Yeah, suggestions about changing the language are much better suited
to the more-specific Python-ideas or Python-3000 mailinglists than the
general-purpose c.l.p


The Python-3000 mailing list, and the gmane.comp.python.python-3.devel 
mirror, is the py-dev equivalent for python3-specific issues.


tjr



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


Re: universal unicode font for reportlab

2008-09-08 Thread Terry Reedy


The simplest solution would be to use a font that is able to handle all 
encodings that I need.


My OpenOffice on WinXP uses a unicode font, I believe Lucida Sans 
Unicode, that seems to cover the entire BMP.  I don't know whether it 
was already installed or installed by OO or how one would get to it to 
extract it.


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


Re: hashing an array - howto

2008-09-08 Thread Robert Kern

[EMAIL PROTECTED] wrote:

John Machin:

Consider this:>>> hash(123) == hash(123.0) == hash(123L)
True


Right... Can you explain me why Python designers have chosen to build
a hash() like that?


Because that's the kind of hash that dicts expect. If two objects are equal 
(i.e. (x==y) is True), they need to have their hash values equal as well. In 
order to do a lookup into a dict, it will hash the key and search the table for 
a that hash value. If there are multiple keys with the same hash value, then the 
dict will compare the keys by value to find a match. Since (123==123.0==123L), 
they must also have the same hash value such that


  {123.0: 'got it'}[123] == 'got it'

--
Robert Kern

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

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


Re: Where does the command "ls" in some doctest files come from ?

2008-09-08 Thread Terry Reedy



KLEIN Stéphane wrote:

Hi,

for example, in http://svn.zope.org/zc.buildout/trunk/src/zc/buildout/
tests.py?rev=89831&view=auto test file, there is this doctests :

def develop_verbose():
"""
We should be able to deal with setup scripts that aren't setuptools based.

>>> mkdir('foo')
>>> write('foo', 'setup.py',
... '''
... from setuptools import setup
... setup(name="foo")
... ''')

>>> write('buildout.cfg',
... '''
... [buildout]
... develop = foo
... parts = 
... ''')


>>> print system(join('bin', 'buildout')+' -vv'), # doctest: +ELLIPSIS
Installing...
Develop: '/sample-buildout/foo'
...
Installed /sample-buildout/foo
...

>>> ls('develop-eggs')
-  foo.egg-link
-  zc.recipe.egg.egg-link

>>> print system(join('bin', 'buildout')+' -vvv'), # doctest: 
+ELLIPSIS

Installing...
Develop: '/sample-buildout/foo'
in: '/sample-buildout/foo'
... -q develop -mxN -d /sample-buildout/develop-eggs/...


"""

I wonder where does the "ls('develop-eggs')" command come from ?


'ls' is the unix abbreviation for the shell command 'list files (in a 
directory)'.  The name is used above for a similar Python function.  It 
presumably was imported somewhere before develop_verbose, or else is 
part of the auto-imported site.py for a development site.


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


The difference between __XX__ and XX method

2008-09-08 Thread AON LAZIO
Hi, Pythoners.
  I would like to know that in some class, it uses __XX__ but in some it
uses only XX
for example,

class Test:
def __som__(self):
  ...
def som(self):
  ...
   What does "__XX__" make the method different from XX?
   Thanks in advance
Aonlazio
--
http://mail.python.org/mailman/listinfo/python-list

Re: exit()

2008-09-08 Thread nntpman68

Hi Jean-Paul,

Jean-Paul Calderone wrote:
On Mon, 08 Sep 2008 21:03:48 +0200, Christian Heimes <[EMAIL PROTECTED]> 
wrote:

Gary Robinson wrote:
In Python 2.5.2, I notice that, in the interpreter or in a script, I 
can exit with:


exit()


The exit callable is defined in the site module. Check out site.py! It 
shouldn't be used in code. It was added to help newbies to 'escape' 
from an interactive Python shell.




It works.  Why shouldn't it be used?

Jean-Paul


Backwards compatibility vs. saving 4 characters.


I'd stick with backwards compatibility

bye


N

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


class(object) and (type)??

2008-09-08 Thread AON LAZIO
Hi again pythoners,
 I notice in the class of a code having (object) and (type) attached to
the name of the class.
I know that in other cases, that means the class inherits methods and
properties from other but
In this case, what does it mean?
For example,

class PY(object):
def __init__(self):
...

class PO(type):
 def __init__(self):
 ...
 What do "object" and "type" mean?

Thanks in advance

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

Re: The difference between __XX__ and XX method

2008-09-08 Thread James Mills
Hi,

This is convention only
and typically used to denote
that a particular class attribute
is "private". Though note,
there is really no such thing in
Python.

cheers
James

On Tue, Sep 9, 2008 at 7:31 AM, AON LAZIO <[EMAIL PROTECTED]> wrote:
> Hi, Pythoners.
>   I would like to know that in some class, it uses __XX__ but in some it
> uses only XX
> for example,
>
> class Test:
> def __som__(self):
>   ...
> def som(self):
>   ...
>What does "__XX__" make the method different from XX?
>Thanks in advance
> Aonlazio
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to make a spider using mechanize

2008-09-08 Thread James Mills
Hi,

Perhaps you might want to
try out using a sample spider
I wrote and base your code of
this ?

See: 
http://hg.shortcircuit.net.au/index.wsgi/pymills/file/b9936ae2525c/examples/spider.py

cheers
James

On Tue, Sep 9, 2008 at 2:24 AM, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I can read the home page using the mechanize lib.  Is there a way to
> load in web pages using filename.html instad of servername/
> filename.html.  Lots of time the links just have the file name.  I'm
> trying to read in the links name and then vsit those pages.
>
> here is the sample code I am ussing.
>
>
> import ClientForm
> import mechanize
>
>
> #get home page
> request = mechanize.Request("http://www.activetechconsulting.com";)
> response = mechanize.urlopen(request)
> print response.read()
>
> #sub page (this does note work)
> request = mechanize.Request("service.html")
> response = mechanize.urlopen(request)
> print response.read-Ted
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: The difference between __XX__ and XX method

2008-09-08 Thread Christian Heimes

AON LAZIO wrote:

Hi, Pythoners.
  I would like to know that in some class, it uses __XX__ but in some it
uses only XX
for example,

class Test:
def __som__(self):
  ...
def som(self):
  ...
   What does "__XX__" make the method different from XX?
   Thanks in advance


The form __method__ is reserved for internal methods also known as magic 
methods. In general you must not name your own methods or attributes 
__XX__ because the core of Python reserves all rights on the __*__ 
naming schema.


Some well know magic methods are __init__, __getattr__, __add__ etc. You 
can find a complete lists in the Python language reference.


Christian

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


F2PY ?? Has anyone worked with the F2PY generator?

2008-09-08 Thread Blubaugh, David A.
To All,


Has anyone worked with the F2PY generator?  This is something that is
supposedly built within numpy and scipy for the Python environment.  I
was wondering if anyone has encountered any issues with this
environment??  This is important to find the answers to these questions.



Thanks,


David Blubaugh



This e-mail transmission contains information that is confidential and may be 
privileged. It is intended only for the addressee(s) named above. If you 
receive 
this e-mail in error, please do not read, copy or disseminate it in any manner. 
If you are not the intended recipient, any disclosure, copying, distribution or 
use of the contents of this information is prohibited. Please reply to the 
message immediately by informing the sender that the message was misdirected. 
After replying, please erase it from your computer system. Your assistance in 
correcting this error is appreciated.

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


Re: Where does the command "ls" in some doctest files come from ?

2008-09-08 Thread KLEIN Stéphane
Le Mon, 08 Sep 2008 12:51:04 +, Steven D'Aprano a écrit :

> On Mon, 08 Sep 2008 12:15:15 +, KLEIN Stéphane wrote:
> 
>> Hi,
>> 
>> for example, in http://svn.zope.org/zc.buildout/trunk/src/zc/buildout/
>> tests.py?rev=89831&view=auto test file, there is this doctests :
> 
> [snip]
> 
>> >>> ls('develop-eggs')
> 
> 
>> I wonder where does the "ls('develop-eggs')" command come from ?
>> 
>> It is doctest buildin command ?
> 
> Easy to find out: import doctest and see for yourself:
> 
 import doctest
 doctest.ls
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'module' object has no attribute 'ls'
> 
> You found the ls() function in a docstring from Zope. The doctest seems
> to be testing ls(). That suggests to me that ls() is defined in Zope,
> not doctest.

Well, ls() is one test utility function defined in zc.buildout.testing 
module. This module contain many utility function like mkdir, ls, cat...

 
> Why do you ask?

I'm curious... I've seen this utility and I would like to know how can I 
use it.

Regards,
Stephane

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

Re: class(object) and (type)??

2008-09-08 Thread Chris Rebert
Subclassing 'object' makes the class new-style as opposed to
old-style. object is the ultimate superclass of all new-style classes.
Old-style classes are deprecated and will be removed in Python 3.0,
but they're currently the default for backward-compatibility reasons.
See http://docs.python.org/ref/node33.html for more info.

- Chris

On Mon, Sep 8, 2008 at 2:35 PM, AON LAZIO <[EMAIL PROTECTED]> wrote:
> Hi again pythoners,
>  I notice in the class of a code having (object) and (type) attached to
> the name of the class.
> I know that in other cases, that means the class inherits methods and
> properties from other but
> In this case, what does it mean?
> For example,
>
> class PY(object):
> def __init__(self):
> ...
>
> class PO(type):
>  def __init__(self):
>  ...
>  What do "object" and "type" mean?
>
> Thanks in advance
>
> Aonlazio
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric literal syntax

2008-09-08 Thread Tom Harris
On Thu, Sep 4, 2008 at 10:22 AM, Alexander Schmolck
<[EMAIL PROTECTED]> wrote:
>
> It's amazing that after over half a century of computing we still can't denote
> numbers with more than 4 digits readably in the vast majority of contexts.
>

I agree. So did Forth's early designers. That is why Forth's number
parser considers a word that starts with a number and has embedded
punctuation to be a 32 bit integer, and simply ignores the
punctuation. I haven't used Forth in years, but it seems a neat
solution to the problem of decoding a long string of numbers: let the
user put in whatever they want, the parser ignores it. I usually used
a comma (with no surrounding whitespace of course), but it was your
choice. You could also do this in whatever base you were working in,
so you could punctuate a 32 bit hex number to correspond to the bit
fields inside it. Of course not applicable to Python.

-- 

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


Re: wxPython problem

2008-09-08 Thread Paul Probert

Peter Anderson wrote:
Stef Mientki said: In PyScripter, you should run wxPython in the plain 
remote machine (not the wxPython remote),and you should set "reset 
before run flag" or reset the remote machine each time yourself.


Stef,

Thanks for the help! It has taken several hours to find and install the 
correct version of Rpyc (which is required to run the remote Python 
engine but it now seems to be working fine. And the "Reinitialise the 
Python engine {Alt]+[F2]" does need to be done between script runs. 
Given all that, the script now runs multiple times in PyScripter. The 
script still only runs ONCE in IDLE but I can live with that.


In case others find this message from a search; I am using Python 2.5.2 
and it requires rpyc-2.60.zip from the Rpyc download page (see 
http://rpyc.wikispaces.com/ click on the "Download" link and make sure 
you select the "main" link under the "Packages" column at Sourceforge. 
You will be shown a list of Rpyc versions. For Python 2.5.2 choose 
Relese "2.60". This will save you the several hours its cost me.


Thanks again Stef.

Regards,
Peter
wxPython never runs well in a program running under Tk, such as IDLE. 
Something about competing GUI's. If you want a replacement, you can try 
pycrust or one of its brethren, which ship with wxpython.


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


RE: F2PY ?? Has anyone worked with the F2PY generator?

2008-09-08 Thread Blubaugh, David A.

Pauli,


Yes,  I am utilizing the windows environment.  I cannot install f2py.  

I obtain the following error when I try to execute the setup.py file
within the f2py folder located within the numpy master folder:


Warning: Assuming default configuration
(lib\parser/{setup_parser,setup}.py was not found)
Appending f2py.lib.parser configuration to f2py.lib
Ignoring attempt to set 'name' (from 'f2py.lib' to 'f2py.lib.parser')
Warning: Assuming default configuration
(lib\extgen/{setup_extgen,setup}.py was not found)
Appending f2py.lib.extgen configuration to f2py.lib
Ignoring attempt to set 'name' (from 'f2py.lib' to 'f2py.lib.extgen')
Appending f2py.lib configuration to f2py
Ignoring attempt to set 'name' (from 'f2py' to 'f2py.lib')
F2PY Version 2_4423

Traceback (most recent call last):
  File "C:\Python25\Lib\site-packages\numpy\f2py\setup.py", line 130, in

**config)
TypeError: setup() got multiple values for keyword argument 'version'
>>> 


I do not know as to how to fix the multiple values for version??
PLEASE HELP!!!


David Blubaugh





 

-Original Message-
From: Blubaugh, David A. 
Sent: Monday, September 08, 2008 6:04 PM
To: 'python-list@python.org'
Subject: F2PY ?? Has anyone worked with the F2PY generator?

To All,


Has anyone worked with the F2PY generator?  This is something that is
supposedly built within numpy and scipy for the Python environment.  I
was wondering if anyone has encountered any issues with this
environment??  This is important to find the answers to these questions.



Thanks,


David Blubaugh



This e-mail transmission contains information that is confidential and may be 
privileged. It is intended only for the addressee(s) named above. If you 
receive 
this e-mail in error, please do not read, copy or disseminate it in any manner. 
If you are not the intended recipient, any disclosure, copying, distribution or 
use of the contents of this information is prohibited. Please reply to the 
message immediately by informing the sender that the message was misdirected. 
After replying, please erase it from your computer system. Your assistance in 
correcting this error is appreciated.

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


Re: lacking follow-through

2008-09-08 Thread Robert Kern

Eric Wertman wrote:

Perhaps the wrong idea of what the group is.  I would have thought
that
if one had a sufficiently developed idea and wanted to have it /
formally/
rejected, rather than merely sniped at, then writting a PEP would be
more
apposite than posting to c.l.py.

It's fine to post your not sufficiently developed ideas here merely
to
have them discussed.  But I don't know what makes you feel that you,
or
your ideas, are /entitled/ to any response at all, much less
"follow-through."


To expand on this a little bit,  I've been subscribed to this group
for a couple of months, but there seems to be a bit more gray area
between what would go to a 'python-dev'  group and a 'python-user'
group.   Long debates about language features and abstract ideas would
appeal to the former, but not the latter.  Certainly I fall into the
user category..  I'm pretty happy with python, and generally just
adjust to it's design and features, rather than spend lots of time on
whether they are 'right' or could be 'better'.  /shrug


Actually, python-dev is for the concrete development of Python. Releases, bugs, 
and occasionally design discussions for relevant features. Long debates about 
potential features and abstract ideas belong either here or python-ideas.


--
Robert Kern

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

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


Re: Updating python dictionary

2008-09-08 Thread John Machin
On Sep 9, 6:12 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
[big snip]
> In the interests of academia (although this isn't homework :)) I'll
> answer some of those questions:

Understanding your own requirements is , I would have thought, not
much to do with "academia" but a very practical idea.

>
> - Yes, the mapping dict doesn't necessarily have the same number of
> entries as the my_dict. It may have less than it or more than it.

What behaviour do you expect when there is a key in my_dict that is
not in the mapping?

> - There will never be dupes of key or value in the mapping. Though
> there maybe in my_dict.

If there are ever any dupes of a key in a Python dict object, it will
be the end of civilisation as we know it.

How are you are guaranteeing that there are no value dupes in your
mapping? What are the consequences if a dupe sneaks in?

>
> And, for extra credit, it may be useful to be able to 'translate' the
> my_dict back again using the same mapping_dict. ie, using the values
> in mapping dict as the new keys in my_dict, and the keys as the new
> values.

"... as the new values" of what? my_dict?? Don't you mean something
like "using the values in mapping dict as the keys in reverse_mapping,
and the keys as the values in reverse_mapping"?

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


Re: Where does the command "ls" in some doctest files come from ?

2008-09-08 Thread Steven D'Aprano
On Mon, 08 Sep 2008 22:04:29 +, KLEIN Stéphane wrote:

>> You found the ls() function in a docstring from Zope. The doctest seems
>> to be testing ls(). That suggests to me that ls() is defined in Zope,
>> not doctest.
> 
> Well, ls() is one test utility function defined in zc.buildout.testing
> module. This module contain many utility function like mkdir, ls, cat...
> 
> 
>> Why do you ask?
> 
> I'm curious... I've seen this utility and I would like to know how can I
> use it.


Untested:

from zc.buildout.testing import ls
ls("somefile")




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

Re: Coming from .NET and VB and C

2008-09-08 Thread benlindelof
BigTable looks great!  There's a 3% performance hit for these types of
databases.  However it makes up for it in other ways.

"Dive Into Python" seems to suggest there is less busy work, but I am
still looking into the GUI components of Python.  Say, a grid of 10x10
tiles of PNGs.


___
> have no preference with MySQL or SQL, stored procedures or ad-hoc
> queries.

Please note: MySQL is specific relational database management
system
(RDBMs), which uses a dialect of structured query language (SQL). SQL
by
itself is just a semi-standardized query language -- and can
technically
be used to access non-relational DBMS (if any such are still in use),
though the query processor would be a pain to program (map a
relational
join into a hierarchical DBMS schema? ugh).
> SO, I'm interested in using my Google App space (free 500MB) to
> develop a quick database application.  Using Python.  I found "Dive
> Into Python" which I will be reading shortly.

So one question: what RDBMs are supported in that space?
--
WulfraedDennis Lee Bieber   KD6MOG


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


Re: F2PY ?? Has anyone worked with the F2PY generator?

2008-09-08 Thread [EMAIL PROTECTED]
On Sep 8, 7:19 pm, "Blubaugh, David A." <[EMAIL PROTECTED]> wrote:
> Pauli,
>
> Yes,  I am utilizing the windows environment.  I cannot install f2py.  
>
> I obtain the following error when I try to execute the setup.py file
> within the f2py folder located within the numpy master folder:

You shouldn't need to do this. The installation of numpy puts f2py.py
in your Scripts folder.

explicitly:
C:\Python25\Python C:\Python25\Scripts\f2py.py

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


  1   2   >