New home for adns-python

2006-12-02 Thread Andy Dustman
I had been falling behind in patches for adns-python, so I thought it
would be a good idea to have a public site where it was easier for
people to contribute and report bugs. The new project page is:

http://code.google.com/p/adns-python

Eventually I will probably add an announcements group, but there is
not likely to be much traffic here for the foreseeable future. For
now, there is a general discussion group:

http://groups-beta.google.com/group/adns-python/

I've applied one important patch since 1.1.0, and that fixes a memory
leak. If you are reading this from the Groups Beta interface, you
should see a tarball for 1.1.1 in the files section; otherwise, you
cannot see it. Unfortunately, there is some name-mangling and referrer
detection and so it's not really possible to distribute a URL to get
the file release. Additionally, code.google.com currently doesn't
support flie releases, so I can't put it there, either.

If you are interested in becoming a project developer, let me know.

-- 
Patriotism means to stand by the country. It does
not mean to stand by the president. -- T. Roosevelt

This message has been scanned for memes and
dangerous content by MindScanner, and is
believed to be unclean.
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

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


Re: Python25.zip

2006-12-02 Thread Georg Brandl
Colin J. Williams wrote:
 Dennis Lee Bieber wrote:
 On Thu, 30 Nov 2006 18:14:11 -0500, Colin J. Williams
 [EMAIL PROTECTED] declaimed the following in comp.lang.python:
 
 As part of the Python initialization, C:\Windows\System32\Python25.zip 
 is set up in the path.

 I haven't seen any documentation on the use or purpose of the zip file.

  Well, did you examine the contents of it?
 There is no such file in C:\Windows\System32 - Python 2.5 on a Windows XP
 
  I believe for some versions now, import can pull from a ZIP
 archive -- perhaps they've put the many standard library imports into a
 single file...
 Yes, since 2.3 - thanks to Fredrick for the pointer to PEP 273.  That 
 gives the helpful warning that the above should follow the home 
 directory in the path list.
 
 PEP 302 says [PYTHONPATH] is directly needed for Zip imports.
 
 The role of Python25.zip is not clear.  Is it required in the path just 
 to enable the import X.zip capability?

No. It's there just *in case* you have a Python25.zip lying around containing
the library. By default, it isn't.

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


Re: strange problems with code generation

2006-12-02 Thread [EMAIL PROTECTED]
It is left over from the example I stold it from, I remove it and see
if that helps.


Dennis Lee Bieber wrote:
 On 1 Dec 2006 17:24:18 -0800, [EMAIL PROTECTED]
 [EMAIL PROTECTED] declaimed the following in comp.lang.python:

  data = sys2.stdin.readlines()

   And what do you expect to read from stdin? Do you even have an
 attached console to read?
 --
   WulfraedDennis Lee Bieber   KD6MOG
   [EMAIL PROTECTED]   [EMAIL PROTECTED]
   HTTP://wlfraed.home.netcom.com/
   (Bestiaria Support Staff:   [EMAIL PROTECTED])
   HTTP://www.bestiaria.com/

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


Re: What are python closures realy like?

2006-12-02 Thread Karl Kofnarson
 Karl,
 
 Usually when using this idiom, fun_basket would return a tuple of all of the 
 defined functions, rather than one vs. the other.  So in place of:
if f == 1:
return f1
if f == 2:
return f2
 Just do
return f1, f2
 (For that matter, the argument f is no longer needed either.)
 
 Then your caller will get 2 functions, who share a common var.  You don't 
 call fun_basket any more, you've already created your two closures.  Call 
 fun_basket using something like:
 
 z1,z2 = fun_basket(None)
 
 And then call z1() and z2() at your leisure - they should have the desired 
 behavior.
 
 -- Paul

Thanks a lot Paul and for the other answers. The things are now
clear to me. In fact, in the Lisp example that I mentioned, you
get a list (or let it be association list) of the internal
functions. Then you can call them separately and they work as
you expect but it's due to the fact only that you got them created
at the same time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing Barcodes from webapp?

2006-12-02 Thread Leo Kislov

Burhan wrote:
 Hello Group:

   I am in the planning stages of an application that will be accessed
 over the web, and one of the ideas is to print a barcode that is
 generated when the user creates a record.  The application is to track
 paperwork/items and uses barcodes to easily identify which paper/item
 belongs to which record.

   Is there an easy way to generate barcodes using Python -- considering
 the application will be printing to a printer at the client's machine?
 I thought of two ways this could be done; one would be to interface
 with the printing options of the browser to ensure that margins,
 headers, footers are setup properly (I have done this before using
 activex and IE, but with mixed results); the other would be to install
 some small application at the client machine that would intercept the
 print jobs and format them properly (taking the printing function away
 from the browser).

   Does anyone have any experience or advice? Any links I could read up
 on to help me find out how to program this?  Another way (easier
 hopefully) to accomplish this?

I think one of the easiest ways is to install acrobat reader and
redirect client browser to a generated pdf file.
http://www.reportlab.org/ has support for generating barcodes (and
more) in pdf documents.

  -- Leo

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


Video feature

2006-12-02 Thread Lad
I would like  to add on my website  a possibility for visitors to
upload video and watch other user's video. How much difficult would it
be with Python?
Thank you any for idea.

L.

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


Re: os.mkdir and mode

2006-12-02 Thread Peter Otten
vj wrote:

 How do I do the following unix command:
 
 mkdir -m770 test
 
 with the os.mkdir command. Using os.mkdir(mode=0770) ends with the
 incorrect permissions.

mkdir() works just like its C equivalent, see
http://docs.python.org/dev/lib/os-file-dir.html:

Where it is used, the current umask value is first masked out.

Use os.chmod() after os.mkdir() to get the desired permissions.

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


Re: strange problems with code generation

2006-12-02 Thread [EMAIL PROTECTED]
I changed that and the writelines and I am very close now.  thanks.


Dennis Lee Bieber wrote:
 On 1 Dec 2006 17:24:18 -0800, [EMAIL PROTECTED]
 [EMAIL PROTECTED] declaimed the following in comp.lang.python:

  data = sys2.stdin.readlines()

   And what do you expect to read from stdin? Do you even have an
 attached console to read?
 --
   WulfraedDennis Lee Bieber   KD6MOG
   [EMAIL PROTECTED]   [EMAIL PROTECTED]
   HTTP://wlfraed.home.netcom.com/
   (Bestiaria Support Staff:   [EMAIL PROTECTED])
   HTTP://www.bestiaria.com/

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


evaluating gui modules, any experience on tkinter?

2006-12-02 Thread krishnakant Mane
hello all,
I seam to have noticed this a bit late but it appears to me that
tkinter is being used very widely for gui development on all platform?
is that right?
since fredric lundh has written a very good introduction to tkinter
(was that just an intro?), I have got keen interest to know the
following.  may be fredric himself might put some light on these
points.
1. I seriously don't intend to start a flame war but does tkinter
stand up to the standards of heavy gui development?  can I have an
entire mdi application working fine with tkinter?  I know wxpython can
do it and I have heard enough about pyqt, but tkinter seams to be very
rich in gui objects.
2.  as usual I always look out for accessibility when it comes to gui
design.  will tkinter be useful for blind people?  I mean, are gui
apps in tkinter accessible on windows?
3.  I don't know if I need any thing else as dependencies on my
windows machine.  I am using python24 and I did not find any thing
about installation in the introduction to tkinter.  can some one give
me the process of installing tkinter and all necessary things?
4. is tkinter absolutely compatible with windows gui?  does it call on
native api for native look and feel?  in that case I think
accessibility issue is automatically solved.
I am looking out gui library for some serious application development.
 one is an erp system and the other is a customer relation management
system.
so I am confused between wxpython pyqt and now tkinter.
out of the 3 I only found qt talking extencively about accessibility,
but did not find a way to install qt in the first place.  I could not
compile qt nor did I find any run-time dlls for mingw so that I can
use it out of the box.
wxpython is the poorest in documentation and tkinter seams to be best at that.
please give me some advice.
thanking all.
Krishnakant.
-- 
http://mail.python.org/mailman/listinfo/python-list


Fw: Is there a reason not to do this?

2006-12-02 Thread Hendrik van Rooyen
Hendrik van Rooyen [EMAIL PROTECTED] wrote:


 Ron Garret [EMAIL PROTECTED] wrote:

   I don't want to get into a philosophical debate.
 
  Actually, I changed my mind.  Consider:

so did I - I think the chair analogy is not quite clear, so let me elucidate:

 
  def g(): print 'G'
 
  def h(): print 'H'
 
  def f(): g()
 
  class C1:
def m1(self): f()

up to here:

m1 will call f that will call g - should there ever be an m1 of this class

 
  class C2:
def m1(self): g()

the m1 of this class will call g with no redirection, if it were called into
existence and called

 
  c1 = C1()
  c2 = C2()

two new things are made (chairs?) , called c1 and c2-
so at this point,

c1.m1()#Prints G
c2.m1()#Prints G

as expected

 
  def f(): h()

now f is changed to call h instead of g for future calls to f (- loose talk
this - actually the name f is rebound...)

 
  class C2:
def m1(self): h()

this is just a promise of things to come, if an instance of this new class with
the old name should be made...

 
  c1.m1()  # Prints H
  c2.m1()  # Prints G

yup.

 
  On what principled basis can you justify two different outputs in this
  case?  Why should I be able to change the definition of f and not have
  to go back and recompile all references to it, but not m1?

I think the simplest way to look at this is as follows - the inherited
attributes of a class instance are fixed
at the time of instantiation, while the function redirection works because it is
evaluated at the time that it is called, not at the time it is created (or
defined if you prefer).

To make it work the way you want, would, I expect,  require that the whole
instantiation process be either checked for validity, or executed with every
call to a class instance - a sort of make and kill on the fly process, or
alternatively, at the time of the re definiton of a class, all instances of the
class of that name would have to be re initialised - and this may not be
possible, if for instance, the new __init__ method needs more variables than the
old one did - so it becomes a bit of a toffee, and it looks as if the python dev
crowd wisely decided to just leave it alone...


 This feels to me as if you are changing the specification of what wood to use
 from yellowood to teak after the chair has already been made.

so now maybe you can see why I said that.  ;-)

- Hendrik


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


Re: best way to align words?

2006-12-02 Thread Robert R.

Hello,

thanks for all your replies, i'm now looking to dynamic programming...

sorry for forgetting to say that i wanted the words to be ordered, thus
:

s1 = hello there dudes
s2 = dudes hello there
s3 = there dudes hello

will not return anything while sharing all three words.

Bearophile your solution with graph looks interesting although i still
do not understand how it works, but yes there is definitively something
with drawing path around words.

i have tried SequenceMatcher from difflib after using combinations of
all sentences as i need to process much more than the 3 of my first
example.

best.

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


Re: type(foo) == function ?

2006-12-02 Thread Fredrik Lundh
Mathias Panzenboeck wrote:

 This builtin will be removed in python 3.0!

that's far from clear (since the replacement approach, just call it, 
simply doesn't work).  and if you track the Py3K discussions, you'll 
notice current threads about *more* support for interface testing, not 
less support.

/F

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


Re: Python25.zip

2006-12-02 Thread Martin v. Löwis
Colin J. Williams schrieb:
 The role of Python25.zip is not clear.  Is it required in the path just
 to enable the import X.zip capability?

To rephrase Georg's explanation: it allows Python distributors (e.g.
Linux distributors, or ActiveState) to put all of the Python library
(including site.py) into a single zip file, instead of requiring a
Lib directory with many files in it. E.g. on Windows, a complete
Python installation could consist of three files: python.exe,
python25.dll, and python25.zip.

To make that possible, you can't tell people that they have to edit
site.py to put a zip file on sys.path, instead, the distributed
interpreter must already look for a file even though this file
will usually not be present.

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


Re: python 2.5 install from source problem

2006-12-02 Thread Martin v. Löwis
Fabian Braennstroem schrieb:
 I just tried to install python 2.5 from source on my
 ScienticLinux (Redhat Clone) machine. It seems to work
 without any problem, at least I am able to run some of my
 old scripts. I installed it with './configure
 --prefix=/opt/python make make altinstall', but now for a
 'vtk' installation which needs the python libraries I am not
 able to find a file like 'libpython2.5.so.*', which I think
 should be produced (at least at my office's machine (redhat)
 it is there). I just can find a 'libpython2.5.a' file ...
 
 Do I do something wrong?

I'd say it is a bug in vtk that it requires libpython2.5.so.*.
However, to work-around, you can configure Python with
--enable-shared. Make sure to set LD_LIBRARY_PATH or LD_RUN_PATH
appropriately.

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


rdf, xmp

2006-12-02 Thread Imbaud Pierre
I have to add access to some XMP data to an existing python
application.
XMP is built on RDF, RDF is built on XML.
I try to reuse as much of possible of existing code.
btw, dont mistake XMP (http://www.adobe.com/products/xmp/) with
XMPP (http://www.faqs.org/rfcs/rfc3920.html), backed by PyXMPP
(http://pyxmpp.jajcus.net/). XMP is adobe's standard for storing
metadata in files (jpg, pdf).
Are there people with the same concern out there?

It seemed logical to use existing rdf libraries. I found two, RDFLib
(http://rdflib.net) and pyrple (http://infomesh.net/pyrple/).
My first contact with RDFLib is disappointing: real intricate lib
(lot of modules, lot of methods), almost no documentation (an almost
empty Epydoc generated documentation frame), puzzling experiments.

I guess XMP uses a real tiny subset of RDF possibilities, and maybe
RDFLib is fine for ambitious design, but too heavy in this case?
Ill now dig a little on pyrple.
Feedback on these matters, please?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.mkdir and mode

2006-12-02 Thread Nick Craig-Wood
Peter Otten [EMAIL PROTECTED] wrote:
  vj wrote:
 
  How do I do the following unix command:
  
  mkdir -m770 test
  
  with the os.mkdir command. Using os.mkdir(mode=0770) ends with the
  incorrect permissions.
 
  mkdir() works just like its C equivalent, see
  http://docs.python.org/dev/lib/os-file-dir.html:
 
  Where it is used, the current umask value is first masked out.
 
  Use os.chmod() after os.mkdir() to get the desired permissions.

I think you meant use os.umask(0) before the os.mkdir() ?

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


Re: os.mkdir and mode

2006-12-02 Thread Nick Craig-Wood
vj [EMAIL PROTECTED] wrote:
  How do I do the following unix command:
 
  mkdir -m770 test
 
  with the os.mkdir command. Using os.mkdir(mode=0770) ends with the
  incorrect permissions. 

You mean :-

$ python -c 'import os; os.mkdir(test, 0770)'
$ stat test/
  File: `test/'
  Size: 4096Blocks: 8  IO Block: 4096   directory
Device: 806h/2054d  Inode: 2453906 Links: 2
Access: (0750/drwxr-x---)  Uid: (  518/ ncw)   Gid: (  518/ ncw)
Access: 2006-12-02 09:42:59.0 +
Modify: 2006-12-02 09:42:59.0 +
Change: 2006-12-02 09:42:59.0 +

vs

$ rmdir test
$ mkdir -m770 test
$ stat test/
  File: `test/'
  Size: 4096Blocks: 8  IO Block: 4096   directory
Device: 806h/2054d  Inode: 2453906 Links: 2
Access: (0770/drwxrwx---)  Uid: (  518/ ncw)   Gid: (  518/ ncw)
Access: 2006-12-02 09:43:23.0 +
Modify: 2006-12-02 09:43:23.0 +
Change: 2006-12-02 09:43:23.0 +
$ umask
0022
$

So it looks like python mkdir() is applying the umask where as
/bin/mkdir doesn't.  From man 2 mkdir

   mkdir() attempts to create a directory named pathname.

   The  parameter mode specifies the permissions to use. It is modified by
   the process's umask in the usual way: the permissions  of  the  created
   directory  are  (mode  ~umask  0777).  Other mode bits of the created
   directory depend on the operating system.  For Linux, see below.

So python follows C rather than shell.  Seems reasonable.

To fix your problem, reset your umask thus :-

$ rmdir test
$ python -c 'import os; os.umask(0); os.mkdir(test, 0770)'
$ stat test
  File: `test'
  Size: 4096Blocks: 8  IO Block: 4096   directory
Device: 806h/2054d  Inode: 2453906 Links: 2
Access: (0770/drwxrwx---)  Uid: (  518/ ncw)   Gid: (  518/ ncw)
Access: 2006-12-02 09:48:04.0 +
Modify: 2006-12-02 09:48:04.0 +
Change: 2006-12-02 09:48:04.0 +
$

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


Re: os.mkdir and mode

2006-12-02 Thread Peter Otten
Nick Craig-Wood wrote:

 Peter Otten [EMAIL PROTECTED] wrote:
  vj wrote:
 
  How do I do the following unix command:
  
  mkdir -m770 test
  
  with the os.mkdir command. Using os.mkdir(mode=0770) ends with the
  incorrect permissions.
 
  mkdir() works just like its C equivalent, see
  http://docs.python.org/dev/lib/os-file-dir.html:
 
  Where it is used, the current umask value is first masked out.
 
  Use os.chmod() after os.mkdir() to get the desired permissions.
 
 I think you meant use os.umask(0) before the os.mkdir() ?

No, I didn't. What is the difference/advantage of that approach?

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


Re: client/server design and advice

2006-12-02 Thread Irmen de Jong
John Henry wrote:
 On the subject of passing things around, is there a no brainer way of
 sending files back and forth over Pyro?
 
 I am currently using a shared drive to do that.  May be I missed that
 feature?
 

Sending files around is just a special case of passing large amounts
of data to other systems. There is no built in support for file transfer
in Pyro.
It's rather easy to make a file transfer tool though, there is an 
example in the Pyro distribution that shows how this *may* be done.

But choose the right tool for the job, things like rsync or even ftp
may be preferable for just file transfer!

If you use a shared drive, you could use Pyro to 'tell' the receiving
side that the file is there with this-and-this name, to trigger a
download. When the receiver is done copying the file, it can signal
back and the sender can delete the file. But that's just an idea.

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


Re: Python, PostgreSQL, What next?

2006-12-02 Thread Armin
 
 I've studied Python and studied PostgreSQL. 
Good.

What is the absolute next best step to take to merge these two finely 
together? I've heard of

Just download psycopg2. Python and PostgreSQL are a match made in heavan.

Make your connection, 
do querys, 
get data,
earn profits.

Object-Relational-Mappers are to direct SQL as phone sex is to the real 
thing.

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


ftputil upload error

2006-12-02 Thread Croteam
Hello,

I have one problem about ftputil file upload.Here is my short example:

from ftputil import FTPHost
import tkFileDialog
import os
from Tkinter import Tk

ftp=FTPHost('myserver','username','password')

forupload=tkFileDialog.askopenfile(parent=root)

file=forupload.name




## I was choose file C:/Documents and Settings/VEKI/My
Documents/internet/popravak.txt  ##



ftp.upload(file,os.path.basename(file))

THEN I GAIN ERROR:
Traceback (most recent call last):
  File pyshell#48, line 1, in -toplevel-
ftp.upload(file,os.path.basename(file),'b')
  File C:\Python24\lib\ftputil.py, line 417, in upload
self.__copy_file(source, target, mode, open, self.file)
  File C:\Python24\lib\ftputil.py, line 406, in __copy_file
target = target_open(target, target_mode)
  File C:\Python24\lib\ftputil.py, line 245, in file
host._file._open(effective_file, mode)
  File C:\Python24\lib\ftp_file.py, line 115, in _open
self._conn = ftp_error._try_with_ioerror(
  File C:\Python24\lib\ftp_error.py, line 101, in _try_with_ioerror
raise FTPIOError(ftp_error)
FTPIOError: 550 popravak.txt: Access is denied.
Debugging info: ftputil 2.1, Python 2.4.2 (win32)



  Regards,

  Vedran

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


Python 2.5 bindings for Subversion 1.4.2 on Win32 binary

2006-12-02 Thread patkinson
Hello,

I am one of those guys trying with no chance to get a working copy of
TRAC for python 2.5

http://trac.edgewall.org/  is a superb Project managment tool with a
wiki, control version (SVN), and a tracking bug/task system.
This is a suposed place to go for a windows user:
http://trac.edgewall.org/wiki/TracOnWindows/Python2.5

You are able to:
- Install a subversion server 1.4.2 (like a windows service).
- Install python 2.5
- Install Genshi 0.3.4
- Install Setuptools
- Install Trac (0.11dev) from the last development source.

But you need a Python 2.5 binding to be able to talk to a subversion
repository, and this is a road to nowhere (cul de sac) issue.

He is a post from Brandt, Servatius to the  Subversion users list
asking for this:
http://svn.haxx.se/users/archive-2006-12/0041.shtml

The people at TRAC and Subversion says: this is a topic not concerning
their software.
Please, could be any interested team o person in the python Comunity to
adapt a python 2.5 interface to SVN ?

Great python Projects like TRAC or DJANGO are the keys to a wide
acceptance of python. Making this easy to the final users is (in my
opinion) a survival question for the future of Python.

Thanks
Peter Atkinson

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


Re: Python, PostgreSQL, What next?

2006-12-02 Thread patkinson
Hi,
Look at DJANGO;-)
http://www.djangoproject.com/
http://www.djangobook.com/

Regards
Peter Atkinson



vbgunz ha escrito:

 Hello all,

 I've studied Python and studied PostgreSQL. What is the absolute next
 best step to take to merge these two finely together? I've heard of
 SQLAlchemy and some others but before I dive in, I would really like
 the opinion of those who tried it and other toolkits.

 My main concern is, I would like to completely work with a database
 from Python. What would you suggest I look into?
 
 Thank you for your time!

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


Re: Printing Barcodes from webapp?

2006-12-02 Thread Fredrik Lundh
Burhan wrote:

   Is there an easy way to generate barcodes using Python -- considering
 the application will be printing to a printer at the client's machine?

here are some barcode generators for Python:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/426069
http://www.cgpp.com/bookland/
http://www.reportlab.org (see the graphics.barcode subpackage)

/F

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


Re: Python 2.5 bindings for Subversion 1.4.2 on Win32 binary

2006-12-02 Thread Martin v. Löwis
patkinson schrieb:
 Great python Projects like TRAC or DJANGO are the keys to a wide
 acceptance of python. Making this easy to the final users is (in my
 opinion) a survival question for the future of Python.

Please note that threatening is useless most of the time in free
software. Very few people will agree that the future of Python depends
on provision of a subversion module for Python 2.5 on Win32, anyway.

If you need this, you would work on making it happen yourself, or
you should hire somebody to make it for you if you can't do it
yourself.

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


Re: rdf, xmp

2006-12-02 Thread Andy Dingley

Imbaud Pierre wrote:
 I have to add access to some XMP data to an existing python
 application.
 XMP is built on RDF, RDF is built on XML.

RDF is _NOT_  built on top of XML. Thinking that it is causes a lot of
trouble in the architecture of big RDF projects. RDF is a data model,
not a serialisation. The data model is also a graph (more than XML can
cope with) and can span multiple documents. It's only RDF/XML that's
the serialisation of RDF into XML and good architectures start from
thinking about the RDF data model, not this RDF/XML serialisation.

As to RDF handling, then the usual toolset is Jena (in Java) and
Redland has a Python binding although Redland is fairly aged now.

I'm unfamiliar with XMP and won't have a chance to look at it until
Monday. However if XMP is strongly XML like despite claiming to be
RDF, then you might find that handling a pure XMP problem is quite
easily done with XML tools.

Famously RDF/XML is unprocessable with XSLT if it's sophisticated, but
quite easy if it's restricted to only a simple XML-like RDF model. XMP
could well be similar.

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


Re: Printing Barcodes from webapp?

2006-12-02 Thread Andy Dingley

Burhan wrote:

   Is there an easy way to generate barcodes using Python

Easy way for any application or language to generate barcodes is to
install a barcode font on the client machine, then just generate a
suitable text string for it. This is _very_ easy, if you can get the
font deployed.  I usually find myself using Code 39 and printing them
from a HTML document. There are plenty of free code 39 fonts around and
the string mangling to get the barcode structured correctly is just a
trivial prefix / suffix.

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


Re: Python 2.5 bindings for Subversion 1.4.2 on Win32 binary

2006-12-02 Thread Fredrik Lundh
patkinson wrote:

 Great python Projects like TRAC or DJANGO are the keys to a wide
 acceptance of python. Making this easy to the final users is (in my
 opinion) a survival question for the future of Python.

any special reason why you cannot use the *recommended* releases in-
stead of playing with bleeding edge development code and use only if 
you don't need to interface with subversion instructions, and then 
complain when you cannot get it to work?

simple instructions for installing Trac 0.10 on Windows can be found here:

   http://trac.edgewall.org/wiki/TracOnWindows/Rewrite

that page contains direct links to Python and Subversion installers, and 
a all-in-one installation scripts that fixes the rest.

subversion bindings for Python on Windows can be found here:

   http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91

/F

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


Re: Python 2.5 bindings for Subversion 1.4.2 on Win32 binary

2006-12-02 Thread patkinson
Yes Martin,

You are right. I'm not trying to threat any one. My excuses to you with
that (infortunated) paragraph.

Thanks anyway for your suggestion.  My intention was to motivate other
people with the same interests, or to find another way or patch, to
keep Trac working.

Regards
P. Atkinson



Martin v. Löwis ha escrito:

 patkinson schrieb:
  Great python Projects like TRAC or DJANGO are the keys to a wide
  acceptance of python. Making this easy to the final users is (in my
  opinion) a survival question for the future of Python.

 Please note that threatening is useless most of the time in free
 software. Very few people will agree that the future of Python depends
 on provision of a subversion module for Python 2.5 on Win32, anyway.

 If you need this, you would work on making it happen yourself, or
 you should hire somebody to make it for you if you can't do it
 yourself.
 
 Regards,
 Martin

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

Re: Thread help

2006-12-02 Thread Bjoern Schliessmann
John Henry wrote:

 Why stop there?

Stop where, after one thread? Different question: Why use many
threads? It adds complexity and overhead and forces you to think
about thread safety and reentrance.

Regards,


Björn

-- 
BOFH excuse #134:

because of network lag due to too many people playing deathmatch

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


Re: Python, PostgreSQL, What next?

2006-12-02 Thread Fredrik Lundh
vbgunz wrote:

 I've studied Python and studied PostgreSQL. What is the absolute next
 best step to take to merge these two finely together?

the db-api interface:

   http://www.python.org/dev/peps/pep-0249/

db-api compliant postgresql adapters:

   http://www.pygresql.org/
   http://www.initd.org/

higher-level interfaces for postgresql and other db-api compliant drivers:

   http://www.sqlobject.org/
   http://www.sqlalchemy.org/
   http://www.djangoproject.com/documentation/db_api/
   etc.

/F

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


Re: best way to align words?

2006-12-02 Thread Oleg Batrashev
 thanks for all your replies, i'm now looking to dynamic programming...
Id better warn you before you go further.
 Notice that LCS is often defined to be finding all common
subsequences of a maximum length. This problem inherently has higher
complexity, as the number of such subsequences is exponential in the
worst case

This means that if you have 10 sentences with 5 words in each there is
5^10 space and time complexity. Definitelly, there are better
algorithms from dynamic programming, but you should review your needs:
how many sentences, words you have.

There can be easier way than dynamic programming.

Oleg

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


Re: Error handling. Python embedded into a C++ app.

2006-12-02 Thread Wolfram
Maybe of interest to people loking for a solution:

I solved my issue by changing the program retroactively from a pure
MFC app to a console one using this procedure:
http://homepage3.nifty.com/ysflight/mfcconsole/mfcconsole.html

I am still not sure why all of my other attempts failed, but most
somehow changed stderr after the program started and before the python
initialisation call. Maybe by binding in the python libraries some
initialisation is done automatically before the first user C++ line
is called and so any change done by the C++ code ignored? 

Oh well, it works now, even if with a kludge (I always need to have a
console, even if I do not use Python).

Bye bye, Wolfram Kuss.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing Barcodes from webapp?

2006-12-02 Thread Burhan

Andy Dingley wrote:
 Burhan wrote:

Is there an easy way to generate barcodes using Python

 Easy way for any application or language to generate barcodes is to
 install a barcode font on the client machine, then just generate a
 suitable text string for it. This is _very_ easy, if you can get the
 font deployed.  I usually find myself using Code 39 and printing them
 from a HTML document. There are plenty of free code 39 fonts around and
 the string mangling to get the barcode structured correctly is just a
 trivial prefix / suffix.

I thought about this as an option too, but I do not have control over
the client machines, maybe I'll use this and go with the PDF idea
mentioned above.

Thanks for all the links, I have some reading to do now.

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


Re: evaluating gui modules, any experience on tkinter?

2006-12-02 Thread Norm

krishnakant Mane wrote:
 hello all,
 I seam to have noticed this a bit late but it appears to me that
 tkinter is being used very widely for gui development on all platform?
 is that right?
 since fredric lundh has written a very good introduction to tkinter
 (was that just an intro?), I have got keen interest to know the
 following.  may be fredric himself might put some light on these
 points.
 1. I seriously don't intend to start a flame war but does tkinter
 stand up to the standards of heavy gui development?  can I have an
 entire mdi application working fine with tkinter?  I know wxpython can
 do it and I have heard enough about pyqt, but tkinter seams to be very
 rich in gui objects.
 2.  as usual I always look out for accessibility when it comes to gui
 design.  will tkinter be useful for blind people?  I mean, are gui
 apps in tkinter accessible on windows?
 3.  I don't know if I need any thing else as dependencies on my
 windows machine.  I am using python24 and I did not find any thing
 about installation in the introduction to tkinter.  can some one give
 me the process of installing tkinter and all necessary things?
 4. is tkinter absolutely compatible with windows gui?  does it call on
 native api for native look and feel?  in that case I think
 accessibility issue is automatically solved.
 I am looking out gui library for some serious application development.
  one is an erp system and the other is a customer relation management
 system.
 so I am confused between wxpython pyqt and now tkinter.
 out of the 3 I only found qt talking extencively about accessibility,
 but did not find a way to install qt in the first place.  I could not
 compile qt nor did I find any run-time dlls for mingw so that I can
 use it out of the box.
 wxpython is the poorest in documentation and tkinter seams to be best at that.
 please give me some advice.
 thanking all.
 Krishnakant.

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


Re: evaluating gui modules, any experience on tkinter?

2006-12-02 Thread Norm
For wxPython, there is a book  wxPython in Action  published by
Manning

Cheers

Norm wrote:
 krishnakant Mane wrote:
  hello all,
  I seam to have noticed this a bit late but it appears to me that
  tkinter is being used very widely for gui development on all platform?
  is that right?
  since fredric lundh has written a very good introduction to tkinter
  (was that just an intro?), I have got keen interest to know the
  following.  may be fredric himself might put some light on these
  points.
  1. I seriously don't intend to start a flame war but does tkinter
  stand up to the standards of heavy gui development?  can I have an
  entire mdi application working fine with tkinter?  I know wxpython can
  do it and I have heard enough about pyqt, but tkinter seams to be very
  rich in gui objects.
  2.  as usual I always look out for accessibility when it comes to gui
  design.  will tkinter be useful for blind people?  I mean, are gui
  apps in tkinter accessible on windows?
  3.  I don't know if I need any thing else as dependencies on my
  windows machine.  I am using python24 and I did not find any thing
  about installation in the introduction to tkinter.  can some one give
  me the process of installing tkinter and all necessary things?
  4. is tkinter absolutely compatible with windows gui?  does it call on
  native api for native look and feel?  in that case I think
  accessibility issue is automatically solved.
  I am looking out gui library for some serious application development.
   one is an erp system and the other is a customer relation management
  system.
  so I am confused between wxpython pyqt and now tkinter.
  out of the 3 I only found qt talking extencively about accessibility,
  but did not find a way to install qt in the first place.  I could not
  compile qt nor did I find any run-time dlls for mingw so that I can
  use it out of the box.
  wxpython is the poorest in documentation and tkinter seams to be best at 
  that.
  please give me some advice.
  thanking all.
  Krishnakant.

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


Re: PythonTidy

2006-12-02 Thread Chuck Rhode
Thomas Heller wrote this on Fri, Dec 01, 2006 at 10:12:38PM +0100.  My reply is 
below.

 Here is part of a diff before and after running PythonTidy on it:
 
 start
 -def comptr_setitem(self, index, value):
 -# We override the __setitem__ method of the
 -# POINTER(POINTER(interface)) type, so that the COM
 -# reference count is managed correctly.
 +def comptr_setitem(self, index, value):  # We override the 
 __setitem__ method of the
 + # 
 POINTER(POINTER(interface)) type, so that the COM
 + # reference count is 
 managed correctly.
 
 Can this be customized?

I am able to rationalize why this happens, but you are correct: This
behavior is not appropriate.  I am testing several changes, one of
which should prevent it in all cases, obviating the need for a custom
switch.

-- 
.. Chuck Rhode, Sheboygan, WI, USA
.. 1979 Honda Goldwing GL1000 (Geraldine)
.. Weather:  http://LacusVeris.com/WX
.. 10° — Wind S 5 mph
-- 
http://mail.python.org/mailman/listinfo/python-list

How to realize the interactive python in Eclipse?

2006-12-02 Thread purple
I have installed the Eclipse and the plug-in Pydev. Also, I have add an
python program in the external tools. When I run the python program in
the external tools, i can type python command just like in the python
shell.But when I finished running a python file, in the console, I
could not type any command to check some argument generated in the
process. Is there any way I can make it?
thank you~~

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

Re: Is there a reason not to do this?

2006-12-02 Thread Michele Simionato
Since we are in a hackish mood, another alternative - interesting if
you want
the freedom to update your instances selectively - is to change their
class at
runtime.
In this way you can specify which instances must use the new version of
the class and which ones must keep the old one. It may be useful
for debugging purposes too. Here is some code, to get you started:

def update(obj):
Look if the class of obj has been redefined in the global
namespace:
if so, update obj
cls = globals().get(obj.__class__.__name__)
if cls and cls is not obj.__class__:
obj.__class__ = cls

class C(object): # old class
def m1(self):
return 1

c = C() # old instance
assert c.m1() == 1

class C(object): # new class
def m1(self):
return 2

update(c) # old instance updated
assert c.m1() == 2

   Michele Simionato

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


Re: Is there a reason not to do this?

2006-12-02 Thread Michele Simionato
Ron Garret wrote:

 Doesn't work for me:

  c2
 __main__.C2 instance at 0x51e850
  c2.m1()
 G
  class C2:
 ...   __metaclass__ = modify_in_place
 ...   def m1(self): print 'Q'
 ...
  c2.m1()
 G
  C2().m1()
 Q

I assume your original C2 class was defined in a different module, not
in the current global
namespace. What do you get from  c.__class__.__module__ ? It should be
__name__ for
this approach to work.

class C2:
   def m1(self):
  return 'G'

c = C2()

def modify_in_place(name,bases,clsdict):
cls = globals()[name]
for attr,val in clsdict.iteritems():
setattr(cls,attr,val)
return cls

# Replace second C2 class above with this
class C2:
__metaclass__ = modify_in_place
def m1(self):
   return 'Q'

assert c.m1() == 'Q'
assert c.__class__.__module__ == __name__ # make sure c.__class__ is
defined in the current module


 Michele Simionato

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


Re: os.mkdir and mode

2006-12-02 Thread vj
 To fix your problem, reset your umask thus :-

Thanks for the detailed reply. Your fix works like a charm. 

VJ

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


Re: converting dict to object

2006-12-02 Thread Neil Cerutti
On 2006-12-02, Michel Claveau [EMAIL PROTECTED] wrote:
 Hi!

 Yes.

 But...

 Try:d = {'a': 1, 'b': 2, 'def': 123}

 Ok, I go out...

How to convert a list of strings into a list of integers:

 a = ['82', '4', '16']

 ai = [int(i) for i in a]

Yes.

But...

Try:  a = ['82', '4', '16', 'foo']

Ok, I go out...

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


Re: python vs java eclipse

2006-12-02 Thread Philippe Martin
Amir  Michail wrote:

 Hi,
 
 It seems to me that measuring productivity in a programming language
 must take into account available tools and libraries.
 
 Eclipse for example provides such an amazing IDE for java that it is no
 longer obvious to me that one would be much more productive in python
 for medium sized projects.
 
 Sure, all that Java static typing can be painful, but Eclipse takes
 some of that pain away. Moreover, static typing can result in better
 on-the-fly error detection and refactoring support.
 
 Any thoughts on this?
 
 Amir

FYI: http://showmedo.com/videos/series?name=PyDevEclipseList

hg

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


Re: a -very- case sensitive search

2006-12-02 Thread Ola K
Thank you! This was really helpful. Also the data bit about .istitle()
was the missinng piece of the puzzle for me... So now my script is nice
and working :)

And as beside the point, yes I am from Israel, and no, we don't have
uper case and lower case letters. Hebrew has only one set of letters.
So my script was actualy for the english letters inside the hebrew
text...

--Ola



Paul McGuire כתב:
 Ola K [EMAIL PROTECTED] wrote in message
 news:[EMAIL PROTECTED]
  Hi,
  I am pretty new to Python and I want to make a script that will search
  for the following options:
  1) words made of uppercase characters -only- (like YES)
  2) words made of lowercase character -only- (like yes)
  3) and words with only the first letter capitalized (like Yes)
  * and I need to do all these considering the fact that not all letters
  are indeed English letters.
 
  I went through different documention section but couldn't find a right
  condition, function or method for it.
  Suggestions will be very much appriciated...
  --Ola
 
 Ola,

 You may be new to Python, but are you new to regular expressions too?  I am
 no wiz at them, but here is a script that takes a stab at what you are
 trying to do. (For more regular expression info, see
 http://www.amk.ca/python/howto/regex/.)

 The script has these steps:
 - create strings containing all unicode chars that are considered lower
 and upper, using the unicode.is* methods
 - use these strings to construct 3 regular expressions (or res), one for
 words of all lowercase letters, one for words of all uppercase letters, and
 one for words that start with an uppercase letter followed by at least one
 lowercase letter.
 - use each re to search the string uYES yes Yes, and print the found
 matches

 I've used unicode strings throughout, so this should be applicable to your
 text consisting of letters beyond the basic Latin set (since Outlook Express
 is trying to install Israeli fonts when reading your post, I assume these
 are the characters you are trying to handle).  You may have to do some setup
 of your locale for proper handling of unicode.isupper, etc., but I hope this
 gives you a jump start on your problem.

 -- Paul


 import sys
 import re

 uppers = u.join( unichr(i) for i in range(sys.maxunicode)
 if unichr(i).isupper() )
 lowers = u.join( unichr(i) for i in range(sys.maxunicode)
 if unichr(i).islower() )

 allUpperRe = ur\b[%s]+\b % uppers
 allLowerRe = ur\b[%s]+\b % lowers
 capWordRe = ur\b[%s][%s]+\b % (uppers,lowers)

 regexes = [
 (allUpperRe, all upper),
 (allLowerRe, all lower),
 (capWordRe, title case),
 ]
 for reString,label in regexes:
 reg = re.compile(reString)
 result = reg.findall(u YES  yes Yes )
 print label,:,result

 Prints:
 all upper : [u'YES']
 all lower : [u'yes']
 title case : [u'Yes']

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

Re: Python, PostgreSQL, What next?

2006-12-02 Thread Thomas Bartkus
On Fri, 01 Dec 2006 23:04:37 -0800, vbgunz wrote:

 Hello all,
 
 I've studied Python and studied PostgreSQL. What is the absolute next
 best step to take to merge these two finely together? I've heard of
 SQLAlchemy and some others but before I dive in, I would really like
 the opinion of those who tried it and other toolkits.
 
 My main concern is, I would like to completely work with a database
 from Python. What would you suggest I look into?

Let me venture that the biggest problem most people seem to have is that
they endure great pain just to avoid learning SQL. SQL is a complete
programming language in and of itself with a breadth and depth that most
people miss.  And it covers much terrain missed by Python. Which is a good
thing because SQL and Python are perfect together.  With this language mix
you've got darn near everything licked.

Get SQL in your head and all you will need would be the db-api interface
with Postgres that Frederick Lundh pointed you to.  All you want to do is
throw SQL commands at Postgres and recover result sets into Python.

It's a cinch.
Thomas Bartkus



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


Re: Python, PostgreSQL, What next?

2006-12-02 Thread jim-on-linux

Before commiting to a RDBMS take a look at Gadfly. 

Depending on what you need a RDB for,
(light duty), or (heavy duty) take a look at 
gadfly.  Gadfly is made from all python code.

Use stardard SQL statements like Select, Create 
and Drop Tables, etc. 

Newest version GadflyB5 
http://gadfly.sourceforge.net/

jim-on-linux
http://www.inqvista.com




On Saturday 02 December 2006 11:33, Thomas Bartkus 
wrote:
 On Fri, 01 Dec 2006 23:04:37 -0800, vbgunz 
wrote:
  Hello all,
 
  I've studied Python and studied PostgreSQL.
  What is the absolute next best step to take
  to merge these two finely together? I've
  heard of SQLAlchemy and some others but
  before I dive in, I would really like the
  opinion of those who tried it and other
  toolkits.
 
  My main concern is, I would like to
  completely work with a database from Python.
  What would you suggest I look into?

 Let me venture that the biggest problem most
 people seem to have is that they endure great
 pain just to avoid learning SQL. SQL is a
 complete programming language in and of itself
 with a breadth and depth that most people miss.
  And it covers much terrain missed by Python.
 Which is a good thing because SQL and Python
 are perfect together.  With this language mix
 you've got darn near everything licked.

 Get SQL in your head and all you will need
 would be the db-api interface with Postgres
 that Frederick Lundh pointed you to.  All you
 want to do is throw SQL commands at Postgres
 and recover result sets into Python.

 It's a cinch.
 Thomas Bartkus
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About alternatives to Matlab

2006-12-02 Thread Carl Banks
Jon Harrop wrote:
 I don't know Python but this benchmark caught my eye.

 def D4_Transform(x, s1=None, d1=None, d2=None):

D4 Wavelet transform in NumPy
(C) Sturla Molden

C1 = 1.7320508075688772
C2 = 0.4330127018922193
C3 = -0.066987298107780702
C4 = 0.51763809020504137
C5 = 1.9318516525781364
if d1 == None:
   d1 = numpy.zeros(x.size/2)
   s1 = numpy.zeros(x.size/2)
   d2 = numpy.zeros(x.size/2)

 Are these definitions ever used? It looks like s1, d1 and d2 are all
 redefined below without reference to these previous values.

No, they're never redefined (even in the recursive version).  Slices of
them are reassigned.  That's a big difference.

odd = x[1::2]
even = x[:-1:2]
d1[:] = odd[:] - C1*even[:]
s1[0] = even[0] + C2*d1[0] + C3*d1[-1]
s1[1:] = even[1:] + C2*d1[1:] + C3*d1[:-1]
d2[0] = d1[0] + s1[-1]
d2[1:] = d1[1:] + s1[:-1]
even[:] = C4 * s1[:]
odd[:] = C5 * d2[:]

 Does that line create an array that is never used? If so, is C5 also never
 used?

No it doesn't create a new array.  But it does have an effect.
Explained below.

(Actually, it does create a temporary array to store the intermediate
result, but that array does not get bound to odd.)


if x.size  2:
 
 D4_Transform(even,s1[0:even.size/2],d1[0:even.size/2],d2[0:even.size/2])

 What is the result of this function?

It modifies the array even in place.  This also has an effect.


 I'm interested in translating this function into other languages, like
 OCaml, to see how good Python's performance is (I am amazed it can beat
 Matlab, not that I've used Matlab).

Matlab has a few *cough* limitations when it comes to hand-optimizing.
When writing naive code, Matlab often is faster than Python with numpy
because it has many commerical man-year of optimizing behind it.
However, Matlab helps v


 In particular, I think you are eagerly
 allocating arrays when, in a functional language, you could just as easily
 compose closures.

You are completely wrong.

What you seem to be missing is that slice assignment shares data.  For
example, the statement odd = x[1::2] does NOT create a new array.  It
takes a slice of x's data (in this case, the odd elements of x: slices
need not be contiguous), and binds it to the symbol odd.  The array
elements are shared; changing elements in odd also changes elements of
x.

So later on, the statement odd[:] = C5*d2[:] reassigns the elements
of odd, which, because the array elements are shared, also reassigns
the odd elements in x.

(Notice the difference between odd[:]= and odd=.  odd[:]= is
slice assignment; it changes the elements in the given slice of odd, in
this case the whole array.  odd= rebinds the symbol odd to a
different object, which could be a new array, a slice of an existing
array, or any other Python object.)


This data sharing more or less accomplishes the same thing that the
closures you speak of accomplish (in this case), only without the
functional.


 For example, this program is 3x faster than the Python on my machine:

 let rec d4 s1 d1 d2 x =
   let c1 = 1.7320508075688772 in
   let c2 = 0.4330127018922193 in
   let c3 = -0.066987298107780702 in
   let c4 = 0.51763809020504137 in
   let c5 = 1.9318516525781364 in
   let n = Array.length x in
   let odd i = x.(2*i) and even i = x.(2*i + 1) in
   let d1 i = odd i -. c1 *. even i in
   let f = function -1 - n/2 - 1 | i - i in
   let s1 i = even i +. c2 *. d1 i +. c3 *. d1 (f(i-1)) in
   let d2 i = d1 i +. s1 (f(i-1)) in
   let even = Array.init (n/2) (fun i - c4 *. s1 i) in
   if n  2 then d4 s1 d1 d2 even else s1, d1, d2

 but I'm not sure it is correct!

It's not correct, but what you left out is probably low cost.

OCaml is compiled to machine code, right?  And types can be inferred at
compile time, correct?  Well then of course it's faster.  It seems to
me a big help is the ability to fold multiple array operations into a
single loop, which is optimization a dynamically-typed language like
Python can't easily make.  (It'd require are really smart JIT compiler
or some concessions in dynamicity.)


Carl Banks

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


Re: Detecting recursion loops

2006-12-02 Thread Kay Schluehr
Instead of threading a counter ( or an accumulator as for
tail-recursive functions ) you can monitor the behaviour of the mutual
recusive function call using an external stack and wrap the
contributing functions using a decorator s.t. pushing and popping to
and from the stack are pre- and postprocessing steps. Since the
external stack is under your control you can define fine grained limits
and actions.

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


text adventure question

2006-12-02 Thread Ara Kooser
   I am working on a text adventure game for python to get back into
python programming. My version 0.1 used only functions so I could get
familiar with how those work. I want to move beyond that. I am not
sure what would be a good Python way of handling this.  I was
wondering if classes would help? What things should be included in the
main program?

A couple of my goals are:
1) Remove the rooms (or areas) from the main program and have them
called in as needed.
2) Remove NPC's and monsters from the main program and have them
called in as needed.
3) A way of keeping track of time passing in the game
4) Having the main character info stored somewhere else.

Below is pasted a section of my code. Each room is a function that is
later called. I included only one room to keep this short. Thanks you
for suggestions and your time.

Code:

#A sample text adventure game
#Version 0.1
#By Ara Kooser

import random
import sys
import string



#Using global variables for the character
#Want to use a function instead

stre = 9
con = 8
inte = 11
agl = 14
app = 10
mag = 6
sz = 9

hp = 17

reputation = 0

stealth = False

quest1 = False
quest2 = False

cruse = False
poison = False
diseased = False

ducats = 50
lira = 25
florin = 80


equipment = {'Sword': 1, 'Dagger': 1, 'Walking staff': 1, 'Leather Armor':1}
backpack = {'Flint and steel': 1, 'Rations': 7, 'dressing kit': 6,
'waterskin': 2}
belt_pouch = {}

#

day = False

###   Global variables for items   ###

#grass blades in meadow_1
getGrass_m1 = 0
#mushroom in edge_forest1
getMushroom_ef1 = 0
#orc in forest2
aliveOrc = 0



#

# help function that will give you a list of commands
def help():
print look, examine (object), n, w, e, s, take (item)
print climb, stealth, fishing, herbalism, forage, haggle
print field dressing
print wield (object), attack, flee, close, withdraw, maintain
print backpack, belt pouch, cs
print Example: examine book, take ducats, attack orc

def character_sheet():
print \

Name:   Profession:
Social Class:   Race:


Strength
Constitution
Intelligence
Agility
Appearance
Magic
Size

Ducats: Lira:   Florin:

Skills: Forage, Haggle, Stealth, Fishing, Herbalism, Climb, Sword, Staff,
Dagger, Field Dressing

Equipment: Backpack, Belt Pouch, Run of the Mill Sword, Dagger, FlintSteel
1 week food, 2 waterskins, walking stick, dressing kit





def start():
print '''
SAMPLE TEXT ADVENTURE V0.1
   You are the last person to leave the small village of Hommlet. The wooden
gate closes behind you and twilight reaches across the land. A dense mist
creeps up out of the ground, only to be kept at bay by the watchmens torches.
Somewhere deep in the woods lies the foul orcs you have tracked for several
days.

'''

print

def outside1():
global hp
global reputation
print  Current Hit Points = ,hp
print  Current Reputation = ,reputation
print '''   You are outside the town gates. The dirt road heads
(N)orth to another
town several days away. The forest lies (E)ast and (W)est through the
meadows. The
rumors you heard in town describe the orcs as being to the west. The town's gate
is to the (S)outh but it is locked for the night.
Type 'help' for a full list of commands.'''
print
prompt_out1()

def out1_desc():
print '''The fog is growing denser as the sun sets on the meadows.
The exits are (N)orth, (E)ast and (W)est.'''
print
prompt_out1()

def prompt_out1():
global day
prompt_o1 = raw_input(Type a command: ).lower()
try:

if prompt_o1 == help:
help()
print
prompt_out1()

elif prompt_o1 == cs:
character_sheet()
print
prompt_out1()

elif prompt_o1 == status:
print  Current Hit Points = ,hp
print  Current Reputation = ,reputation
prompt_out1()

elif prompt_o1 == backpack:
print backpack
prompt_out1()

elif prompt_o1 == belt pouch:
print belt_pouch
prompt_out1()

elif prompt_o1 == equipment:
print equipment
prompt_out1()


elif prompt_o1 == examine fog:
print The fog seems natural enough for this time of year.
print
prompt_out1()

elif prompt_o1 == examine road:
print '''The road is a 

Re: About alternatives to Matlab

2006-12-02 Thread Carl Banks

Carl Banks wrote:
 Matlab has a few *cough* limitations when it comes to hand-optimizing.
 When writing naive code, Matlab often is faster than Python with numpy
 because it has many commerical man-year of optimizing behind it.
 However, Matlab helps v

That should say:

However, Matlab helps very little when you need to speed things up, or
(especially) use less memory than the naive way.


Carl Banks

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


Re: converting dict to object

2006-12-02 Thread Carl D. Roth
On Fri, 01 Dec 2006 17:48:40 -0800, rieh25 wrote:

 If I have a dictionary such as:
 
 d = {'a' : 1, 'b' : 2}
 
 is there a way to convert it into an object o, such as:
 
 o.a = 1
 o.b = 2

Rather, the question could be asked the other way around: how can you
convert that object into a dict?

The attributes in 'o' are part of its '__dict__' attribute, which is a
dictionary.  That is,

  o.a = 1

is equivalent to

  o.__dict__['a'] = 1

If you already have a dictionary 'd', you can overlay it onto the object's
attributes with

  o.__dict__.update(d)

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


Re: evaluating gui modules, any experience on tkinter?

2006-12-02 Thread David Boddie
krishnakant Mane wrote:

 I seam to have noticed this a bit late but it appears to me that
 tkinter is being used very widely for gui development on all platform?
 is that right?

Tkinter is bundled with Python on all platforms that support Tcl/Tk.
As a result there's a low barrier to entry to Tkinter programming, so
people tend to use it, at least when they start with GUI development.

 3.  I don't know if I need any thing else as dependencies on my
 windows machine.  I am using python24 and I did not find any thing
 about installation in the introduction to tkinter.  can some one give
 me the process of installing tkinter and all necessary things?

It's been a long time since I installed Python on Windows, and I think
I used ActivePython:

  http://www.activestate.com/Products/ActivePython/

I believe that this package includes Tkinter, so you shouldn't have
to do anything else to install it.

 so I am confused between wxpython pyqt and now tkinter.
 out of the 3 I only found qt talking extencively about accessibility,
 but did not find a way to install qt in the first place.  I could not
 compile qt nor did I find any run-time dlls for mingw so that I can
 use it out of the box.

I believe there should be a package which includes pre-built Qt
libraries as well as source code, all licensed under the GNU GPL.
It may not help you get started with MinGW, though the information
on the download page indicates that the package will also download
and install the MinGW compiler, if needed.

Take a look at the following page for more information:

  http://www.trolltech.com/developer/downloads/qt/windows

If you're unable to license your own code under the GNU GPL then
you'll have to look at commercial licenses for Qt and PyQt.

David

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


Re: os.mkdir and mode

2006-12-02 Thread Martin v. Löwis
Nick Craig-Wood schrieb:
 So it looks like python mkdir() is applying the umask where as
 /bin/mkdir doesn't.  From man 2 mkdir

Actually, mkdir(1) has no chance to not apply the umask: it also
has to use mkdir(2), which is implemented in the OS kernel, and
that applies the umask. Try

strace mkdir -m770 test

to see how mkdir solves this problem; the relevant fragment
is this:

umask(0)= 022
mkdir(test, 0770) = 0
chmod(test, 0770) = 0

So it does *both* set the umask to 0, and then apply chmod.

Looking at the source, I see that it invokes umask(0) not to
clear the umask, but to find out what the old value was.
It then invokes chmod to set any special bits (s, t) that
might be specified, as mkdir(2) isn't required (by POSIX spec)
to honor them.

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


Re: Security Descriptor and CoInitializeSecurity

2006-12-02 Thread Roger Upole

Huayang Xia wrote:
 I'd like to call pythoncom.CoInitializeSecurity with a
 PySecurityDescriptor object to set the process-wide security values.
 But I'm not able to find a way to let the code go through.

 I have read MSDN and searched web, I've not been able to find answer. I
 cooked a security descriptor like this (assume aces is a tuple of tuple
 (access, sid) :



sd = win32security.SECURITY_DESCRIPTOR()
sd.Initialize()
sd.SetSecurityDescriptorOwner(sid_owner, False)
sd.SetSecurityDescriptorGroup(sid_group, False)


# create DACL
dacl = win32security.ACL()
dacl.Initialize()
for (access, acc_sid) in aces:
# Add ACE which is access and SID
dacl.AddAccessAllowedAce(win32security.ACL_REVISION, access,
 isinstance(acc_sid, (unicode, str)) and
 win32security.ConvertStringSidToSid(acc_sid) or acc_sid)

sd.SetDacl(True, dacl, False)   # SetSecurityDescriptorDacl
print sd.IsSelfRelative()# result is 1

 The sd is a self relative one.

From MSDN, after calling InitializeSecurityDescriptor, the sd is
 absolute sd, and CoInitializeSecurity needs absolute sd. Pythonwin has
 not wrapped function like 'MakeAbsoluteSD'.

 Has someone ever had same problem. Could you give a hint for solving
 the problem. Thanks.

 Regards

PySECURITY_DESCRIPTOR's are always stored in self-relative format.
They should be converted automatically in the few places that require an
absolute SD, but looks like this one was missed.
Could you file a bug report on SourceForge ?
http://sourceforge.net/projects/pywin32/

  Roger




== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


global name 'self' is not defined

2006-12-02 Thread Evan
Hi

I have a short script that makes 2 calls to methods in another script
as follows:

import canPlaces as canp

callOne=canp.addMe(3,5)
callTwo=canp.estocStn()

The 2 methods in the second script are:

def addMe(a,b)
   sumAb=a+b
   return sumAb

def estocStn():
   estoc={'lat':29.15,'lon':-15.667,'place':'ESTOC'}
   return estoc

Why is it that the first call works fine, but the second tells me
'global name 'self' is not defined'?  What I want is to have the
dictionary 'estoc' available in my calling script.

Thanks, Evan

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


Re: global name 'self' is not defined

2006-12-02 Thread Felipe Almeida Lessa
On 2 Dec 2006 10:42:28 -0800, Evan [EMAIL PROTECTED] wrote:
 Why is it that the first call works fine, but the second tells me
 'global name 'self' is not defined'?  What I want is to have the
 dictionary 'estoc' available in my calling script.

Well, you have not posted the code that is causing the problem,
nowhere in your mail there's a reference to self.


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


Re: global name 'self' is not defined

2006-12-02 Thread George Sakkis
Evan wrote:
 Hi

 I have a short script that makes 2 calls to methods in another script
 as follows:

 import canPlaces as canp

 callOne=canp.addMe(3,5)
 callTwo=canp.estocStn()

 The 2 methods in the second script are:

 def addMe(a,b)
sumAb=a+b
return sumAb

 def estocStn():
estoc={'lat':29.15,'lon':-15.667,'place':'ESTOC'}
return estoc

 Why is it that the first call works fine, but the second tells me
 'global name 'self' is not defined'?  What I want is to have the
 dictionary 'estoc' available in my calling script.

 Thanks, Evan

Please post examples that reproduce the error; what you posted doesn't
even refer to self at all.

George

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


wxpython worked out but can't find api docs for download.

2006-12-02 Thread krishnakant Mane
hello all.
finally I got the accessibility issue out from wxpython.  actually
almost got it out, but that's another story.
now my problem is that I can't gind a downloadable version of wxpython
api reference for the latest version or the latest api reference at
least.
I found the on-line version so please don't provide the same link.
when I opened it on line, it took about 8 minuts to get the wx package
come up on screen with over 600 links.
I need to have some off line reference for the wxpython api.
I have enough documentation to get started but I don't have the
extencive api references for events and other methods, properties and
attributes.
can some one point me to a .zip or .tar.gz version of the api docs for wxpython?
thanking all.
Krishnakant.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python 2.5 install from source problem

2006-12-02 Thread Fabian Braennstroem
Hi Martin,

* Martin v. Löwis [EMAIL PROTECTED] wrote:
 Fabian Braennstroem schrieb:
 I just tried to install python 2.5 from source on my
 ScienticLinux (Redhat Clone) machine. It seems to work
 without any problem, at least I am able to run some of my
 old scripts. I installed it with './configure
 --prefix=/opt/python make make altinstall', but now for a
 'vtk' installation which needs the python libraries I am not
 able to find a file like 'libpython2.5.so.*', which I think
 should be produced (at least at my office's machine (redhat)
 it is there). I just can find a 'libpython2.5.a' file ...
 
 Do I do something wrong?

 I'd say it is a bug in vtk that it requires libpython2.5.so.*.
 However, to work-around, you can configure Python with
 --enable-shared. Make sure to set LD_LIBRARY_PATH or LD_RUN_PATH
 appropriately.

Thanks a lot!


Greetings!
 Fabian

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


Re: PythonTidy

2006-12-02 Thread Chuck Rhode
Thomas Heller wrote this on Fri, Dec 01, 2006 at 10:12:38PM +0100.  My reply is 
below.

 Chuck Rhode schrieb:

  o Command-line args: Please give an example of a standard command that
  I might emulate w.r.t. standard argument use.

 Well, at least it would be nice if I could call
 'PythonTidy.py mymodule.py' to tidy up the mymodule.py file.

I've uploaded a new version of PythonTidy:

o  http://www.lacusveris.com/PythonTidy/PythonTidy-1.4.python  

It fixes several problems.  Also it allows file names as arguments.

 Here is part of a diff before and after running PythonTidy on it:

 start
 -def comptr_setitem(self, index, value):
 -# We override the __setitem__ method of the
 -# POINTER(POINTER(interface)) type, so that the COM
 -# reference count is managed correctly.
 +def comptr_setitem(self, index, value):  # We override the 
 __setitem__ method of the
 + # 
 POINTER(POINTER(interface)) type, so that the COM
 + # reference count is 
 managed correctly.

 Can this be customized?

This problem has been fixed I think.  No customization should be
required to keep block comments from being rendered as in-line
comments.

Wolfgang Grafen reported that PythonTidy crashed in Python-2.4 because
new Abstract Syntax Tree node types introduced in Python-2.5 weren't
available.  It was trivial to check availability, so PythonTidy should
now run in Python-2.4.  However, this has not been thoroughly tested
and is not guaranteed.

PythonTidy can now recode string literals if required, although this
capability is turned off by default.  See RECODE_STRINGS.

Docstrings will henceforward be enclosed in double quotes when
feasible.

-- 
.. Chuck Rhode, Sheboygan, WI, USA
.. Weather:  http://LacusVeris.com/WX
.. 30° — Wind WSW 10 mph — Sky overcast.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: wxpython worked out but can't find api docs for download.

2006-12-02 Thread hg
krishnakant Mane wrote:

 hello all.
 finally I got the accessibility issue out from wxpython.  actually
 almost got it out, but that's another story.
 now my problem is that I can't gind a downloadable version of wxpython
 api reference for the latest version or the latest api reference at
 least.
 I found the on-line version so please don't provide the same link.
 when I opened it on line, it took about 8 minuts to get the wx package
 come up on screen with over 600 links.
 I need to have some off line reference for the wxpython api.
 I have enough documentation to get started but I don't have the
 extencive api references for events and other methods, properties and
 attributes.
 can some one point me to a .zip or .tar.gz version of the api docs for
 wxpython? thanking all.
 Krishnakant.

http://www.wxpython.org/download.php
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: global name 'self' is not defined

2006-12-02 Thread Evan
In answer to the 2 replies, I had no references anywhere to 'self'.  In
order to post my code I rewrote 2 scripts containing just the relevant
parts of the problem; these work.  However, they are identical to my
original code.  So I have deleted the 'old' script2 and renamed the new
one, and no problem.  I don't know why it worked with one and not the
other when they are identical, but I have what I want now.

Thanks for your replies.

-Evan

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


Re: detecting that a SQL db is running

2006-12-02 Thread bill ramsay
On Sat, 02 Dec 2006 07:39:51 GMT, Dennis Lee Bieber
[EMAIL PROTECTED] wrote:

On Sat, 02 Dec 2006 09:02:43 +1300, bill ramsay [EMAIL PROTECTED]
declaimed the following in comp.lang.python:

 Dennis
 
 none of this matters,  all i am trying to find out is whether or not
 the local MSDE is actually running.

   From my reading of your system, you have multiple local MSDE
server processes distributed about, and something on those distributed
systems that causes the initial problem... So I've never been clear of
just where any given application/server process actual resides...

   However, all the tests I've been able to perform on my desktop
indicate that /I/ get time-outs or failure to connect messages within 15
seconds of a connection request when the server process is running.

   I don't get unending lock-ups...


dennis 

it doesn't matter what is causing the lockups,  it's a problem with a
supposedly professionally written application package that I have no
control over.  I am just at this moment trying to deal with the
consequences.

I think that I haave found a way to deal with the issue that I have.

Kind regards

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


Re: evaluating gui modules, any experience on tkinter?

2006-12-02 Thread hg
krishnakant Mane wrote:

 hello all,
 I seam to have noticed this a bit late but it appears to me that
 tkinter is being used very widely for gui development on all platform?
 is that right?
 since fredric lundh has written a very good introduction to tkinter
 (was that just an intro?), I have got keen interest to know the
 following.  may be fredric himself might put some light on these
 points.
 1. I seriously don't intend to start a flame war but does tkinter
 stand up to the standards of heavy gui development?  can I have an
 entire mdi application working fine with tkinter?  I know wxpython can
 do it and I have heard enough about pyqt, but tkinter seams to be very
 rich in gui objects.
 2.  as usual I always look out for accessibility when it comes to gui
 design.  will tkinter be useful for blind people?  I mean, are gui
 apps in tkinter accessible on windows?
 3.  I don't know if I need any thing else as dependencies on my
 windows machine.  I am using python24 and I did not find any thing
 about installation in the introduction to tkinter.  can some one give
 me the process of installing tkinter and all necessary things?
 4. is tkinter absolutely compatible with windows gui?  does it call on
 native api for native look and feel?  in that case I think
 accessibility issue is automatically solved.
 I am looking out gui library for some serious application development.
  one is an erp system and the other is a customer relation management
 system.
 so I am confused between wxpython pyqt and now tkinter.
 out of the 3 I only found qt talking extencively about accessibility,
 but did not find a way to install qt in the first place.  I could not
 compile qt nor did I find any run-time dlls for mingw so that I can
 use it out of the box.
 wxpython is the poorest in documentation and tkinter seams to be best at
 that. please give me some advice.
 thanking all.
 Krishnakant.


Tkinter is fine under *nix and Windows for a large range of applications. I
think it has drawbacks and advantage compared to other toolkits. The major
advantage being bundled with python, and the drawbacks include (I
think) ... look and feel, printing support, imaging, documentation.

Then there are two schools: PyQT and wxPython - both very easy to learn and
production libraries ... I never know whether PyQT is commercial or not
under windows (trollteck changed their QT license I think). 

I strongly suggest looking at wxPython - and start with their demo package
which runs also under *nix and windows.


hg

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


problem occurs with replaced values using fileinput

2006-12-02 Thread Phoe6
Hi All,

I am able to use urlib2 through proxy. I give proxy credentials and use


# Set the Proxy Address
proxy_ip = 10.0.1.1:80

proxy_user = 'senthil_or'
proxy_password_orig='password'
proxy_password = urllib.quote(proxy_password_orig,)

# Setup the Proxy with urllib2

proxy_url = 'http://' + proxy_user + ':' + proxy_password + '@' +
PROXY_IP
#proxy_url = urllib.quote(proxy_url_add)
proxy_support = urllib2.ProxyHandler({http:proxy_url})
opener = urllib2.build_opener(proxy_support,urllib2.HTTPHandler)
urllib2.install_opener(opener)

--
Now, I have decided in my program, I shall give a Configfile.txt to
users who can enter the proxy details and I shall substitute the
details in the script;

#FILE: Configfile.txt
# Provide the Proxy Details
PROXY_IP: 10.0.1.1
PROXY_PORT: 80
PROXY_USER: senthil_or
PROXY_PASSWORD: password

#Config Parsing function.

def configParsed():
Parse the Configfile.txt
configparser = ConfigParser()
configparser.read('ConfigFile.txt')
settings = {}
settings['PROXY_IP'] = configparser.get('PROXY','PROXY_IP')
settings['PROXY_PORT'] =
configparser.get('PROXY','PROXY_PORT').strip()
settings['PROXY_USER'] = configparser.get('PROXY','PROXY_USER')
settings['PROXY_PASSWORD'] =
configparser.get('PROXY','PROXY_PASSWORD')
return settings

Now, in my script I do a replacement of values in the script:

FILE BEFORE Replacement:
# Set the Proxy Address
proxy_ip = PROXY_IP:PROXY_PORT

proxy_user = 'PROXY_USER'
proxy_password_orig='PROXY_PASSWORD'
proxy_password = urllib.quote(proxy_password_orig,)
# Setup the Proxy with urllib2
proxy_url = 'http://' + proxy_user + ':' + proxy_password + '@' +
proxy_ip
#proxy_url = urllib.quote(proxy_url_add)
proxy_support = urllib2.ProxyHandler({http:proxy_url})
opener = urllib2.build_opener(proxy_support,urllib2.HTTPHandler)
urllib2.install_opener(opener)

# Replacing Functions:
def replaceProxy(settings):
'''Replace the Proxy Credential values'''
for k,v in settings.items():
  for line in fileinput.input('src' + os.sep+'file.py',inplace=1):
print line.replace(k,v),
return


The problem, I am facing is, when I use a script to replace certain
variables with config file based values, the urllib2 is failing!! It is
not able to get the correct credentials to open the proxy!
I debuged and derived at the conclusion at there is something wrong
with replaceProxy(settings) function I am using:
1) Either with for k,v in settings.items()
2) OR with fileinput.input and print line.replace(k,v),

The output file with replaced values looks perfectly fine to human
eyes!  I dont know what is happening with automatic replacement of
values which is failing my program.

Has anyone faced this kind of scenario before?
Need your help in solving this.

Thanks,
Senthil

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


Re: converting dict to object

2006-12-02 Thread John Machin
Neil Cerutti wrote:
 On 2006-12-02, Michel Claveau [EMAIL PROTECTED] wrote:
  Hi!
 
  Yes.
 
  But...
 
  Try:d = {'a': 1, 'b': 2, 'def': 123}
 
  Ok, I go out...

 How to convert a list of strings into a list of integers:

  a = ['82', '4', '16']

  ai = [int(i) for i in a]

 Yes.

 But...

 Try:  a = ['82', '4', '16', 'foo']

 Ok, I go out...


Michel was making (part of) a valid point: dictionaries have more
flexibility in choice of keys than objects have in attribute names.
More completely:

Suppose d.keys() produces [one, def, foo bar, 3, 3]

o.one is OK.

o.def is not OK [def is a keyword] but getattr(o, def) still works.

o.foo bar is not OK [foo bar is not a valid identifier] but
getattr(o, foo bar) still works.

o.3 is not OK [3 is not a valid identifier] but getattr(o, 3) still
works.

getattr(o, 3) doesn't work [3 is not a string]; you would have to do
o.__dict__[3] to access the value -- no advantage over keeping it in a
dict.

The OP might consider adding code to the __init__ method to check for
cases where the dictionary key is not a string containing a valid
Python identifier (not a keyword).

Note: I have done a reasonable number of exercises that involved taking
a database table definition or a flat file record definition or the
headings in an XLS worksheet or CSV file and ending up with names for
attributes of Python objects. Various heuristics are necessary of
course to get valid identifers without duplicates, but I've never been
bitten by the keyword problem. I'll have to confess that I wasn't aware
of the problem until the 3rd reading of Michel's message :-)

Any experiences of keyword-bite?

Observation: the keyword module's iskeyword() function gives an easy
check. If one is supporting multiple versions of Python, a more
complicated (overkill?) approach might be desirable: use the latest
version of Python to generate a source file containing the latest
keywords from keyword.kwlist.

Cheers,
John

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


Re: rdf, xmp

2006-12-02 Thread Imbaud Pierre
Andy Dingley a écrit :
 Imbaud Pierre wrote:
 
I have to add access to some XMP data to an existing python
application.
XMP is built on RDF, RDF is built on XML.
 
 
 RDF is _NOT_  built on top of XML. Thinking that it is causes a lot of
 trouble in the architecture of big RDF projects. RDF is a data model,
 not a serialisation. The data model is also a graph (more than XML can
 cope with) and can span multiple documents. It's only RDF/XML that's
 the serialisation of RDF into XML and good architectures start from
 thinking about the RDF data model, not this RDF/XML serialisation.
Granted, I oversimplified, my statement was misleading. I tried to
help unknowledgeable reader understand what it was about.
 
 As to RDF handling, then the usual toolset is Jena (in Java) and
 Redland has a Python binding although Redland is fairly aged now.
 
 I'm unfamiliar with XMP and won't have a chance to look at it until
 Monday. However if XMP is strongly XML like despite claiming to be
 RDF, then you might find that handling a pure XMP problem is quite
 easily done with XML tools.
This was my wild guess: the data model I deal with (XMP data, I mean) is 
hardly more than a bunch of key-value pairs - with control for 
vocabulary, and some typing.
 
 Famously RDF/XML is unprocessable with XSLT if it's sophisticated, but
 quite easy if it's restricted to only a simple XML-like RDF model. XMP
 could well be similar.
Still unclear.
 
Thanks for your help!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: converting dict to object

2006-12-02 Thread Fredrik Lundh
John Machin wrote:

 Any experiences of keyword-bite?

creating or manipulating CSS-styled (X)HTML using an XML binding that 
exposes XML attributes as Python attributes.

(this could be viewed as an unnecessary restriction in the Python 
parser; it wouldn't be too hard to allow reserved words for keyword
argument names and for attribute access; iirc, Jython already does this, 
and Paul Svensson posted a patch for CPython a couple of years ago. 
PEP-time, anyone?)

/F

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


Re: global name 'self' is not defined

2006-12-02 Thread John Machin

Evan wrote:
 In answer to the 2 replies, I had no references anywhere to 'self'.  In
 order to post my code I rewrote 2 scripts containing just the relevant
 parts of the problem; these work.  However, they are identical to my
 original code.

This is (putting it mildly) somewhat difficult to believe. If true, it
would indicate a rather severe bug in Python. Identical as determined
how?

When you ran your original code and it gave an error, Python would have
told you where the error occurred, on which line of which file, as in
the following example:

C:\junkcopy con noself.py
def foo():
   return self
^Z
1 file(s) copied.

C:\junk\python25\python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win
32
Type help, copyright, credits or license for more information.
|  import noself
|  noself.foo()
Traceback (most recent call last):
  File stdin, line 1, in module
  File noself.py, line 2, in foo === location of error-causing
line
return self === contents of error-causing line
NameError: global name 'self' is not defined

And you could have told us that information. No, should. Adding to what
others have already said:

When asking a question about an error message:
(a) Provide code (abbreviated if necessary) that causes the error.
Don't retype it; copy/paste the code that you actually ran.
(b) Show the full traceback and error message. Again, use copy/paste.

 So I have deleted the 'old' script2 and renamed the new
 one, and no problem.  I don't know why it worked with one and not the
 other when they are identical, but I have what I want now.

No problem? Sorry, it just transformed itself. Here is a precise
definition of the transformed problem: I don't know why it worked with
one and not the other.

And what you want now doesn't include enlightenment? Thrashing madly at
problems with a sledgehammer may sometimes (but not always) make them
appear to go away faster than a methodical problem-solving approach
would take, but it's rather a short-tem gain.

HTH,
John

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


Re: Python, PostgreSQL, What next?

2006-12-02 Thread vbgunz
I need to thank you all for your suggestions and recommendations. I am
ultimately aiming to work in Python, PostgreSQL and Django and this
link http://www.sqlalchemy.org/news.myt#item_3 sort of made my day :)

I really appreciate all of your feedback and will go through Fredrik's
links as soon as I get the chance. I thank you all again, I appreciate
it very much!

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


** Listen to Professor FETZER, JONES, JUDY WOOD, whose student was murdered by ACTUAL 911 CRIMINALS

2006-12-02 Thread thermate
LISTEN AND LEARN TO THINK CRITICALLY 

http://mp3.rbnlive.com/Fetzer06.html

http://janedoe0911.tripod.com/

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


Re: python vs java eclipse

2006-12-02 Thread Amir Michail
Hi,

Here's a blog post that is relevant to this discussion:

http://sixthandredriver.typepad.com/river_of_code/2006/01/automated_refac.html

Amir

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


Re: evaluating gui modules, any experience on tkinter?

2006-12-02 Thread Gian Mario Tagliaretti
hg wrote:

 Tkinter is fine under *nix and Windows for a large range of applications.
 I think it has drawbacks and advantage compared to other toolkits. The
 major advantage being bundled with python, and the drawbacks include (I
 think) ... look and feel, printing support, imaging, documentation.

agreed

 Then there are two schools: PyQT and wxPython - 

you completely forgot pygtk. or you didn't want to mention it :)

 both very easy to learn 

I think that pygtk is the easiest

ciao
-- 
Gian Mario Tagliaretti
-- 
http://mail.python.org/mailman/listinfo/python-list


Anyone understand this syntax error?

2006-12-02 Thread Sean Hammond

Anyone understand this?

Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02)
[GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2
Type help, copyright, credits or license for more information.
 def markdown_perl(input):
... Send 'input' (string) to the markdown perl script, and return 
the
...output from markdown (string).
...
...input: a string of markdown-formatted text, including \n's at 
the end
...   of lines, that will be sent to the markdown process.
...
...returns: a string of valid XHTML from markdown
...
... import tempfile
... import commands
... file = tempfile.NamedTemporaryFile()
... file.write(input)
... file.flush()
... return commands.getoutput('./markdown.pl '+file.name)
   File stdin, line 15
 return commands.getoutput('./markdown.pl '+file.name)
 ^
SyntaxError: invalid syntax


I don't get it. Syntax seems fine to me, just a normal string 
concatenation.

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


Re: Joining data from three different files to be written into three Columns

2006-12-02 Thread Dawn Abbott

On 11/29/06, Dawn Abbott [EMAIL PROTECTED] wrote:


I have three files of binary data.  I want to write the three binary data
files to one file.  I want the old files to each have their own column in
the new file.  This is what I have,

f=open('relative_x.INT32','rb')
a=array('l')
a.fromfile(f,10)
g=open('relative_y.INT32','rb')
b=array('l')
b.fromfile(g,10)
data=zip(a,b)
for datum in data:
...print ' '.join(datum)
...


the error I get is expected string, found int
I figure that the joint is for strings only does anyone know of a way were
I could join the data that would be for ints.
Thanks
Dawn


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

Re: Anyone understand this syntax error?

2006-12-02 Thread John Machin

Sean Hammond wrote:
 Anyone understand this?

 Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02)
 [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2
 Type help, copyright, credits or license for more information.
  def markdown_perl(input):
 ... Send 'input' (string) to the markdown perl script, and return
 the
 ...output from markdown (string).
 ...
 ...input: a string of markdown-formatted text, including \n's at
 the end
 ...   of lines, that will be sent to the markdown process.
 ...
 ...returns: a string of valid XHTML from markdown
 ...
 ... import tempfile
 ... import commands
 ... file = tempfile.NamedTemporaryFile()
 ... file.write(input)
 ... file.flush()
 ... return commands.getoutput('./markdown.pl '+file.name)
File stdin, line 15
  return commands.getoutput('./markdown.pl '+file.name)
  ^
 SyntaxError: invalid syntax
 

 I don't get it. Syntax seems fine to me, just a normal string
 concatenation.

Superficially there is nothing wrong with it. After saving that to a
file and doing the editing necessary to change it from a screen dump to
a script, it loads OK on windows with Python 2.4.3 and 2.5.

It is probably not complaining about the string concatenation. The
caret is positioned at the start of the statement; this would indicate
that the problem is on an earlier line. There was a while back a
strange error that only manifested itself in very large source files
(e.g. those generated by the pywin32 package's makepy routine) and
could be cured by adding trailing spaces to the line before the
allegedly offending line. However that seems to have gone away.

My guess is that the problem is something to do with tabs/spaces or you
have some other invisible character at the start of the return
statement. As the text has been through two mail or news clients, the
problem may have been munged away and I'm not seeing it.

Two sugggestions:
(1) at an interactive prompt:

print repr(open(yourfile.py).readlines())

and eyeball the last few lines for monkey business.

(2) e-mail somebody (like me) a zipped (i.e. e-mail-munging-proof) copy
of your file.

Two other comments on your code:
(1) It's not wise to use file as a variable name; it shadows the
built-in file(). Not a problem in this code but it's a bad habit that
could bite you later.
(2) Any good reason for flushing the file instead of closing it?

HTH,
John

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


Re: Possible to assure no cyclic/uncollectible memory leaks?

2006-12-02 Thread Klaas
Joe Peterson wrote:
 I've been doing a lot of searching on the topic of one of Python's more
 disturbing issues (at least to me): the fact that if a __del__ finalizer
 is defined and a cyclic (circular) reference is made, the garbage
 collector cannot clean it up.

It is a somewhat fundamental limitation of GCs, if you want to support:

1. __del__ that can resurrect objects and is deterministically called
when objects are destroyed
2. the view of alive objects by __del__ methods is consistent
3. no crashing

If there is a cycle of objects containing __del__ methods, there is
clearly no way of knowing a safe order of invoking them.

 First of all, it seems that it's best to avoid using __del__.  So far, I
 have never used it in my Python programming.  So I am safe there.  Or am
 I?  Also, to my knowledge, I have never created a cyclic reference, but
 we do not typically create bugs intentionally either (and there are
 certainly times when it is an OK thing to do).

It is good practice to avoid __del__ unless there is a compelling
reason to do so.  weakref resource management is much safer.  Note that
it is pretty much impossible to avoid creating reference cycles--they
have a tendency to sneak into unsuspecting places (for instance, bound
methods can be a subtle source of cycles).

 Still, it's not comforting to know that it is possible to create a
 situation that would create a memory leak using a language that is
 supposed to relieve us of that worry.  I understand the problem, but it
 would be nice to know that as a programmer, I could be assured that
 Python would always deal with memory management and that memory leaks
 were not something I had to think about.

It is unrealistic to ever be completely relieved of such worry, since
it is always possible to accidently hold on to a strong reference to
data that should actually be garbage.  But your question is perhaps
precluding these kinds of memory leak.  In that case, it is a matter of
providing to the programmer sufficiently-fine-grained abstractions such
that the compiler can reason about their safety.  For instance, an
included weakref-based resource cleanup scheme has been discussed and
would cover many of the current uses of __del__.  It would also be nice
to remove some of the hidden gotchas that are inherent in CPython,
like the integer and float object freelist (not necessarily removing
those features, but providing some mechanism for reclaiming them when
they get out of hand).

These things can reduce the possibility of a problem, but (IMO) can
never completely obviate it.

 So here's a question: if I write Python software and never use __del__,
 can I guarantee that there is no way to create a memory leak?  What
 about system libraries - do any of them use __del__, and if so, are they
 written in such a way that it is not possible to create a cyclic reference?

It is always possible to create a cyclic reference by monkeypatching a
class.  Here are the stdlib modules which use __del__:
$ find -name \*.py | xargs grep __del__ | grep -v test
./Mac/Demo/sound/morselib.py:def __del__(self):
./Lib/telnetlib.py:def __del__(self):
./Lib/plat-mac/EasyDialogs.py:def __del__(self):
./Lib/plat-mac/FrameWork.py:def __del__(self):
./Lib/plat-mac/MiniAEFrame.py:def __del__(self):
./Lib/plat-mac/Audio_mac.py:def __del__(self):
./Lib/plat-mac/videoreader.py:def __del__(self):
./Lib/fileinput.py:def __del__(self):
./Lib/subprocess.py:def __del__(self):
./Lib/gzip.py:def __del__(self):
./Lib/wave.py:def __del__(self):
./Lib/wave.py:def __del__(self):
./Lib/popen2.py:def __del__(self):
./Lib/lib-tk/Tkdnd.py:def __del__(self):
./Lib/lib-tk/tkFont.py:def __del__(self):
./Lib/lib-tk/Tkinter.py:def __del__(self):
./Lib/lib-tk/Tkinter.py:def __del__(self):
./Lib/urllib.py:def __del__(self):
./Lib/tempfile.py:# __del__ is called.
./Lib/tempfile.py:def __del__(self):
./Lib/tarfile.py:def __del__(self):
./Lib/socket.py:def __del__(self):
./Lib/zipfile.py:fp = None   # Set here since
__del__ checks it
./Lib/zipfile.py:def __del__(self):
./Lib/httplib.py:def __del__(self):
./Lib/bsddb/dbshelve.py:def __del__(self):
./Lib/bsddb/dbshelve.py:def __del__(self):
./Lib/bsddb/__init__.py:def __del__(self):
./Lib/bsddb/dbtables.py:def __del__(self):
./Lib/idlelib/MultiCall.py:def __del__(self):
./Lib/idlelib/MultiCall.py:def __del__(self):
./Lib/idlelib/MultiCall.py:def __del__(self):
./Lib/sunau.py:def __del__(self):
./Lib/sunau.py:def __del__(self):
./Lib/poplib.py:#__del__ = quit
./Lib/_threading_local.py:def __del__(self):
./Lib/aifc.py:def __del__(self):
./Lib/dumbdbm.py:# gets called.  One place _commit() gets called is
from __del__(),
./Lib/dumbdbm.py:# be called from __del__().  Therefore we must
never reference a
./Lib/dumbdbm.py:__del__ = close
./Lib/wsgiref/validate.py:def 

Re: global name 'self' is not defined

2006-12-02 Thread Bjoern Schliessmann
Evan wrote:

 So I have deleted the 'old' script2 and renamed the new one, and
 no problem.

Pity. Next time try using diff (or something similar).

Regards,


Björn

-- 
BOFH excuse #115:

your keyboard's space bar is generating spurious keycodes.

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


Re: converting dict to object

2006-12-02 Thread Steven D'Aprano
On Sat, 02 Dec 2006 12:16:24 -0800, John Machin wrote:

 The OP might consider adding code to the __init__ method to check for
 cases where the dictionary key is not a string containing a valid
 Python identifier (not a keyword).

If the OP is doing something like this:

attributes = {length: 15, id: 2345}
# attribute names are known at compile time, created by the coder
obj.__dict__.update(attributes)
print obj.length
print obj.id

then checking that length and id are valid identifiers is hardly
necessary, any more than this would be:

class Spam:
def __init__(self, length, id):
check_valid_indentifier(length)
self.length = length
check_valid_indentifier(id)
self.id = id


But if he's doing something like this:

attributes = fetch_user_dict()
# attribute names aren't known until runtime
obj.__dict__.update(attributes)
for key in attributes:
print getattr(obj, key)

then it is also redundant to check for valid identifiers, since getattr()
doesn't need them. However, one might still need to test for accidental
clashes with pre-existing object attributes.

On the third hand, if that's the case then there seems to be no real
advantage to converting the dict into object attributes. Why not just
delegate to a saved copy of the dict?

class Spam:
def __init__(self, d):
self._d = d
def __getitem__(self, key):
return self._d[key]
def __setitem__(self, key, value):
self._d[key] = value

s = Spam({a: 1, something else: 2})
s[a]
s[something else]




-- 
Steven.

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


Re: converting dict to object

2006-12-02 Thread John Machin

Steven D'Aprano wrote:
 On Sat, 02 Dec 2006 12:16:24 -0800, John Machin wrote:

  The OP might consider adding code to the __init__ method to check for
  cases where the dictionary key is not a string containing a valid
  Python identifier (not a keyword).

[snip]
 But if he's doing something like this:

 attributes = fetch_user_dict()
 # attribute names aren't known until runtime
 obj.__dict__.update(attributes)
 for key in attributes:
 print getattr(obj, key)

 then it is also redundant to check for valid identifiers, since getattr()
 doesn't need them.

but getattr() needs strings.

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


Re: converting dict to object

2006-12-02 Thread Steven D'Aprano
On Sat, 02 Dec 2006 17:00:15 -0800, John Machin wrote:

 
 Steven D'Aprano wrote:
 On Sat, 02 Dec 2006 12:16:24 -0800, John Machin wrote:

  The OP might consider adding code to the __init__ method to check for
  cases where the dictionary key is not a string containing a valid
  Python identifier (not a keyword).

 [snip]
 But if he's doing something like this:

 attributes = fetch_user_dict()
 # attribute names aren't known until runtime
 obj.__dict__.update(attributes)
 for key in attributes:
 print getattr(obj, key)

 then it is also redundant to check for valid identifiers, since getattr()
 doesn't need them.
 
 but getattr() needs strings.

Well, that's true, but if the dict is being read from a file or with
raw_input, the keys will naturally be strings. But even if it is some
arbitrary dict, the keys still don't need to be checked for valid
identifiers, merely checked for strings. And again, keeping the
keys/values in a dict instead of converting to object attributes naturally
solves that problem -- or rather, it isn't a problem that needs to be
solved.

Either way, I see no advantage to taking an arbitrary dict and converting
it into object attributes. It sounds to me like when the only tool you
have is Java, everything looks like an object attribute coding :-)

I'd suggest that the right answer to the OP's original question How
do I convert a dict to object attributes? is Don't do that, regardless
that it is technically possible.

Maybe I'm wrong and there are lots of really handy uses for such a tactic.
Can anyone suggest any?



-- 
Steven.

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


Re: converting dict to object

2006-12-02 Thread Neil Cerutti
On 2006-12-02, John Machin [EMAIL PROTECTED] wrote:
 Neil Cerutti wrote:
 On 2006-12-02, Michel Claveau [EMAIL PROTECTED] wrote:
  Hi!
 
  Yes.
 
  But...
 
  Try:d = {'a': 1, 'b': 2, 'def': 123}
 
  Ok, I go out...

 How to convert a list of strings into a list of integers:

  a = ['82', '4', '16']

  ai = [int(i) for i in a]

 Yes.

 But...

 Try:  a = ['82', '4', '16', 'foo']

 Ok, I go out...

 Michel was making (part of) a valid point: dictionaries have
 more flexibility in choice of keys than objects have in
 attribute names.  More completely:

 Suppose d.keys() produces [one, def, foo bar, 3, 3]

 o.one is OK.

I made the assumption that Michael was also the original poster,
and had somehow laid a clever trap. If I was wrong about that, my
apologies. It's one thing to ask how to convert 'a' and 'b' to
attributes, but quite another to convert arbitrary text.

 The OP might consider adding code to the __init__ method to
 check for cases where the dictionary key is not a string
 containing a valid Python identifier (not a keyword).

That raises the interesting question of what to do in that case.
Just letting an error occur might be perfectly good behavior.
Plus, I didn't know about...

 Observation: the keyword module's iskeyword() function gives an
 easy check. If one is supporting multiple versions of Python, a
 more complicated (overkill?) approach might be desirable: use
 the latest version of Python to generate a source file
 containing the latest keywords from keyword.kwlist.

Thanks for the pointer to keyword module. I hadn't noticed it
yet.

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


Re: text adventure question

2006-12-02 Thread Neil Cerutti
On 2006-12-02, Ara Kooser [EMAIL PROTECTED] wrote:
 I am working on a text adventure game for python to get back
 into python programming. My version 0.1 used only functions so
 I could get familiar with how those work. I want to move beyond
 that. I am not sure what would be a good Python way of handling
 this.  I was wondering if classes would help? What things
 should be included in the main program?

The language used by the Infocom implementors was called ZIL, and
it so happens that the ZIL manual is available for download.
It was sort of a wimpy version of Lisp.

   http://www.mv.com/ipusers/xlisper/zil.pdf

Anyway, the ZIL manual explains how Infocom's library for text
adventures worked.  That should be inspirational for your design.
It's also an entertaining historical artifact, if the history of
computer games is your thing. Here's an amusing sampling:

  EXERCISE THREE
  Design and implement a full-size game. Submit it to testing,
  fix all resulting bugs, help marketing design a package, ship
  the game, and sell at lest 250,000 units.

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


Re: converting dict to object

2006-12-02 Thread John Machin

Neil Cerutti wrote:


 Thanks for the pointer to keyword module. I hadn't noticed it
 yet.

Bonus: you got an extremely fresh, scarcely used pointer -- I wasn't
aware of it myself till today :-)

Cheers,
John

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


Re: text adventure question

2006-12-02 Thread Steven D'Aprano
On Sat, 02 Dec 2006 10:22:28 -0700, Ara Kooser wrote:

I am working on a text adventure game for python to get back into
 python programming. My version 0.1 used only functions so I could get
 familiar with how those work. I want to move beyond that. I am not
 sure what would be a good Python way of handling this.  I was
 wondering if classes would help? What things should be included in the
 main program?

Think about nouns and verbs. Verbs, doing words, are functions and
methods. Nouns, things, are classes and objects. You should model nouns
in your game with classes and objects, and verbs (actions) with functions
and methods.

Here is a simple example: a room. A room is a thing. So we might define a
room like this:


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

Now we create a new room, and fill it:

bedroom = Room(King's Bedroom)
bedroom.description = You are in a fancy bedroom.
self.contents.append(crown)

Now we create a function for looking around:

def look(here):
Look around the place you are in
print here.description

And when you are in the King's bedroom, you (the programmer) would call
the look function like this:

look(bedroom)


But look above: I said that the King's bedroom contains a crown, using
only a built-in object (str). Maybe that's all you need. Or perhaps you
need something more fancy:

class Object:
# note: not object, lower case, as that is a built-in type
def __init__(self, name, value, description):
self.name = name
self.value = value
self.description = description


crown = Object(King's crown, 15000, a gold crown with many jewels)
scepter = Object(King's scepter, 1, a silver scepter)
vorpel_sword = Object(vorpel sword, 200, a strange looking sword)
bedpan = Object(bedpan, 3, a smelly metal bowl)


Now you can write a function to look at any object:

def look_at(something):
print something.description


and it will work for both objects and rooms.

Let's put some more things in the King's bedroom:

bedroom.contents.extend([crown, bedpan, vorpel_sword, scepter])

Rooms also need doors:

bedroom.north = wall
bedroom.south = wall
bedroom.west = wall
bedroom.east = Room(corridor) # a corridor is just a long, empty room

Perhaps that's not the best way to do it, because now the King's bedroom
has an exit into the corridor, but the corridor has no exit into the
bedroom! Perhaps you need to think about a better way to map the world.
But for now, we can make a really simple fix for that:

corridor = bedroom.east
corridor.west = bedroom
corridor.north = wall
corridor.south = wall
corridor.east = Room('kitchen')

Hmmm... we're doing a lot of unnecessary typing here. Better to create
rooms with four walls already! Go back and change the definition of a room:

class Room:
def __init__(self, name):
self.name = name
self.north = wall
self.south = wall
self.east = wall
self.west = wall


and now you only need to change the directions that AREN'T walls.


Now you have defined the rooms and objects in your text adventure. You
should do something similar for monsters, and any other thing in the game.
Then create functions for verbs:

def fight(what):
if type(what) == Room:
print Mindlessly attacking the room doesn't  \
accomplish anything except bruising your fists.
elif type(what) == Object:
print My, you have a bad temper. You pummel the object.  \
It doesn't notice.
elif type(what) == Monster:
fight_monster()  # you have to write this function
elif type(what) == Royalty:
print You try to punch the King. His bodyguards leap  \
out from the shadows and kick the bejeebus out of you,  \ 
then drag you into the deepest dungeon. You have a long, \
long LONG time to consider what you did wrong as the rats  \
nibble at your toes.
end_game()
 else:
print You don't know how to fight, what


def say(words, what):
Say words to what.
if poot in words:
print Do you kiss your mommy with that potty-mouth?

if type(what) == Room:
print The room doesn't answer.
elif type(what) == Monster:
print The monster doesn't understand English.
# and you can write the rest


One suggested improvement: if you find yourself writing lots of code like
the above, testing if type(what) == Room etc., there is a better way of
doing it. Move that block of code into a method of Room:

class Room:
# def __init__ stays the same as before
def hears(words):
The player says words to the Room, and the Room responds.
print The room doesn't answer.

and then your function becomes much simpler:

def say(words, what):
Say words to what.
if poot in words:
print Do you kiss your mommy with that potty-mouth?
else:
# the player talks, so what hears and responds.
what.hears(words)


There is more that you can do 

RE: python vs java eclipse

2006-12-02 Thread Sells, Fred
If you're in the PyDev perspective, F9 runs the current script while
ctrl-F11 reruns the last script run.  I have found that certain types of
operations just plain don't work this way and must be run from a
conventional shell window.

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
Behalf Of krishnakant Mane
Sent: Friday, December 01, 2006 6:19 AM
To: python-list@python.org
Subject: Re: python vs java eclipse


just used the py dev plugin for eclipse.
it is great.
auto indentation and intellisence.
and all other things.
so now how does it look from this end?
python + productivity and eclipse + productivity = double productivity!
only problem with the plugin is that I find it difficult to manage the
script running.
I open a command prompt and run the scripts manually.
any suggestion for this.
for example I had name = raw_input(please enter your name) and the
moment I type the first letter on the keyboard the code execution
moves over to the next statement.  should it not wait for the return
key as it always does?
Krishnakant.
-- 
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: text adventure question

2006-12-02 Thread [EMAIL PROTECTED]
 When I was playing around with adventure games using oop (in c++)
I had all charecters defined as a type, no need to seperate non-player
charecters with user defined charecters.  Makes it easier to create a
party of charecters or monsters.  I left it up to the logic of the
program to define behavior after it was loaded in.

http://www.stormpages.com/edexter/csound.html


Ara Kooser wrote:
 I am working on a text adventure game for python to get back into
 python programming. My version 0.1 used only functions so I could get
 familiar with how those work. I want to move beyond that. I am not
 sure what would be a good Python way of handling this.  I was
 wondering if classes would help? What things should be included in the
 main program?

 A couple of my goals are:
 1) Remove the rooms (or areas) from the main program and have them
 called in as needed.
 2) Remove NPC's and monsters from the main program and have them
 called in as needed.
 3) A way of keeping track of time passing in the game
 4) Having the main character info stored somewhere else.

 Below is pasted a section of my code. Each room is a function that is
 later called. I included only one room to keep this short. Thanks you
 for suggestions and your time.

 Code:

 #A sample text adventure game
 #Version 0.1
 #By Ara Kooser

 import random
 import sys
 import string



 #Using global variables for the character
 #Want to use a function instead

 stre = 9
 con = 8
 inte = 11
 agl = 14
 app = 10
 mag = 6
 sz = 9

 hp = 17

 reputation = 0

 stealth = False

 quest1 = False
 quest2 = False

 cruse = False
 poison = False
 diseased = False

 ducats = 50
 lira = 25
 florin = 80


 equipment = {'Sword': 1, 'Dagger': 1, 'Walking staff': 1, 'Leather Armor':1}
 backpack = {'Flint and steel': 1, 'Rations': 7, 'dressing kit': 6,
 'waterskin': 2}
 belt_pouch = {}

 #

 day = False

 ###   Global variables for items   ###

 #grass blades in meadow_1
 getGrass_m1 = 0
 #mushroom in edge_forest1
 getMushroom_ef1 = 0
 #orc in forest2
 aliveOrc = 0



 #

 # help function that will give you a list of commands
 def help():
 print look, examine (object), n, w, e, s, take (item)
 print climb, stealth, fishing, herbalism, forage, haggle
 print field dressing
 print wield (object), attack, flee, close, withdraw, maintain
 print backpack, belt pouch, cs
 print Example: examine book, take ducats, attack orc

 def character_sheet():
 print \
 
 Name:   Profession:
 Social Class:   Race:

 
 Strength
 Constitution
 Intelligence
 Agility
 Appearance
 Magic
 Size
 
 Ducats: Lira:   Florin:

 Skills: Forage, Haggle, Stealth, Fishing, Herbalism, Climb, Sword, Staff,
 Dagger, Field Dressing

 Equipment: Backpack, Belt Pouch, Run of the Mill Sword, Dagger, FlintSteel
 1 week food, 2 waterskins, walking stick, dressing kit
 
 



 def start():
 print '''
 SAMPLE TEXT ADVENTURE V0.1
You are the last person to leave the small village of Hommlet. The wooden
 gate closes behind you and twilight reaches across the land. A dense mist
 creeps up out of the ground, only to be kept at bay by the watchmens torches.
 Somewhere deep in the woods lies the foul orcs you have tracked for several
 days.

 '''

 print

 def outside1():
 global hp
 global reputation
 print  Current Hit Points = ,hp
 print  Current Reputation = ,reputation
 print '''   You are outside the town gates. The dirt road heads
 (N)orth to another
 town several days away. The forest lies (E)ast and (W)est through the
 meadows. The
 rumors you heard in town describe the orcs as being to the west. The town's 
 gate
 is to the (S)outh but it is locked for the night.
 Type 'help' for a full list of commands.'''
 print
 prompt_out1()

 def out1_desc():
 print '''The fog is growing denser as the sun sets on the meadows.
 The exits are (N)orth, (E)ast and (W)est.'''
 print
 prompt_out1()

 def prompt_out1():
 global day
 prompt_o1 = raw_input(Type a command: ).lower()
 try:

 if prompt_o1 == help:
 help()
 print
 prompt_out1()

 elif prompt_o1 == cs:
 character_sheet()
 print
 prompt_out1()

 elif prompt_o1 == status:
 print  Current Hit Points = ,hp
 print  Current Reputation = ,reputation
 prompt_out1()

 elif prompt_o1 == backpack:
 print backpack
  

Non-exhaustive file reads

2006-12-02 Thread Fredrik Tolf
I just got shocked to find out the hard way that the read() method on
Python's file objects will, very much unlike the C read() function, read
until the given size is reached, which is quite a problem for me when
selecting a couple of pipes and wanting to just read the available data
from them.

The only hint I can find for avoiding this behavior is from
file.read.__doc__, which says that it doesn't do that in non-blocking
mode, but nowhere can I find any information about how to enable
non-blocking mode in Python.

Can anyone provide me with any information on how to accomplish this?

Regards,
Fredrik Tolf


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


Re: Non-exhaustive file reads

2006-12-02 Thread Paul Rubin
Fredrik Tolf [EMAIL PROTECTED] writes:
 mode, but nowhere can I find any information about how to enable
 non-blocking mode in Python.
 
 Can anyone provide me with any information on how to accomplish this?

In Linux you'd use fcntl.  Some other discussion can be found on the
web:

http://www.google.com/search?q=python+non-blocking+mode
-- 
http://mail.python.org/mailman/listinfo/python-list


Parsing data from pyserial

2006-12-02 Thread Lone Wolf
I'm trying to get data through my serial port from a CMUcam.
This gizmo tracks a color and returns a packet of data. The
packet has nine data points (well, really eight since the first
point is just a packet header) separated by spaces as follows: M
xxx xxx xxx xxx xxx xxx xxx xxx

Here is the code I am using (python v24):

import serial

ser=serial.Serial('com1',baudrate=115200, bytesize=8,
parity='N', stopbits=1,xonxoff=0, timeout=1)

ser.write(PM 1) #This sets the CMUcam to poll mode

for i in range(0,100,1):
ser.write(TC 016 240 100 240 016 240\r\n)
reading = ser.read(40)
print reading
components = reading.split()
print components
ser.close

Here is an example output: 

M 37 79 3 4 59 124 86 25
['59', '123', '87', '25', 'M', '37', '79', '3', '4', '59',
'124', '86', '25', 'M
']
M 38 77 3 2 59 124 86 25
['39', '85', '26', 'M', '38', '77', '3', '2', '59', '124', '86',
'25', 'M', '38'
, '7']

My problem is that I am trying to get each data point of the
packet into a separate variable. Ordinarily, this would be easy,
as I would just parse the packet, read the array and assign each
element to a variable eg. mx = components[1]. However, that
doesn't work here because the original packet and the array that
I got from using the split() method are different. If I were to
try read the array created in the first example output, mx would
be 123 instead of 37 like it is in the packet. In the second
example, the array is 85 while the packet is 38.

As near as I can figure out, pyserial is reading a stream of
data and helpfully rearranging it so that it fits the original
packet format M xxx xxx xxx xxx xxx xxx xxx xxx. I would have
thought the split() method that I used on original packet (ie
the reading variable) would have just returned an array with
nine elements like the packet has. This is not the case, and I
am at a loss about how to fix this.  

I've searched the archive here and elsewhere with no luck. Any
help REALLY appreciated!

Wolf :)


Get your own 800 number
Voicemail, fax, email, and a lot more
http://www.ureach.com/reg/tag
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Non-exhaustive file reads

2006-12-02 Thread Fredrik Tolf
On Sat, 2006-12-02 at 20:00 -0800, Paul Rubin wrote:
 Fredrik Tolf [EMAIL PROTECTED] writes:
  mode, but nowhere can I find any information about how to enable
  non-blocking mode in Python.
  
  Can anyone provide me with any information on how to accomplish this?
 
 In Linux you'd use fcntl.  Some other discussion can be found on the
 web:

I was looking for os.fcntl() without finding it, but now that you
reassured me, I found the fcntl module instead.

However, I also found os.read() in the process, which might be a better
alternative (since I can just use it normally like in C without setting
extra fd flags or anything).

Thanks!

Fredrik Tolf


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


python + database book

2006-12-02 Thread progman
new to python.
i work with db heavily.

any good  book for python + database?

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


Re: About alternatives to Matlab

2006-12-02 Thread Jon Harrop
Carl Banks wrote:
 No, they're never redefined (even in the recursive version).  Slices of
 them are reassigned.  That's a big difference.

I see.

 (Actually, it does create a temporary array to store the intermediate
 result, but that array does not get bound to odd.)

Sure.

 In particular, I think you are eagerly
 allocating arrays when, in a functional language, you could just as
 easily compose closures.
 
 You are completely wrong.

I'll give an example. If you write the Python:

  a[:] = b[:] + c[:] + d[:]

I think that is equivalent to the ML:

  fill a (map2 ( + ) (map2 ( + ) b c) d)

which can be deforested in ML to avoid the creation of the intermediate
result b[:] + c[:] by using a closure to add three values at once:

  fill a (map3 (fun b c d - b + c + d) b c d)

which will be much faster because it doesn't generate an intermediate array.

 This data sharing more or less accomplishes the same thing that the
 closures you speak of accomplish (in this case), only without the
 functional.

The closure avoided the intermediate result. You said that the Python isn't
doing that?

 It's not correct, but what you left out is probably low cost.
 
 OCaml is compiled to machine code, right?

Yes.

 And types can be inferred at compile time, correct?

Types are completely inferred at compile time.

 Well then of course it's faster.

Yes. So this doesn't seem to be a killer example of numpy, although I am
still amazed that it can outperform Matlab.

 It seems to  
 me a big help is the ability to fold multiple array operations into a
 single loop, which is optimization a dynamically-typed language like
 Python can't easily make.  (It'd require are really smart JIT compiler
 or some concessions in dynamicity.)

Writing a JIT to compile this kind of stuff is easy. My point is that this
is fundamentally bad code, so why bother trying to write a Python JIT? Why
not just write in a better language for this task? Optimising within a
fundamentally slow language seems silly to me.

-- 
Dr Jon D Harrop, Flying Frog Consultancy
Objective CAML for Scientists
http://www.ffconsultancy.com/products/ocaml_for_scientists
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: v2.3, 2.4, and 2.5's GUI is slow for me

2006-12-02 Thread Tim Roberts
g4rlik [EMAIL PROTECTED] wrote:

No one can help?  This is seriously bugging me to no end.

You waited 2 hours before posting this reply.  Please note that Usenet is
NOT a real-time medium.  It can take half a day or more before your posting
makes it to all the news servers around the world, and much longer before
people actually download the message to their local reader, then an equal
amount of time for replies to get back to you.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza  Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: text adventure question

2006-12-02 Thread Steven D'Aprano
On Sat, 02 Dec 2006 22:19:53 +, Dennis Lee Bieber wrote:

   Suggest you try to go back and reread some of the responses to such
 a subject from whenever (Unfortunately, I suspect my responses are no
 longer available as I run with x-noarchive active).

That seems horribly anti-social, not to mention counter-productive. What's
the point of writing to the newsgroup if your response won't be around by
the time they go to read it? After all, what's the point of treating a
newsgroup like comp.lang.python as a chat group?



-- 
Steven.

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


Re: Parsing data from pyserial

2006-12-02 Thread John Machin
Lone Wolf wrote:
 I'm trying to get data through my serial port from a CMUcam.
 This gizmo tracks a color and returns a packet of data. The
 packet has nine data points (well, really eight since the first
 point is just a packet header) separated by spaces as follows: M
 xxx xxx xxx xxx xxx xxx xxx xxx

 Here is the code I am using (python v24):

 import serial

 ser=serial.Serial('com1',baudrate=115200, bytesize=8,
 parity='N', stopbits=1,xonxoff=0, timeout=1)

 ser.write(PM 1) #This sets the CMUcam to poll mode

 for i in range(0,100,1):
   ser.write(TC 016 240 100 240 016 240\r\n)
   reading = ser.read(40)

You are asking for 40 bytes of data. You will get 40 bytes of data.

However your packets are (presumably) variable length, (presumably)
terminated by CR and/or LF. What does the documentation for the device
tell you?

   print reading

What you see from the print statement is not necessarily what you've
got.
Change that to print repr(reading) and show us what you then see.

   components = reading.split()
   print components
 ser.close

 Here is an example output:

 M 37 79 3 4 59 124 86 25
 ['59', '123', '87', '25', 'M', '37', '79', '3', '4', '59',
 '124', '86', '25', 'M
 ']
 M 38 77 3 2 59 124 86 25
 ['39', '85', '26', 'M', '38', '77', '3', '2', '59', '124', '86',
 '25', 'M', '38'
 , '7']


Let's try to reconstruct reading:

|  a =  ['59', '123', '87', '25', 'M', '37', '79', '3', '4', '59',
| ... '124', '86', '25', 'M']
|  astrg = ' '.join(a)
|  astrg
| '59 123 87 25 M 37 79 3 4 59 124 86 25 M'
|  len(astrg)
| 39  ooh! almost 40!!
|  b =  ['39', '85', '26', 'M', '38', '77', '3', '2', '59', '124',
'86',
| ... '25', 'M', '38'
| ... , '7']
|  bstrg = ' '.join(b)
|   bstrg
| '39 85 26 M 38 77 3 2 59 124 86 25 M 38 7'
|  len(bstrg)
| 40  ooh! exactly 40!!!

My guess: the device is pumping out packets faster than you can handle
them. So you are getting 40-byte snatches of bytes. A snatch is long
enough to cover a whole packet with possible fragments of packets at
each end. You will need to discard the fragments. If you need all the
data, you'd better get some help on how to implement flow control --
I've never used pyserial and I'm not going to read _all_ the docs for
you :-)

I'm very interested to see what print repr(reading) actually shows. I'm
strongly suspecting there is a CR (no LF) at the end of each packet; in
the two cases shown, this would cause the print reading to appear as
only one packet ... think about it: carriage return, with no linefeed,
would cause overwriting. It is a coincidence with those two samples
that the first part of the line doesn't appear strange, with a 4, 5, or
6-digit number showing up where the trailing fragment ends


 My problem is that I am trying to get each data point of the
 packet into a separate variable. Ordinarily, this would be easy,
 as I would just parse the packet, read the array and assign each
 element to a variable eg. mx = components[1].

better would be:

mx, foo, bar, .., eighth_vbl = components[start:start + 8]
once you have worked out what start should be, e.g. start =
components.index('M') + 1

 However, that
 doesn't work here because the original packet and the array that
 I got from using the split() method are different. If I were to
 try read the array created in the first example output, mx would
 be 123 instead of 37 like it is in the packet. In the second
 example, the array is 85 while the packet is 38.

 As near as I can figure out, pyserial is reading a stream of
 data and helpfully rearranging it so that it fits the original
 packet format M xxx xxx xxx xxx xxx xxx xxx xxx.

How, if you've read the docstring for the Serial.read() method, did you
come to that conclusion?

pyserial knows nothing about your packet format.

 I would have
 thought the split() method that I used on original packet (ie
 the reading variable) would have just returned an array with
 nine elements like the packet has. This is not the case, and I
 am at a loss about how to fix this.

 I've searched the archive here and elsewhere with no luck. Any
 help REALLY appreciated!


With a bit of repr() and a bit of RTFM, one can often manage without
help :-)

Cheers,
John

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


db.commit() to take effect

2006-12-02 Thread progman
I was testing the python+mysql

here are my sample codes:

import MySQLdb
from pprint import pprint
db = MySQLdb.connect(host=localhost, user=root, passwd=password,
db=database)
cursor = db.cursor()
cursor.execute('update promo set date=100)




i was expecting the cursor.execute will update my db immediately.
it wasn't. not until i  run db.commit(), then only i see the value
changes.

it that the right way to update db?

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


Re: db.commit() to take effect

2006-12-02 Thread John Machin

progman wrote:
 I was testing the python+mysql

 here are my sample codes:
 
 import MySQLdb
 from pprint import pprint
 db = MySQLdb.connect(host=localhost, user=root, passwd=password,
 db=database)
 cursor = db.cursor()
 cursor.execute('update promo set date=100)


 

 i was expecting the cursor.execute will update my db immediately.
 it wasn't. not until i  run db.commit(), then only i see the value
 changes.

 it that the right way to update db?

Short answer: yes

Longer answer: In most non-trivial db apps, to carry out a given
real-world transaction, you will need to do multiple updates/inserts,
and you want them all to happen, or none to happen. The database would
be inconsistent if your app or server crashed half-way through. Imagine
you are transferring some money to someone else's bank account. The
money gets deducted from your account but not added to theirs -- not
good. [A real banking system would not be that simple, but you should
get the general idea.]  So you do db.commit() after the last
insert/update.

HTH,
John

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


Re: Tools for Java/Python scripting

2006-12-02 Thread skip

steve http://wiki.python.org/moin/Java_Scripting
 
 Renamed to JavaScripting.
 
 Skip

Rob So nobody around here has heared of that other language called
Rob JavaScript then ?

Rob Perhaps Scripting_Java might be better.

That would be JavaScriptScripting...

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


Re: Parsing data from pyserial

2006-12-02 Thread Hendrik van Rooyen
Lone Wolf [EMAIL PROTECTED] wrote:

 I'm trying to get data through my serial port from a CMUcam.
 This gizmo tracks a color and returns a packet of data. The
 packet has nine data points (well, really eight since the first
 point is just a packet header) separated by spaces as follows: M
 xxx xxx xxx xxx xxx xxx xxx xxx

8

Try splitting the stuff on the M first to separate the records,
then get rid of the newlines, carriage return, linefeed, whatever,
and then use the split on whitespace...

- HTH - Hendrik

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


  1   2   >