Re: Sending a file to a remote server.

2006-04-03 Thread Fredrik Lundh
Jose Carlos Balderas Alberico wrote:

> Hi. I posted a message in the list a couple of days ago about sending a file
> to a remote SimpleXMLRPCServer. Well. my doubt still remains, so I come to
> you again in search of a clearer answer.
>
> The thing is I want to send a ZIP file to a server, and what I basically do
> is enclose the file data into a Binary object by doing something like "data
> = Binary(f.read())". Then I call a function in the server, passing the
> object as a parameter, and have the server process the same file by doing
> something like
>
> f = open("somefile.zip", 'w')
> f.write(binaryObject.data)
>
> Since I've never programmed server/client before, I've never faced the fact
> of sending a file to a remote machine.
>
> I just want to know if what I've done to send the file is acceptable, and if
> you know of a better way to send files to a SimpleXMLRPCServer.

since ZIP files can contain arbitrary data, wrapping the data in the Binary
wrapper is the only way to you can transfer it over XML-RPC.

note, however, that XML-RPC (as well as any other XML-based transport)
needs to encode the bytes, which typically adds ~33% overhead.

if you're on a slow connection, or your files are really large, plain HTTP
transfers (or rsync etc.) are more efficient (but often somewhat harder
to implement).





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


Get the input from user

2006-04-03 Thread sushant . sirsikar
hi,
I am doing example of address book.when user enter stop and presses
enter my loop should stop.But there is some prob in my loop.It is
accepting \r after pressing Enter key.How do i check end of input :
  addressbook={}
name = raw_input("Enter Name (stop to Finish)")

name = EnterAddress(addressbook)

ShowAddress(name, addressbook)

def ShowAddress(name, addressbook):
name = raw_input("Enter Name for Address ")
print "Address of %s is %s" %(name,addressbook[name])

def EnterAddress(addressbook):
while name != "stop":
entry = raw_input("Enter the address")
addressbook[name]=entry
name = raw_input("Enter Name (Leave blank to Finish)")
return name

thanks
Sushant

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


Re: Getting a list of all classes derived from a base class

2006-04-03 Thread Vijairaj
Thanks Dylan and Alex, that was a new learning for me.

but both the solutions don't work in jython 2.1 is there an alternative
that will work with jython2.1

--
Thanks,
Vijairaj

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


Problem with wrapping GNU Units

2006-04-03 Thread TheSeeker
Hi,
As part of a larger project, I am trying to use the GNU Units program
to provide unit conversions between quantities.

My first iteration, which worked OK, was to simply use units as a
command-line app, and capture its output. The larger program however,
calls the conversion routine many times, and the overhead of starting
units for every call made things too slow.

I then re-formulated my use of units to open it using popen2, and do
conversions with it through stdin and stdout (Windows XP). This too
works OK, at least up to the point I want to stop the program, which is
where I am having problems.

If I simply try to exit my app, python.exe hangs, and units.exe keeps
running, according to the Task Manager. If I try sending Control-D, as
the on-line help suggests, the program hangs too.

Does anyone have any ideas on how to control this app?

Here is some of my code:

# Functions for driving GNU Units (if installed)
GNU_Units_stdin = None
GNU_Units_stdout = None

def SetupGNU_Units():
import time, os, sys
# Initialization routine to set up pipe to running GNU Units
process
# Start GNU Units as a child and feed and read through stdin and
stdout
global GNU_Units_stdin, GNU_Units_stdout
CurrentDir = os.getcwd()
# Hack to find correct directory
if not 'units.exe' in os.listdir(os.getcwd()):
UnitsDir = os.path.join(CurrentDir, 'GNU_Units')
else:
UnitsDir = CurrentDir
print "CurrentDir ", CurrentDir
os.chdir(UnitsDir)
(GNU_Units_stdin, GNU_Units_stdout) = os.popen2('units.exe -f
.\units.dat')
time.sleep(0.5)
print 'First initialization read: ', GNU_Units_stdout.readline()
time.sleep(0.5)
print 'Second initialization read: ', GNU_Units_stdout.readline()
time.sleep(0.5)
print 'Units initialization complete.'

def ShutdownGNU_Units():
global GNU_Units_stdin, GNU_Units_stdout
# From the GNU Units help, to quit the program from the interactive
prompt
#(which is how we are using it), one needs to feed it Control-D
GNU_Units_stdin.write(chr(4))
# ResponseLine1 = GNU_Units_stdout.readline()
GNU_Units_stdin = None
GNU_Units_stdout = None

def ConvertUnits(Value, FromUnitStr, ToUnitStr):
import os, sys
global GNU_Units_stdin, GNU_Units_stdout
# Sanity check on the numerical portion of the input
try:
dummy=float(Value)
except ValueError:
raise ConvertUnitsError('ConvertUnits: non-numeric input')
return 0
if not GNU_Units_stdin:
# Initialize pipes to GNU Units
SetupGNU_Units()
FromStr = str(Value)
FromStr += ' ' + FromUnitStr + '\r'
ToStr = ToUnitStr + '\r'
GNU_Units_stdin.write(FromStr)
GNU_Units_stdin.write(ToStr)
ResponseLine1 = GNU_Units_stdout.readline()
ResponseLine2 = GNU_Units_stdout.readline()
ReadBackLine = GNU_Units_stdout.readline()
ReadBackLine2 = GNU_Units_stdout.readline()
if 'conformability error' == ReadBackLine.strip():
raise ConvertUnitsError('ConvertUnits: conformability error')
AnswerElement = ReadBackLine.strip()
return float(AnswerElement.split()[1])

Thanks in advance,
Duane

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


Re: print() in Python 3000 return value?

2006-04-03 Thread Georg Brandl
Gary Herron wrote:

>>for i in sequence:
>>  mylist.append(print(i))
>>
>>  
>>
> No no, please NO!   You *know* that someday you'll want the return value 
> without actually printing the text. 
> 
> So let's don't overload a single function with two operations.  Let 
> "print" print, and propose a separate function (named "format" --yuck-- 
> or some such) that returns the same text as a string.

Yes! That's really a good idea. But "format" is a bad name. Let's call it
"as_string"!

Hm, bad too. What about "text"?

No, now I know. Let it be called "str".

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


Re: very very basic question

2006-04-03 Thread aghazalp
WO Larry
that was very very smart...it works perfectly  =)

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


Re: print() in Python 3000 return value?

2006-04-03 Thread bayerj
> Sorry? 2+2 here returns 4, and certainly should with your Python.

Err. Never mind. I was thinking about assignments, like

>>> x += 2

which returns None.

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


Re: Assignment in a while?

2006-04-03 Thread Alex Martelli
none <""thulben\"@(none)"> wrote:
...
> can't do an assignment in the while loop.  I found a way around this 
> (see the commented out while loop), but it seems hackish.  Assignment
> within a while loop seems like a pretty standard thing, so I'm just 
> curious what I'm missing.

I see you've already received many excellent suggestions, and just
wanted to point out the way in which you CAN "assign-and-test" in those
rare occasions where you really want to (in my experience, that boils
down to: I need Python code whose structure is as close as possible to
some other's language -- either because I need to transliterate into
Python some published "reference implementation" kind of algorithm, or
because I know I'm just doing a _prototype_ in Python, and once that's
accepted some poor folks will have to transliterate it into C or
whatever).  Anyway, it boils down to something like...:

class ValueHolder(object):
def __init__(self, value=None):
self.set(value)
def set(self, value): 
self.value = value
return value
data = ValueHolder()

and then, say, something like...:

while data.set(zip.zop()):
frobnicate(data.value)

Not as Pythonic as iterators etc, but structurally very close to

while (xx=zip.zop()) {
frobnicate(xx);
}

if that's what you need to stick close to!-)


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


Re: Getting a list of all classes derived from a base class

2006-04-03 Thread Dylan Moreland
Alex Martelli wrote:
> Vijairaj  R <[EMAIL PROTECTED]> wrote:
>...
> > class Test:
>
> do not use old-style classes: they exist ONLY for backwards
> compatibility.
>
> Make you class Test new-style:
>
> class Test(object):
>...
>
>
> and you can call Test.__subclasses__() to get a list of all extant
> subclassed of Test at any time.
>
>
> Alex

Thanks Alex. That's a new one to me -- new-style classes have so many
strange properties.

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


Re: update or refresh a Listbox widget

2006-04-03 Thread Recoruds
it might be very slow when the data is big...

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


Re: Assignment in a while?

2006-04-03 Thread Ben Thul
The inline iterator version fits very well with my sensibilities.  The 
problem that I have with fetchall is that sometimes you need to deal 
with a very large dataset.  Calling fetchall() on it will put the whole 
thing in memory, which is no good.  Better to iterate over it one row at 
a time, IMO.

Thanks a ton!
Ben

Duncan Booth wrote:
> none wrote:
> 
> 
>>If I try to run the above code, I get a SyntaxError indicating that I 
>>can't do an assignment in the while loop.  I found a way around this 
>>(see the commented out while loop), but it seems hackish.  Assignment 
>>within a while loop seems like a pretty standard thing, so I'm just 
>>curious what I'm missing.
>>
> 
> 
> Not much, you cannot assign to a variable in the controlling expression 
> of a while loop. However, for loops do assign values to variables, so if 
> the form with the break offends you, try restructuring your code as a for 
> loop. For example:
> 
> for results in iter(sth.fetchone, None):
>print results
> 
> or in many cases you can just fetch everything in one go:
> 
> for results in sth.fetchall():
>print results
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 licensing: stop this change

2006-04-03 Thread Tim Roberts
Steve Holden <[EMAIL PROTECTED]> wrote:

>As the only director of the Python Software Foundation to vote against a 
>recent Board motion to implement the change in licensing terms described in
>
>   http://pyfound.blogspot.com/2006/04/python-25-licensing-change.html
>
>I would like to place on record my protest against this change. I think 
>it will harm the Python language and ultimately be counter-productive, 
>reducing the user base and discouraging open source programmers from 
>contributing to the code base.
>
>If you disagree with this proposed change it's not too late to do 
>something about it. If this change goes ahead it will be the end of 
>Python as we know it.

The subject of this post really scared me.  I was one of the driver
developers for XFree86.  They really DID change their license in XFree86
4.4, and within about 6 months, XFree86 was effectively dead and X.Org had
taken over the world, with the same code base but a more traditional
license.

I held my breath until I read the actual document...
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxpython in action book

2006-04-03 Thread Tim Roberts
Butternut squash <[EMAIL PROTECTED]> wrote:
>
>any recommendations? any opinions?
>
>I want to learn to program in python and need a gui reference. I'll be
>updating various mysql tables. I have most of the code ready to roll by
>using a command line. I need put some lipstick on my project.
>
>pyQT seems viable but there is not really a good reference and tutorial
>
>so now I'm considering wxPython and saw this book and I'm wanting to know if
>if's even worth spending my $40 on.

It's a great book.  However, before diving in, take a moment to think about
how you expect to use this.  When I have an app that mostly dinks with a
database, I almost always decide to put a web front-end onto it.  That way,
I can run it locally (using CGIHTTPServer or CherryPy or something
similar), or I can plop it onto a web site and run it EVERYWHERE.

The thought processes are the same -- you create UI, you handle events.

You also might look at Dabo, which is a wrapper around wxPython for exactly
this kind of app.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "definitive" source on advanced python?

2006-04-03 Thread Michele Simionato
I gave a course on advanced Python last year at the ACCU conference.
See
http://www.reportlab.org/~andy/accu2005/pyuk2005_simionato_wondersofpython.zip

   Michele Simionato

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


Can't detect EOF from stdin on windows console

2006-04-03 Thread Dmitry Anikin
I want to read stdin in chunks of fixed size until EOF
I want to be able (also) to supply data interactively in console
window and then to hit Ctrl+Z when finished
So what I do is:

while True:
s = sys.stdin.read(chunk_size)
if not s:
break
# do something with s

if stdin is standard console input (on windows xp), here what happens:
(suppose, chunk_size = 3)
input: 123^Z
--- s gets "123" but reading doesn't end
input: ^Z
--- now s is empty and loop breaks,
so you have to press Ctrl-Z  TWICE to end the loop
worse still:
input: 12^Z
--- EOF is there, but there's only TWO chars instead of requested THREE,
so stdin.read() doesn't even return yet
input: ^Z
--- s gets "12" but reading doesn't end
input: ^Z
--- only now loop breaks
so you have to press Ctrl-Z  THRICE to end the loop

I haven't discovered any EOF function in python which could tell me
if eof was encountered. As you see, testing for empty string or for
len(s) = chunk_size doesn't improve the situation, anyone can
suggest a workaround?

Also I think the latter case is a straightaway bug, doc says:
  read( [size]) 

Read at most size bytes from the file (less if the read hits EOF before 
obtaining size bytes). 
According to that, stdin.read(3), when supplied with "12^Z" should return 
immediately
with two-character string instead of waiting for third character after EOF.
By the way, if I enter something between ^Z's that will be treated as vaild 
input
and ^Z's will be completely ignored.
-- 
http://mail.python.org/mailman/listinfo/python-list


How can i design a band-pass filter with scipy?

2006-04-03 Thread LabWINC
Hi all,
i would like to design a high pass filter with scipy.signal module.

This is the code i'm using to:

import scipy.signal as signal
import scipy

#first of all i design the lowpass fir filter. This is a 10 taps filter
with cutoff frequency =1 (as help tell me to do)

lpwindow=signal.firwin(10,1)

#with the following instruction i'm creating a band pass filter from
the low pass one
bpwindow=signal.lp2bp(lpwindow,1,0.5,0.2)

My problem is that the band-pass filter obtained with lp2bp function is
16 taps one!
How is it possible??

thanks,

Vincenzo

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


Re: wx.checklistbox

2006-04-03 Thread luca72
Hello Frefrik
It works but sometimes it insert a blank row so the file is like:

item1

item2
item3


item4
etc..

I don't inderstand  why.

But supposing that we can't solve this, is it possible to delete blanlk
items in the checkListBox?

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


Re: print() in Python 3000 return value?

2006-04-03 Thread Felipe Almeida Lessa
Em Dom, 2006-04-02 às 10:41 -0700, James Thiele escreveu:
> Martin chimedin:
> > James Thiele wrote:
> > > I noticed in PEP 3000 that print will become a function. The PEP
> > > references a thread where Guido explains this decision. The thread does
> > > not specify what the function will return. Has this been decided?
> >
> > My intuition is that it should be a procedure (i.e. returning None).
> > What do you want it to return?
> >
> > Regards,
> > Martin
> 
> The string that was printed. It could be useful inside expessions:
> 
> message = "I don't need to see all of this:%s" % print(s)

Or maybe:

for i in sequence:
mylist.append(print(i))

-- 
Felipe.

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

Re: ANN: uuid-0.1 Released

2006-04-03 Thread Lawrence D'Oliveiro
UUID = file("/proc/sys/kernel/random/uuid").readline().rstrip("\n")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: datetime, tzinfo ... strange conversion?

2006-04-03 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 Tino Lange <[EMAIL PROTECTED]> wrote:

>--> Why is GMT (3) wrong?

At a guess, it's because there's nothing in the parameters passed to 
indicate that daylight saving is currently in effect.

Tip: always do your date/time calculations as far as possible in UTC. 
Only convert to local time at the last possible step, before displaying 
results to the user.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Obtaining the Python Control Flow Graph

2006-04-03 Thread Carl Friedrich Bolz
Hi!

[EMAIL PROTECTED] wrote:
> I have been looking for a good way to convert python code into a
> control flow graph.
> 
> I know of Python functions that will convert an expression into an
> abstract syntax tree (i.e. ast = parser.expr('(x+5)*5') then t =
> ast.totuple() then t), but I am not sure how to obtain a CFG.
> 
> I've gone through the compiler and it has code that converts the AST
> into a CFG (described here:
> http://www.python.org/doc/peps/pep-0339/#ast-to-cfg-to-bytecode).
> Basically, PyAST_Compile() in Python/compile.c coverts the AST to a CFG
> and outputs final bytecode from the CFG by calling two functions:
> PySymtable_Build() in Python/symtable.c and compiler_mod() in
> Python/compile.c. PySymtable_Build() will build a symtable and
> compiler_mod() will create the CFG.
> 
> PyPy also offers a way to obtain a control flow graph:
> http://codespeak.net/pypy/dist/pypy/doc/objspace.html#the-flow-model

(Disclaimer: I am a PyPy developer) This works quite well in most cases 
but not in all, e.g. generators are not supported. It has other 
problems: The result will be (due to the used approach) in SSA form, 
which might be good or bad, depending on what you want. I don't know the 
CPython compiler well enough to say whether it is easy to get a CFG out 
of it. I know of no other easy method to get a CFG graph from Python code.

> I was wondering if anyone had any advice on the best way to obtain a
> control flow graph.  I need the control flow graph because I am trying
> figure out if there is a way to bound the integer ranges and list
> lengths at compile time.

This might be quite hard, for generic Python code. You might possibly 
(depending again on what your exact plans are) also look into the type 
inference part of PyPy:

http://codespeak.net/pypy/dist/pypy/doc/translation.html#the-annotation-pass

Feel free to also contact the PyPy mailing list (pypy-dev@codespeak.net) 
if you have PyPy-specific questions.

Cheers,

Carl Friedrich Bolz

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


"definitive" source on advanced python?

2006-04-03 Thread vdrab
Hi all,

Is there some sort of coherent source (dead tree format, maybe?) on
some of the more advanced features
of python (decorators, metaclasses, etc)? I'm sort of looking for a
python book that actually gets to the good stuff at some point, without
first spending 6 chapters on how to append ints to a list. I can't seem
to find any.

I get the impression people just get by with scraps and code snippets
posted on blogs left and right. (hope I'm wrong and my google skills
just suck ...)

Thanks in advance,

stijn.

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


Py+SQLite or other (big output) ?

2006-04-03 Thread DurumDara
Hi !
 
I want to process many data with python, and want to store in database.
In the prior version of my code I create a simple thing that delete the 
old results, recreate the database and fill up it.
 
But that is not too flexible, because when an power supply or hardware 
problem occured, all of the processed items are lost.
 
Then I thinking about a solution that can continue the work. This is 
like an diff or sync. directories problem.
Everytime I need to compare existing datas with inputs, and get result 
about this database: is finished, or I need to drop/add some elements.
 
That is not to hard to code, but I see that the very large files are 
very vulnerable.
Example: the older version of my code is use zip to export files... When 
I processed many files, I access the physical limit of the zip (4 GB), 
and every results destroyed in the crash...
Or when the database file is getting inconsistent state, I only way to 
make result is to drop db, and recreate it.
 
So I thinking about that I split the datas into smaller sections, and 
use them. If any of them destroyed or injured, I need to recreate only that.
But this solution have a problems too.
1.) I need a header file to "join" them logically. When this file 
injured, every data must drop.
2.) The sync. operation is harder, because some files are not needed 
(when input data amount less than before), or some records are not 
needed; or I need to add some records to some of the files.
3.) I need to use global db to store global values.
 
If I use this concept, I pay with hardest coding, and many-many bug chance.
 
So I want to use one database file - but I want to protect it.
How to do it with SQLite ?
I see that solutions:
- 1. I use transactions.
- 2. I create full copy of database after every bigger transation.
- 3. Shadow file ???
- 4. Mirror database (this is problematic to synch.).
 
The transactions are very good things, but does not protect the database 
from injuring.
The copy operation is better, but very decrease the processing speed, 
because the result db grow fast, and copy of 1/2,2/3 GBs is slow, and 
not too good.
 
Have SQLite any solution to this problem ?

Or have you any solution to this problem ? Hash-DB ? Pickled elements ?
 
Thanx for the help:
dd
 
-- 
http://mail.python.org/mailman/listinfo/python-list


beautiful GUI

2006-04-03 Thread Daily Lama
Hello,
is there a way to create nice good-looking Form for Windows;
I mean not the windows-style form, but something cute, like mac os
forms
with their coloured red-yellow-green buttons

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


Re: Obtaining the Python Control Flow Graph

2006-04-03 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
>
> I was wondering if anyone had any advice on the best way to obtain a
> control flow graph.  I need the control flow graph because I am trying
> figure out if there is a way to bound the integer ranges and list
> lengths at compile time.

Although I haven't actually been generating control flow graphs as
such, the analysis distribution [1] produces both HTML summaries and C
source code for Python programs of a certain level of sophistication,
and I'm currently trying to finish off a new release which exposes
different strategies for deducing types and specialising functions. You
probably want to read Mark Dufour's ShedSkin paper [2] to get an idea
about how hard this kind of stuff is, and a dose of defeatism might
also be necessary given that your problem may not be solvable in
general. ;-)

Paul

[1] http://www.boddie.org.uk/python/analysis.html
[2] http://kascade.org/optimizing_python.pdf

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


Subtle architecture-dependent bug in Numeric.RandomArray

2006-04-03 Thread Johannes Nix

There is a subtle bug in the RandomArray module, which is part of
the Numeric package. It causes the random number generator 
RandomArray.normal() to return incorrect values when invoked on Linux 
compiled with gcc  on a AMD Opteron machine, that is, a system with 
64-Bit CPU and ILP64 data model. The result will depend on the data model 
and the aligning of the C implementation on the used architecture. 
The bug seems not to be triggered on 32-bit systems.

Cause of the bug are the code lines

ranlibmodule.c:get_continuous_random, line 48:
---
case 0:
  *out_ptr = (double) ((double (*)()) fun)();
  break;
---

and

ranlibmodule.c:standard_normal, line 125:

static PyObject *
standard_normal(PyObject *self, PyObject *args) {
  return get_continuous_random(0, self, args, snorm);
}
-

where fun is a function pointer to the functions ranf() or 
snorm(). However, only in the case of ranf(),
the function returns actually a double value, snorm(),
which is used to generate Gaussian random numbers, returns 
a float.

The Numpy package, which is the recommended replacement
for Numeric, uses a different random number generator
(the Mersenne Twister RNG) and does not contain this code.


Kind Regards,

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


[CONSTRUCT] - Removing Need For Repeated Definition of __str__

2006-04-03 Thread Ilias Lazaridis
I have some python code which looks similar to this:

class Car(BaseClass) :
   manufacturer = factory.string()
   model = factory.string()
   modelYear = factory.integer()

   def __str__(self):
   return '%s %s %s' % (self.modelYear, self.manufacturer,
self.model)

def factory.string(self)
  s = String() # creates a string object
  #... # does several things
  return s # returns the string object

-

I would like to simplify it in this way:

class Car(BaseClass):
   manufacturer = factory.string(2)  # 2 = position number...
   model = factory.string(3) # ...withinn __str__
   modelYear = factory.integer(1)

def factory.string(self, position)
  s = String() # creates a string object
  ...  # does several things
   # creates somehow the __str__ functionality...

  return s # returns the string object

-

How could I achieve this?

.

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


Oserror: [Errno 20]

2006-04-03 Thread k r fry
Hi, I am new to this list and also programming with python.

I have an error: oserror [errno 20] not a directory "katiescint.py"

The piece of code causing the problem is:
[code]

for subdir in os.listdir(DATADIR):  #loop through list of 
strings

 file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens 
flux.fits file and reads

 summation=open(DATADIR+'/'+subdir+'/flux.dat','w')  #opens the 
summation results file for writing to

 spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the 
spot-by-spot file for writing to

 output=''
 print'\n~~\n'+sys.argv[1]+' 
'+subdir+'\n\n'

[/code]

The first line is the one with the error.  Can anyone help?

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


Re: how to comment lot of lines in python

2006-04-03 Thread Sion Arrowsmith
Eric Deveaud  <[EMAIL PROTECTED]> wrote:
>some moderns editors allow you to comment/uncomment  a selected Bunch 
>of lines of code

Out of curiousity, is there a modern editor which *doesn't* allow you
to comment/uncomment a selected bunch of lines of code?

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

Re: Py+SQLite or other (big output) ?

2006-04-03 Thread Gerhard Häring
Anonymous Coward DurumDara wrote:
> [...]
> So I want to use one database file - but I want to protect it.
> How to do it with SQLite ?
> I see that solutions:
> - 1. I use transactions.
> - 2. I create full copy of database after every bigger transation.
> - 3. Shadow file ???
> - 4. Mirror database (this is problematic to synch.).
>  
> The transactions are very good things, but does not protect the database 
> from injuring.

Actually, SQLite transactions do protect you from "bad things 
happening". If a transaction suceeds, it also does an fsync() call so 
that the data gets written to disk and does not remain in the database's 
or operating system's write cache.

And of course, the main feature is that if you group your SQL statements 
right, then the database is always in a consistent state, even after a 
crash.

> The copy operation is better, but very decrease the processing speed, 
> because the result db grow fast, and copy of 1/2,2/3 GBs is slow, and 
> not too good.

and doesn't help the real problem at all. If your application or 
computer crashes during a copy, from where do you recover from?

> Have SQLite any solution to this problem ?

Transactions :-)

And don't set PRAGMA synchronous = OFF; to increase the speed of your 
application, because then your database *will* be corrupted during a 
crash. (*)

-- Gerhard

(*) Full details at http://www.sqlite.org/pragma.html for PRAGMA 
synchronous.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Oserror: [Errno 20]

2006-04-03 Thread Peter Hansen
k r fry wrote:
> Hi, I am new to this list and also programming with python.
> 
> I have an error: oserror [errno 20] not a directory "katiescint.py"

Please always post complete tracebacks, and without manually reentering 
the data.  In most cases you'll save us and you lots of time and guessing.

> The piece of code causing the problem is:
> [code]
> 
> for subdir in os.listdir(DATADIR):  #loop through list of 
> strings
> 
>  file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens 
> flux.fits file and reads

os.listdir() returns a list of all files and directories inside the 
directory specified (DATADIR), so you can't assume that "subdir" is 
always going to be a directory.  Use os.path.isdir() to confirm that it 
is and ignore those items for which that function returns False.

-Peter

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


Re: how to comment lot of lines in python

2006-04-03 Thread Kent Johnson
Sion Arrowsmith wrote:
> Eric Deveaud  <[EMAIL PROTECTED]> wrote:
>> some moderns editors allow you to comment/uncomment  a selected Bunch 
>> of lines of code
> 
> Out of curiousity, is there a modern editor which *doesn't* allow you
> to comment/uncomment a selected bunch of lines of code?
> 
TextPad is my editor of choice but it doesn't have this feature.

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


Re: Oserror: [Errno 20]

2006-04-03 Thread k r fry
Sorry for not copying the whole traceback before, I hop I have done it 
right this time.

I am now getting:

Traceback (most recent call last):
   File "katiescint.py", line 153, in ?
 for subdir in os.path.istdir(DATADIR):  #loop through 
list of strings
AttributeError: 'module' object has no attribute 'istdir'

I did think maybe it was meant to be "listdir" instead of "istdir", but 
that doesn't work either.
Sorry to be a pain.


Peter Hansen wrote:

> k r fry wrote:
> 
>> Hi, I am new to this list and also programming with python.
>>
>> I have an error: oserror [errno 20] not a directory "katiescint.py"
> 
> 
> Please always post complete tracebacks, and without manually reentering 
> the data.  In most cases you'll save us and you lots of time and guessing.
> 
>> The piece of code causing the problem is:
>> [code]
>>
>> for subdir in os.listdir(DATADIR):  #loop through list of 
>> strings
>>
>>  file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens 
>> flux.fits file and reads
> 
> 
> os.listdir() returns a list of all files and directories inside the 
> directory specified (DATADIR), so you can't assume that "subdir" is 
> always going to be a directory.  Use os.path.isdir() to confirm that it 
> is and ignore those items for which that function returns False.
> 
> -Peter
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wx.checklistbox

2006-04-03 Thread luca72
I have solve in this way i'm sure it's not the best, but it works:

 lista1leggi = open('/lista1.txt', 'r')
mt = lista1leggi.readlines()
lunghezzamt = len(mt)
lucianino = 0
while lucianino < (lunghezzamt - 1):
if mt[lucianino] == '\n':
del mt[lucianino]
lucianino = lucianino - 1
lunghezzamt = lunghezzamt - 1
else: lucianino = lucianino + 1

pippo = self.checkListBox1.AppendItems(mt)

Ragards Luca

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


GIS

2006-04-03 Thread Albert Leibbrandt
Hi

I need to get myself familiarised with GIS, specifically postgis for 
postgres. Can anyone give some advice, or some docs that start at the 
beginning. I've tried the postgis mailing list but it does not seem as 
if that list is very active.

Perhaps you guys know of gis packages for python?

Thanks
Albert

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


Re: how to comment lot of lines in python

2006-04-03 Thread Rick Zantow
Kent Johnson <[EMAIL PROTECTED]> wrote in news:44310867$1_1
@newspeer2.tds.net:

> Sion Arrowsmith wrote:
>> Eric Deveaud  <[EMAIL PROTECTED]> wrote:
>>> some moderns editors allow you to comment/uncomment  a selected Bunch 
>>> of lines of code
>> 
>> Out of curiousity, is there a modern editor which *doesn't* allow you
>> to comment/uncomment a selected bunch of lines of code?
>> 
> TextPad is my editor of choice but it doesn't have this feature.
> 

I use TextPad all the time, and while it is true that the feature is not 
built in, it's misleading to say it doesn't have it. It is implemented by 
means of a macro definition. I assign a key to a 'comment' macro (basically 
replacing regex ^ with '# ' for the selected text) to do this. And of 
course I have a reciprocal 'uncomment' macro as well.

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


Re: Problem with wrapping GNU Units

2006-04-03 Thread Kent Johnson
TheSeeker wrote:
> Hi,
> As part of a larger project, I am trying to use the GNU Units program
> to provide unit conversions between quantities.

Maybe Unum would be a useful alternate:
http://home.tiscali.be/be052320/Unum.html

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


Re: New Python Logo Revealed

2006-04-03 Thread robin
"Giovanni Bajo" <[EMAIL PROTECTED]> wrote:

>robin wrote:
>
>> I have an entry on my blog discussing the new Python logo, which is
>> apparently due to replace the current one within the month. I'd be
>> interested in what people think of it.
>>
>> Surf:
>> http://diagrammes-modernes.blogspot.com
>
>Tell me tell me it's an april's joke, please? :)

yes :-)
-
robin
noisetheatre.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DO NOT USE JAVA BECAUSE IT IS NOT OPEN SOURCE

2006-04-03 Thread [EMAIL PROTECTED]
I love messages like this!  Just when I think I'm about the dumbest
person in the World, someone comes in and sets a brand new all-time
low.  Good Job, Dude.

But call your kickin' ~ditrabation~, "Cooty Tar", or something.  That
will insulate all newbies to this list from a lifetime of idiocy.  You
have done us all a great service.  Watch out for alcohol poisoning.  It
affects the speling senters of your brain.  I sure hope
Google doesn't escape HTML tags.  This could be
important.

[EMAIL PROTECTED] wrote:
> Programing Languiges Are Ment to be free. That is why i am starting The
> Coo De Tar thats french for Blow of state it is a flash/java
> alternative and if you are going to use a server side languige use
> Perl,Python or better yet Ruby. What is the point of a languige without
> a standerd and without a open source distrabution. Coo De Tar will be
> released as a api for perl,python and ruby. Java sucks because it IS
> NOT FREE. I AM A GNU GUY I BELEVE THAT SOFTWARE MUST AND SHALL BE
> FREE!! do not use java because it is an oxymoron

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


Re: "definitive" source on advanced python?

2006-04-03 Thread Gabriel de Dietrich
Maybe you're looking for something like this?
http://jamesthornton.com/eckel/TIPython/html/Index.htm

Haven't read it yet, but seems to be about design patterns. Not the
"definitive" stuff, though...

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


Re: how to comment lot of lines in python

2006-04-03 Thread Frank Millman

Kent Johnson wrote:
> Sion Arrowsmith wrote:
> > Eric Deveaud  <[EMAIL PROTECTED]> wrote:
> >> some moderns editors allow you to comment/uncomment  a selected Bunch
> >> of lines of code
> >
> > Out of curiousity, is there a modern editor which *doesn't* allow you
> > to comment/uncomment a selected bunch of lines of code?
> >
> TextPad is my editor of choice but it doesn't have this feature.
>
> Kent

I also use TextPad - 4.7.3. I have never thought to comment a block of
code, but this thread prompted me to see if it is possible. As far as I
can see, you can do it like this -

Menu > Configure > Block Select Mode - Ctrl+Q,B

Select a block, one column wide, using mouse or keyboard.

Menu > Edit > Fill Block (brings up dialog box)
Fill character:   #
Format:  Left align
Fill mode:   Replace
OK

Done.

To uncomment, as above but set Fill character to a space.

It feels a bit fiddly, but I reckon if you use it a few times it will
become quite smooth.

Frank Millman

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


Re: GIS

2006-04-03 Thread Cyril Bazin
Postgis is only an extension of Postgres which add new classes and new operations specialised for GIS.
All you should know, is how to build SQL requests for postgres...

If you want to be familiarised with the GIS, you should try to make your own little project. 
So you will be able to ask more precises questions.
Cyril
On 4/3/06, Albert Leibbrandt <[EMAIL PROTECTED]> wrote:
HiI need to get myself familiarised with GIS, specifically postgis forpostgres. Can anyone give some advice, or some docs that start at thebeginning. I've tried the postgis mailing list but it does not seem as
if that list is very active.Perhaps you guys know of gis packages for python?ThanksAlbert--http://mail.python.org/mailman/listinfo/python-list

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

Re: Oserror: [Errno 20]

2006-04-03 Thread Sybren Stuvel
k r fry enlightened us with:
> I did think maybe it was meant to be "listdir" instead of "istdir",
> but that doesn't work either.

And again you don't tell us in what way it doesn't work.

Think about what you post from our point of view. Then re-read it, and
think about it again. Only if you're sure that we'll be able to fully
understand it, hit the 'send' button. That will save us a lot of
guessting and asking, and will also get you your answer a lot faster.

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


Re: Oserror: [Errno 20]

2006-04-03 Thread k r fry
Again, I apologise.  Not knowing much about Python means that I don't 
know what needs to be provided.  I meant it doesn't work in the same way 
that "istdir" didn't work.

Here is what I have coded:

for subdir in os.path.istdir(DATADIR):  #loop through list 
of strings

 file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens 
flux.fits file and reads

 summation=open(DATADIR+'/'+subdir+'/flux.dat','w')  #opens the 
summation results file for writing to

 spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the 
spot-by-spot file for writing to

 output=''
 print'\n~~\n'+sys.argv[1]+' 
'+subdir+'\n\n'

And here is what I get when I try to run it:

Traceback (most recent call last):
   File "katiescint.py", line 153, in ?
 for subdir in os.path.istdir(DATADIR):  #loop through 
list of strings
AttributeError: 'module' object has no attribute 'istdir'

Here is trying with listdir:

for subdir in os.path.listdir(DATADIR):  #loop through list 
of strings

and here is what I get:

Traceback (most recent call last):
   File "katiescint.py", line 153, in ?
 for subdir in os.path.listdir(DATADIR):  #loop through 
list of strings
AttributeError: 'module' object has no attribute 'listdir'




Sybren Stuvel wrote:

> k r fry enlightened us with:
> 
>>I did think maybe it was meant to be "listdir" instead of "istdir",
>>but that doesn't work either.
> 
> 
> And again you don't tell us in what way it doesn't work.
> 
> Think about what you post from our point of view. Then re-read it, and
> think about it again. Only if you're sure that we'll be able to fully
> understand it, hit the 'send' button. That will save us a lot of
> guessting and asking, and will also get you your answer a lot faster.
> 
> Sybren
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: GIS

2006-04-03 Thread Albert Leibbrandt

Cyril Bazin wrote:
> Postgis is only an extension of Postgres which add new classes and new 
> operations specialised for GIS.
> All you should know, is how to build SQL requests for postgres...
>
> If you want to be familiarised with the GIS, you should try to make 
> your own little project.
> So you will be able to ask more precises questions.
>
> Cyril
>
> On 4/3/06, *Albert Leibbrandt* <[EMAIL PROTECTED] 
> > wrote:
>
> Hi
>
> I need to get myself familiarised with GIS, specifically postgis for
> postgres. Can anyone give some advice, or some docs that start at the
> beginning. I've tried the postgis mailing list but it does not
> seem as
> if that list is very active.
>
> Perhaps you guys know of gis packages for python?
>
> Thanks
> Albert
>
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
>
>
I need to create a sphere with a certain size. I have x and y 
coordinates which I then need to calculated the distances between.
I use postgresql, that is why I am looking at postgis.

If anybody knows of any documentation (except for what is on the postgis 
homepage) please let me know as I seam to have problems with the 
installation, postgres does not recognize the functions although the 
functions exist.

Thanks
Albert



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


Re: Oserror: [Errno 20]

2006-04-03 Thread Sybren Stuvel
k r fry enlightened us with:
> Traceback (most recent call last):
>File "katiescint.py", line 153, in ?
>  for subdir in os.path.listdir(DATADIR):  #loop through 
> list of strings
> AttributeError: 'module' object has no attribute 'listdir'

But why do you use that function then? listdir is in the module os,
not in os.path.

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


Re: DO NOT USE JAVA BECAUSE IT IS NOT OPEN SOURCE

2006-04-03 Thread alainpoint
Bravo, yoo r write, a propriatary languish is an oxy-moron. I have a
rekwest zou: witch languish do yoo rekomend, bikoos yoo seem so a grate
programor, at list zis is wat eye beleve, judging by yoo spelling.
Alain

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


Re: - Removing Need For Repeated Definition of __str__

2006-04-03 Thread Dylan Moreland
Ilias Lazaridis wrote:
> I have some python code which looks similar to this:
>
> class Car(BaseClass) :
>manufacturer = factory.string()
>model = factory.string()
>modelYear = factory.integer()
>
>def __str__(self):
>return '%s %s %s' % (self.modelYear, self.manufacturer,
> self.model)
>
> def factory.string(self)
>   s = String() # creates a string object
>   #... # does several things
>   return s # returns the string object
>
> -
>
> I would like to simplify it in this way:
>
> class Car(BaseClass):
>manufacturer = factory.string(2)  # 2 = position number...
>model = factory.string(3) # ...withinn __str__
>modelYear = factory.integer(1)
>
> def factory.string(self, position)
>   s = String() # creates a string object
>   ...  # does several things
>
   # creates somehow the __str__ functionality...
>
>   return s # returns the string object
>
> -
>
> How could I achieve this?
>
> .
>

I'm slightly confused about your use of factory functions for making
instance variables (perhaps you could explain that?). Without knowing
more about that, here's a mixin solution I've used in the past (note
that __strdef__ is something I just made up):

class SmartStr(object):

def __str__(self):
return "<%s %s>" % (self.__class__.__name__,
", ".join(attrname + "=" + str(getattr(self, attrname))
  for attrname in self.__strdef__))

class Car(SmartStr):

__strdef__ = ["model_year", "manufacturer", "model"]

def __init__(self, manufacturer, model, model_year):
self.manufacturer = manufacturer
self.model = model
self.model_year = model_year

c = Car("Toyota", "Camry", 1990)
print c # => 

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


Re: Oserror: [Errno 20]

2006-04-03 Thread k r fry
Thank you very much!  *embarassed*.

:-)

Ben Thul wrote:

> I think that if you go back and look at the original reply, he spelled 
> it "isdir"...;)
> 
> --Ben
> k r fry wrote:
> 
>> Again, I apologise.  Not knowing much about Python means that I don't 
>> know what needs to be provided.  I meant it doesn't work in the same 
>> way that "istdir" didn't work.
>>
>> Here is what I have coded:
>>
>> for subdir in os.path.istdir(DATADIR):  #loop through list 
>> of strings
>>
>> file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens 
>> flux.fits file and reads
>>
>> summation=open(DATADIR+'/'+subdir+'/flux.dat','w')  #opens the 
>> summation results file for writing to
>>
>> spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the 
>> spot-by-spot file for writing to
>>
>> output=''
>> print'\n~~\n'+sys.argv[1]+' 
>> '+subdir+'\n\n'
>>
>> And here is what I get when I try to run it:
>>
>> Traceback (most recent call last):
>>   File "katiescint.py", line 153, in ?
>> for subdir in os.path.istdir(DATADIR):  #loop through 
>> list of strings
>> AttributeError: 'module' object has no attribute 'istdir'
>>
>> Here is trying with listdir:
>>
>> for subdir in os.path.listdir(DATADIR):  #loop through 
>> list of strings
>>
>> and here is what I get:
>>
>> Traceback (most recent call last):
>>   File "katiescint.py", line 153, in ?
>> for subdir in os.path.listdir(DATADIR):  #loop through 
>> list of strings
>> AttributeError: 'module' object has no attribute 'listdir'
>>
>>
>>
>>
>> Sybren Stuvel wrote:
>>
>>> k r fry enlightened us with:
>>>
 I did think maybe it was meant to be "listdir" instead of "istdir",
 but that doesn't work either.
>>>
>>>
>>>
>>>
>>> And again you don't tell us in what way it doesn't work.
>>>
>>> Think about what you post from our point of view. Then re-read it, and
>>> think about it again. Only if you're sure that we'll be able to fully
>>> understand it, hit the 'send' button. That will save us a lot of
>>> guessting and asking, and will also get you your answer a lot faster.
>>>
>>> Sybren
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Oserror: [Errno 20]

2006-04-03 Thread Peter Hansen
k r fry wrote:
> Sorry for not copying the whole traceback before, I hop I have done it 
> right this time.
> 
> I am now getting:
> 
> Traceback (most recent call last):
>File "katiescint.py", line 153, in ?
>  for subdir in os.path.istdir(DATADIR):  #loop through 
> list of strings
> AttributeError: 'module' object has no attribute 'istdir'
> 
> I did think maybe it was meant to be "listdir" instead of "istdir", but 
> that doesn't work either.
> Sorry to be a pain.

You'll get the hang of it... :-)

There are two functions required here: os.listdir(), and 
os.path.isdir().  The first one is the correct one for the purpose, as 
you originally used it.  The second one (which I suppose someone with a 
German background might try to spell "istdir" ;-) ) is to test whether a 
given path "is [a] dir[ectory]".

If you read the documentation on those two functions, and experiment at 
the interactive prompt, you'll shortly notice that os.listdir() returns 
only the names of the items in the directory, not the full paths. 
os.path.isdir(), on the other hand, requires a full path (since of 
course it can't know what directory you looked in with os.listdir), so 
you'll have to join the names together before testing them, something 
like this (and I'll rely on you to actually *read the docs* and 
*experiment at the interactive prompt* this time, instead of giving up 
so quickly and asking for help again when you could figure this out 
yourself with a little more effort):

for name in os.listdir(DATADIR):
 path = os.path.join(DATADIR, name)
 if os.path.isdir(path):
 filename = os.path.join(path, 'flux.fits')
 data = FITS.Read(filename)
 # etc

-Peter

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


Re: how to comment lot of lines in python

2006-04-03 Thread Kent Johnson
Rick Zantow wrote:
> Kent Johnson <[EMAIL PROTECTED]> wrote in news:44310867$1_1
> @newspeer2.tds.net:
> 
>> Sion Arrowsmith wrote:
>>> Out of curiousity, is there a modern editor which *doesn't* allow you
>>> to comment/uncomment a selected bunch of lines of code?
>>>
>> TextPad is my editor of choice but it doesn't have this feature.
>>
> 
> I use TextPad all the time, and while it is true that the feature is not 
> built in, it's misleading to say it doesn't have it. It is implemented by 
> means of a macro definition. I assign a key to a 'comment' macro (basically 
> replacing regex ^ with '# ' for the selected text) to do this. And of 
> course I have a reciprocal 'uncomment' macro as well.

Thank you! I don't suppose you have any tricks to make it work with 
UTF-8 data outside the cp1252 character set, do you?

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


Re: Oserror: [Errno 20]

2006-04-03 Thread Ben Thul
I think that if you go back and look at the original reply, he spelled 
it "isdir"...;)

--Ben
k r fry wrote:
> Again, I apologise.  Not knowing much about Python means that I don't 
> know what needs to be provided.  I meant it doesn't work in the same way 
> that "istdir" didn't work.
> 
> Here is what I have coded:
> 
> for subdir in os.path.istdir(DATADIR):  #loop through list 
> of strings
> 
> file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens flux.fits 
> file and reads
> 
> summation=open(DATADIR+'/'+subdir+'/flux.dat','w')  #opens the 
> summation results file for writing to
> 
> spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the 
> spot-by-spot file for writing to
> 
> output=''
> print'\n~~\n'+sys.argv[1]+' 
> '+subdir+'\n\n'
> 
> And here is what I get when I try to run it:
> 
> Traceback (most recent call last):
>   File "katiescint.py", line 153, in ?
> for subdir in os.path.istdir(DATADIR):  #loop through 
> list of strings
> AttributeError: 'module' object has no attribute 'istdir'
> 
> Here is trying with listdir:
> 
> for subdir in os.path.listdir(DATADIR):  #loop through list 
> of strings
> 
> and here is what I get:
> 
> Traceback (most recent call last):
>   File "katiescint.py", line 153, in ?
> for subdir in os.path.listdir(DATADIR):  #loop through 
> list of strings
> AttributeError: 'module' object has no attribute 'listdir'
> 
> 
> 
> 
> Sybren Stuvel wrote:
> 
>> k r fry enlightened us with:
>>
>>> I did think maybe it was meant to be "listdir" instead of "istdir",
>>> but that doesn't work either.
>>
>>
>>
>> And again you don't tell us in what way it doesn't work.
>>
>> Think about what you post from our point of view. Then re-read it, and
>> think about it again. Only if you're sure that we'll be able to fully
>> understand it, hit the 'send' button. That will save us a lot of
>> guessting and asking, and will also get you your answer a lot faster.
>>
>> Sybren
-- 
http://mail.python.org/mailman/listinfo/python-list


Pydev and Pydev Extensions 1.0.4 release

2006-04-03 Thread Fabio Zadrozny
Hi All,

Pydev and Pydev Extensions 1.0.4 have been released

Check http://www.fabioz.com/pydev for details on Pydev Extensions

and http://pydev.sf.net for details on Pydev

Release Highlights in Pydev Extensions:
-

- Interactive Console binded to the Pydev Editor
- Bug-fixes

Release Highlights in Pydev:
--

- Added jython scripting
- Added an 'easy' way to bind actions after Ctrl+2 (to make scripting easier)
- Added a way to list things binded with Ctrl+2 (To see: Ctrl+2+help)
- Added a 'go to next problem' with jython scripting capabilities, as a
first example on how to script Pydev with Jython (Ctrl+.)
- A brand new indentation engine is available:

    * Does not try to make different indentations inside multilines
    * Does not try to add spaces to make smart-indent when in only tabs mode
    * Indents correctly after opening some bracket or after closing some bracket
    * Indents to 'expected level' when hitting tab

- Fixed bug: syntax error described instead of throwing an error
- Profiled Pydev (not that much, but still, I hope you'll be able to 'feel' it)
- Fixed bug: the pythonpath was not added when additional environment variables where specified
- And as always, other bugs have been fixed


What is PyDev?

---


PyDev is a plugin that enables users to use Eclipse for Python and
Jython development -- making Eclipse a first class Python IDE -- It
comes with many goodies such as code completion, syntax highlighting,
syntax analysis, refactor, debug and many others. 


Cheers,

-- 
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
http://www.esss.com.br

Pydev Extensions
http://www.fabioz.com/pydev

Pydev - Python Development Enviroment for Eclipse
http://pydev.sf.net
http://pydev.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Oserror: [Errno 20]

2006-04-03 Thread k r fry
Thank you very much!  I really appreciate the help. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "definitive" source on advanced python?

2006-04-03 Thread bruno at modulix
Gabriel de Dietrich wrote:
> Maybe you're looking for something like this?
> http://jamesthornton.com/eckel/TIPython/html/Index.htm
> 
> Haven't read it yet, but seems to be about design patterns. Not the
> "definitive" stuff, though...

While TIP is an interesting book, it is more about implementation of
standard design patterns in Python than about 'advanced' Python
programming.



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


Re: GIS

2006-04-03 Thread Diez B. Roggisch
 I need to create a sphere with a certain size. I have x and y
> coordinates which I then need to calculated the distances between.
> I use postgresql, that is why I am looking at postgis.
> 
> If anybody knows of any documentation (except for what is on the postgis
> homepage) please let me know as I seam to have problems with the
> installation, postgres does not recognize the functions although the
> functions exist.

That is a question to ask on the postgis mailing list. And I can't see any
postings of you there so far...

I can tell you that I have successfully installed postigis with PG 8.0 and
8.1 - under a debian system. Just by following the available documentation.

Diez


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


Re: "definitive" source on advanced python?

2006-04-03 Thread Kent Johnson
vdrab wrote:
> Hi all,
> 
> Is there some sort of coherent source (dead tree format, maybe?) on
> some of the more advanced features
> of python (decorators, metaclasses, etc)? I'm sort of looking for a
> python book that actually gets to the good stuff at some point, without
> first spending 6 chapters on how to append ints to a list. I can't seem
> to find any.

The "What's New" documents that come with each version of Python do a 
good job of introducing new features, with reference to the relevant PEP 
for all the details. For example decorators:
http://docs.python.org/whatsnew/node6.html

I found the printed Python Cookbook to be a good way to learn about 
idiomatic usage. It also has some recipes using advanced features and 
the explanations are helpful.

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


Re: Difference between 'is' and '=='

2006-04-03 Thread Adam DePrince
On Mon, 2006-03-27 at 17:17 -0500, Terry Reedy wrote:
> "Clemens Hepper" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
> > It's strange: python seem to cache constants from 0 to 99:
> 
> The Python specification allows but does not require such behind-the-scenes 
> implementation optimization hacks.  As released, CPython 2.4 caches -5 to 
> 99, I believe.  In 2.5, the upper limit was increased to 256.  The limits 
> are in a pair of #define statements in the int object source file.  Anyone 
> who compiles from source can adjust as desired (though the corresponding 
> test will fail unless also adjusted ;-).
> 
> I think the visibility of this implementation detail from Python code is an 
> example of a leaky abstraction.  For more, see
> http://www.joelonsoftware.com/articles/LeakyAbstractions.html

I disagree wholeheartedly with this.  == and is are two very different
operators that have very different meaning.  It just happens that the
logical operation 

 (a is b ) -> (a == b )

is always True.  

There is no abstraction going on here; a==b is not an abstract version
of a is b.  They are different operations.

a == b tests if the values of objects at a and b are equal.  a and b
point be the same darn object, or they might be different objects, but
the question we are asking is if they have the same value.  

The is operator is different, you use it if you are interested in
introspecting the language.  

Some people have noticed that  1 + 1 is 2 will return True and  1 + 100
is 101 returns False.   This isn't a "leaky abstraction" unless you
wrongly consider is to be an analogy for ==.

Python has certain optimizations ... small strings and numbers are
"interned," that is canonical copies are maintained and efforts to
create fresh objects result in the old cached copies being returned,
albeit with higher reference counts.  This saves memory and time; time
because for any intern-able objects the truth of the first test is a
realistic possibility.

if a is b:
return True
if hash( a ) != hash( b )
return False
... Now do proper equality testing. ... 

As for "joelonsoftware's" leaky abstraction article, I respectfully
disagree.  His leaky abstractions are merely inappropriate analogies.
TCP is perfectly reliable with respect to its definition of
reliability.  

As for wipers abstracting away the rain ...

Well over a decade ago I recall walking to lunch with my supervisor, a
truly masterful C programmer.  We worked in Manhattan, a land where two
way streets are the exception.  When crossing each street he would look
the wrong way, look the correct way and then stare the wrong way again.
Upon noticing my inquisitorial expression, he answered "A good
programmer always looks both ways when crossing a one way street."   

I'm uncertain that a quip about abstracting away the rain would have
prompted the same adjective "masterful" now 10+ years in the future.

- Adam DePrince


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


string building

2006-04-03 Thread John Salerno
Out of curiosity, is there any kind of equivalent in Python to the 
StringBuilder class in C#? Here's a quick description from the .NET 
documentation:

"This class represents a string-like object whose value is a mutable 
sequence of characters. The value is said to be mutable because it can 
be modified once it has been created by appending, removing, replacing, 
or inserting characters."

It's used for dealing with large strings that otherwise would cause 
performance problems if used as regular string objects. I'm just 
wondering if Python has something like this, or if it is even really 
necessary. I know there is even some discussion on when exactly 
StringBuilder becomes useful over regular strings, but I imagine at some 
point it is good to use.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Python Logo Revealed

2006-04-03 Thread Alec Jang
robin 写道:
> "Giovanni Bajo" <[EMAIL PROTECTED]> wrote:
> 
>> robin wrote:
>>
>>> I have an entry on my blog discussing the new Python logo, which is
>>> apparently due to replace the current one within the month. I'd be
>>> interested in what people think of it.
>>>
>>> Surf:
>>> http://diagrammes-modernes.blogspot.com
>> Tell me tell me it's an april's joke, please? :)
> 
> yes :-)
> -
> robin
> noisetheatre.blogspot.com

I guess it is absolutely a joke. If not, there will be a disaster, and
that means ruby will rule the world.

-- 
Best regards,
Alec Jang
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: string building

2006-04-03 Thread Chris Mellon
On 4/3/06, John Salerno <[EMAIL PROTECTED]> wrote:
> Out of curiosity, is there any kind of equivalent in Python to the
> StringBuilder class in C#? Here's a quick description from the .NET
> documentation:
>
> "This class represents a string-like object whose value is a mutable
> sequence of characters. The value is said to be mutable because it can
> be modified once it has been created by appending, removing, replacing,
> or inserting characters."
>
> It's used for dealing with large strings that otherwise would cause
> performance problems if used as regular string objects. I'm just
> wondering if Python has something like this, or if it is even really
> necessary. I know there is even some discussion on when exactly
> StringBuilder becomes useful over regular strings, but I imagine at some
> point it is good to use.


The StringIO module (and it's better performing counterpart,
cStringIO)  present a string as a file-like object and are the
appropriate way to incrementally build large strings.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Python Logo Revealed

2006-04-03 Thread Alec Jang
Alec Jang 写道:
> robin 写道:
>> "Giovanni Bajo" <[EMAIL PROTECTED]> wrote:
>>
>>> robin wrote:
>>>
 I have an entry on my blog discussing the new Python logo, which is
 apparently due to replace the current one within the month. I'd be
 interested in what people think of it.

 Surf:
 http://diagrammes-modernes.blogspot.com
>>> Tell me tell me it's an april's joke, please? :)
>> yes :-)
>> -
>> robin
>> noisetheatre.blogspot.com
> 
> I guess it is absolutely a joke. If not, there will be a disaster, and
> that means ruby will rule the world.
> 

Sorry. I made a mistaken. This should have been a replay to "stop
change-- about python 2.5 license "

-- 
Best regards,
Alec Jang
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Getting a list of all classes derived from a base class

2006-04-03 Thread Alex Martelli
Dylan Moreland <[EMAIL PROTECTED]> wrote:
   ...
> > do not use old-style classes: they exist ONLY for backwards
> > compatibility.
   ...
> > and you can call Test.__subclasses__() to get a list of all extant
> > subclassed of Test at any time.
   ...
> Thanks Alex. That's a new one to me -- new-style classes have so many
> strange properties.

You're welcome! Actually, IMHO, it's the _legacy_ style classes which
have odd quirks, as they fail to distinguish cleanly between a type/clas
and its instances, and provide a unified conceptual model.

For example, given an object X which has an attribute named __call__
(has it directly, not from its class/type), does calling X() call
X.__call__()?  In the new-style model, the answer is clear and sharp:
no.  Special methods that Python internally invokes always come from the
type/class, never from the object itself.  In the legacy model, the
answer is fuzzy and muddled: "mostly yes _except_ if X is a class then
no", because if X is a class then X.__call__ is meant to influence the
behavior of calling *instances* of X, only, not that of calling X
itself.

This kind of "conceptual muddle" in oldstyle classes could not be solved
without breaking backwards compatibility, so a parallel concept of
"newstyle" was introduced, and behaves much more simply and predictably;
in Python 3.0, oldstyle will go away -- good riddance!-)

This is quite separate from the fact that, since Python 2.2 where
newstyle objects were introduced, some handy features such as __mro__
and __subclasses__ were introduced -- not to legacy classes, of course,
since you should not use those in new code (not for conceptual reasons).
The "conceptual" side of things can be boiled down to descriptors (and
to a lesser extent, custom metaclasses, but those are rare beasts).


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


Re: Getting a list of all classes derived from a base class

2006-04-03 Thread Alex Martelli
Vijairaj <[EMAIL PROTECTED]> wrote:

> Thanks Dylan and Alex, that was a new learning for me.
> 
> but both the solutions don't work in jython 2.1 is there an alternative
> that will work with jython2.1

Alas, no: your simple idea is essentially the best you can do in any
implementation of Pyhon at 2.1 level.

To put a positive spin on it: if there *WEREN'T* some things that are
much easier and slicker in Python 2.4, with all the years and the work
we've put into Python since 2.1's times, now THAT would be bad!-)

I do hope that Jython does eventually "grow up" to a more modern version
of Python -- unfortunately, I'm too rusty with Java, and not involved
enough in JVM work day by day, to actually help out there, and
apparently so are most potential contributors to Jython:-(


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


Re: "definitive" source on advanced python?

2006-04-03 Thread Alex Martelli
vdrab <[EMAIL PROTECTED]> wrote:

> Thank you.
> 
> The original question was not meant to sound particularly arrogant, and
> as you point out
> a book covering ONLY things like metaprogramming would probably be
> pretty useless in its own way. 

There's a niche market for such books -- "Putting Metaclasses to Work",
for example, an out-of-print book that's about a funky dialect of C++,
did influence the design of Python's new object model, since Guido read
it at just the right time.  But, the book IS out of print and the
language it describes is dead, which are cautionary signs;-).

> I have been using python on and off for
> about a year or so but still find myself staring at some of the funky
> recipes at the aspn cookbook site, not knowing which way is up.
> A good reference seems to be hard to come by, hence the question.
> Thanks for the link, I will have a look at some of the material.

You're welcome!  Besides the 2nd edition of the Nutshell, for which you
should not hold your breath (it's months away yet), and the
presentations on my site, there's a fair amount of material in the 2nd
edition of the printed Cookbook -- we put a immense amount of work into
selecting, discussing, explaining, *and* shoring up the recipes
presented there, most particularly the "black magic" ones (look
especially for the two chapters whose introductions Raymond Hettinger
wrote, both the introductions and contents are quite instructive).  But,
the Cookbook is mostly about examples/uses of language and library
feaures, not a *reference* to them.


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


Re: How to debug python code?

2006-04-03 Thread Johannes Nix
Dennis Lee Bieber <[EMAIL PROTECTED]> writes:

>   My typical debugging technique is the infamous "wolf fence" (there's
> one wolf in Alaska, how do you find it? First build a fence down the
> middle of the state, wait for the wolf to howl, determine which side of
> the fence it is on. Repeat process on that side only, until you get to
> the point where you can see the wolf). In other words; put in a few
> "print" statements until you find the statement that is failing (then
> maybe work backwords from the "tracks" to find out where the wolf/bug
> comes from).


I think the advantage of this method is that one has to become
clear what the state of the program should look like.

For the same reason, unit tests may help to develop a
proper specification of the task of a module.

However, pdb's port mortem debugging can be helpful when a 
program takes a lot of time to hit the error, and
a large amount of data is in play, for example for
numerical computations.

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


Re: Newbie: splitting dictionary definition across two .py files

2006-04-03 Thread Adam DePrince
On Fri, 2006-03-31 at 12:46 -0800, Karthik Gurusamy wrote:
> Ben Finney wrote:
> > [EMAIL PROTECTED] writes:
> >
> > > I'm fairly new to python. I like to define a big dictionary in two
> > > files and use it my main file, build.py
> > >
> > > I want the definition to go into build_cfg.py and build_cfg_static.py.
> >
> > That sounds like a very confusing architecture, and smells very much
> > like some kind of premature optimisation. What leads you to that
> > design? It's very likely a better design can be suggested to meet your
> > actual requirements.
> 
> 
> I work in a source tree of 100s of .c files. The make file builds the
> various .o files from the .c files. It takes a while to finish on the
> first run. When I make changes to a .c file, I need to compile to get
> the .o and also quickly fix any compilation errors.  I don't want to
> use the make infrastructure, as it takes a while to resolve the
> dependencies.

Dependencies for 100 files? 

- Adam 


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


Re: Difference between 'is' and '=='

2006-04-03 Thread Roy Smith
Adam DePrince  <[EMAIL PROTECTED]> wrote:
> It just happens that the
>logical operation 
>
> (a is b ) -> (a == b )
>
>is always True.  

Only for small values of "always".  You can always do pathological
things with operators:

class Foo:
def __eq__ (self, other):
return False

f = Foo()
print f is f
print f == f

frame:play$ ./is.py
True
False

This may even be useful.  What if you were trying to emulate SQL's
NULL?  NULL compares false to anything, even itself.  To test for
NULLness, you have to use the special "is NULL" operator.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best IDE for Python?

2006-04-03 Thread Adam DePrince
On Fri, 2006-03-31 at 09:30 +0200, Fredrik Lundh wrote:
> Dennis Lee Bieber wrote:
> 
> > >   I want to know which is the best IDE for python.Please if
> > > possible mention the features of the IDE.
> >
> > The best IDE is the one that YOU can be most productive in. What /I/
> > find useful may not be of interest to /you/.
> 
> nonsense.  emacs is the best tool for everyone!

Emacs?  Wait, I didn't post anything?  Could this mean I'm not alone! 

- Adam


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


Re: beautiful GUI

2006-04-03 Thread M�ta-MCI
Hi!


Two ideas :
  - WindowsBlind
  - Internet-Explorer + DHTML
  - Flash, like GUI

Oups, there are three ideas  Sorry


@-salutations
-- 
Michel Claveau



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


Re: Difference between 'is' and '=='

2006-04-03 Thread Dave Hansen
On 3 Apr 2006 10:37:11 -0400 in comp.lang.python, [EMAIL PROTECTED] (Roy
Smith) wrote:

>Adam DePrince  <[EMAIL PROTECTED]> wrote:
>> It just happens that the
>>logical operation 
>>
>> (a is b ) -> (a == b )
>>
>>is always True.  
>
>Only for small values of "always".  You can always do pathological
>things with operators:
>
>class Foo:
>def __eq__ (self, other):
>return False
>
>f = Foo()
>print f is f
>print f == f
>
>frame:play$ ./is.py
>True
>False
>
>This may even be useful.  What if you were trying to emulate SQL's
>NULL?  NULL compares false to anything, even itself.  To test for
>NULLness, you have to use the special "is NULL" operator.

Another instance where this may be useful is IEEE-754 NaN.  I don't
have fpconst to verify if that's the case, but I would expect 
NaN is NaN to be true, but NaN == NaN to be false.

Regards,
-=Dave

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


Re: Get the input from user

2006-04-03 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:

> hi,
> I am doing example of address book.when user enter stop and presses
> enter my loop should stop.But there is some prob in my loop.It is
> accepting \r after pressing Enter key.How do i check end of input :
>   addressbook={}
> name = raw_input("Enter Name (stop to Finish)")
> 
> name = EnterAddress(addressbook)
> 
> ShowAddress(name, addressbook)
> 
> def ShowAddress(name, addressbook):
> name = raw_input("Enter Name for Address ")
> print "Address of %s is %s" %(name,addressbook[name])
> 
> def EnterAddress(addressbook):
> while name != "stop":
> entry = raw_input("Enter the address")
> addressbook[name]=entry
> name = raw_input("Enter Name (Leave blank to Finish)")
> return name

Add 'name' to the arguments of EnterAddress, just as you correctly have
it in ShowAddress.


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


Re: string building

2006-04-03 Thread Duncan Booth
John Salerno wrote:

> Out of curiosity, is there any kind of equivalent in Python to the 
> StringBuilder class in C#? 

Yes, usually you use StringIO/cStringIO for this. It works for those 
situations where you just want to append to a string as you build it.

The alternative is just to build up a list of strings and then concatenate 
them all when you are done (using str.join).

If you really need mutable strings you can use the array module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 licensing: stop this change

2006-04-03 Thread Philippe Martin
That was nasty Steve - at least I'm ready for any kind of bad new today ;-)

Regards,


Philippe


Steve Holden wrote:

> As the only director of the Python Software Foundation to vote against a
> recent Board motion to implement the change in licensing terms described
> in
> 
>http://pyfound.blogspot.com/2006/04/python-25-licensing-change.html
> 
> I would like to place on record my protest against this change. I think
> it will harm the Python language and ultimately be counter-productive,
> reducing the user base and discouraging open source programmers from
> contributing to the code base.
> 
> If you disagree with this proposed change it's not too late to do
> something about it. If this change goes ahead it will be the end of
> Python as we know it.
> 
> regards
>   Steve

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


Re: Difference between 'is' and '=='

2006-04-03 Thread Jon Ribbens
In article <[EMAIL PROTECTED]>, Roy Smith wrote:
> This may even be useful.  What if you were trying to emulate SQL's
> NULL?  NULL compares false to anything, even itself.

Strictly speaking, comparing NULL to anything gives NULL, not False.
-- 
http://mail.python.org/mailman/listinfo/python-list


mod_python and PHP sharing same session

2006-04-03 Thread Scott
I am trying to get a mod_python application to read an existing PHP
session.  I need some data that was set in the session by the PHP
application.  I am using the mod_python Session class but even when I
specify the session id that PHP uses the Sesssion(req, sid) call
returns a new session id.  The session file exists in /tmp as
mp_sess.dbm and I have verified that PHP is reading/writing it and from
what I have read mod_python will use the same file.  I have used the
PythonOption session DbmSession in the Apache configuration to force
this and specified the filename as well but to no avail.

Has anyone attermpted what I am trying to perform and if so a short
snippet of code or explanation of how to interface to PHP session via
mod_python would be great.  I am not an experiecne PHP users but have
used mod_python extensively.
Scott

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


Re: Difference between 'is' and '=='

2006-04-03 Thread Duncan Booth
Adam DePrince wrote:

> It just happens that the
> logical operation 
> 
>  (a is b ) -> (a == b )
> 
> is always True.

That is incorrect:

>>> inf = 1e300*1e300
>>> nan = inf-inf
>>> nan is nan, nan==nan
(True, False)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can i design a band-pass filter with scipy?

2006-04-03 Thread Serge Orlov
LabWINC wrote:
> Hi all,
> i would like to design a high pass filter with scipy.signal module.
> ...

I think you'd better ask scipy people at
. Your question requires a lot of
field specific knowledge.

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


Re: String pattern matching

2006-04-03 Thread Eddie Corns
"Jim Lewis" <[EMAIL PROTECTED]> writes:

>Anyone have experience with string pattern matching?
>I need a fast way to match variables to strings. Example:

>string - variables
>
>abcaaab - xyz
>abca - xy
>eeabcac - vxw

>x matches abc
>y matches a
>z matches aab
>w maches ac
>v maches ee

Off topic I know but I've been learning snobol pattern matching recently so I
thought I'd give this one a bash.  Here is my effort:

define('foo(str)')
&fullscan = 1
'/abcaaab/abca/eeabcac/' '/' arb $ x arb $ y arb $ z '/' *x *y '/'
+arb $ v *x arb $ w '/' *foo(v '/' w '/' x '/' y '/' z) :F(end)
foo output = str :(FRETURN)

end

Good eh?  Here's the output:

/eeabcac//abca/aab
e/eabcac//abca/aab
ee/abcac//abca/aab
eea/bcac//abca/aab
eeab/cac//abca/aab
eeabc/ac//abca/aab
eeabca/c//abca/aab
eeabcac///abca/aab
ee/bcac/a/bca/aab
eeabc/c/a/bca/aab
ee/cac/ab/ca/aab
ee/ac/abc/a/aab
ee/c/abca//aab

Removing empty entries is quite easy:

'/abcaaab/abca/eeabcac/' '/' arb $ x arb $ y arb $ z '/' *x *y '/'
+arb $ v *x arb $ w '/' *differ(v) *differ(w) *differ(x)
+*differ(y) *differ(z) *foo(v '/' w '/' x '/' y '/' z) :F(end)

generates:

ee/bcac/a/bca/aab
eeabc/c/a/bca/aab
ee/cac/ab/ca/aab
ee/ac/abc/a/aab

If I get time I'll try to get this working in Sam Wilmott's Python pattern
matching library.

What fun!

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


Re: Can't detect EOF from stdin on windows console

2006-04-03 Thread Serge Orlov
Dmitry Anikin wrote:
> I want to read stdin in chunks of fixed size until EOF
> I want to be able (also) to supply data interactively in console
> window and then to hit Ctrl+Z when finished

[snip fighting with windows]

> Read at most size bytes from the file (less if the read hits EOF before 
> obtaining size bytes).
> According to that, stdin.read(3), when supplied with "12^Z" should return 
> immediately
> with two-character string instead of waiting for third character after EOF.

On windows EOF is recognized only in the beginning of a line. That is
how almost all console applications work on windows. So you have to use
either .readline() method or .read(1)

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


Re: string building

2006-04-03 Thread Sion Arrowsmith
John Salerno  <[EMAIL PROTECTED]> wrote:
>Out of curiosity, is there any kind of equivalent in Python to the 
>StringBuilder class in C#? Here's a quick description from the .NET 
>documentation:
>
>"This class represents a string-like object whose value is a mutable 
>sequence of characters. The value is said to be mutable because it can 
>be modified once it has been created by appending, removing, replacing, 
>or inserting characters."

You can get a long way with list of characters wrapped in list() and
"".join(). Seems to me like the main gotcha is to be careful with things
like:
>>> mutable_string = list("initial\nvalue")
>>> mutable_string[7] = "\r\n"
and make sure you do:
>>> mutable_string[7:8] = "\r\n"

(Although note that you have to spell find() and other string
methods "".join(mutable_string).find("value").)

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

can I get the index number in for x in y loop?

2006-04-03 Thread JuHui
>>> a='String'
>>> for x in a:
... print x
...
S
t
r
i
n
g
>>>

can I get the index number  of a in the upon loop within for x in a
loop?

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


Capturing stdout without waiting for the process end

2006-04-03 Thread Luigi
Hi to all!

I'd like to execute an external program capturing the stdout/stderr
messages at "real-time". I mean that I don't want to wait for the end
of the process. If I write a code like this:

import os
import sys

class Runner:

def run(self, arg):
try:
fin, fout = os.popen4(arg)
self.outData = fout.readlines()
self.outStatus = fout.close()

except Exception, err:
print err

def printOut(self):
print "###"
print self.outStatus
print "###"
for line in self.outData:
print line


r = Runner()
r.run("ls /tmp")
r.printOut()

I can print out (in this case in the os.stdout, but it may be
elsewhere) the whole external program output only once it ends. How can
I do to intercept the external program output during the processing?

Thank you in advance

Luigi

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


Re: mod_python and PHP sharing same session

2006-04-03 Thread Diez B. Roggisch
Scott wrote:

> I am trying to get a mod_python application to read an existing PHP
> session.  I need some data that was set in the session by the PHP
> application.  I am using the mod_python Session class but even when I
> specify the session id that PHP uses the Sesssion(req, sid) call
> returns a new session id.  The session file exists in /tmp as
> mp_sess.dbm and I have verified that PHP is reading/writing it and from
> what I have read mod_python will use the same file. 

Where did you read that? I seriously doubt that - simply because the
internal representations of data stored in sessions are most likely
incompatible between python and php - not sure what mod_pythonuses, but I
guess pickle. And php will use whatever php uses.

So - if you already know the session file, you'd might be able to parse it
yourself. Alternatively, you might consider using cookies for the shared
state.

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


Re: can I get the index number in for x in y loop?

2006-04-03 Thread Luigi
Try this:

>>> a='String'
>>> i=0
>>> for x in a:
...   print i, x
...   i+=1
...
0 S
1 t
2 r
3 i
4 n
5 g

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


Re: can I get the index number in for x in y loop?

2006-04-03 Thread Paul McGuire
"JuHui" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> >>> a='String'
> >>> for x in a:
> ... print x
> ...
> S
> t
> r
> i
> n
> g
> >>>
>
> can I get the index number  of a in the upon loop within for x in a
> loop?
>

Use enumerate.  See example below.

-- Paul

>>> a = "String"
>>> for x in a:
...   print x
...
S
t
r
i
n
g
>>> for x in enumerate(a):
...   print x
...
(0, 'S')
(1, 't')
(2, 'r')
(3, 'i')
(4, 'n')
(5, 'g')
>>>


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


Re: can I get the index number in for x in y loop?

2006-04-03 Thread Rune Strand

JuHui wrote:
> >>> a='String'
> >>> for x in a:
> ... print x
> ...
> S
> t
> r
> i
> n
> g
> >>>
>
> can I get the index number  of a in the upon loop within for x in a
> loop?

for x, y in enumerate(a)
print x, y

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


Re: Can't detect EOF from stdin on windows console

2006-04-03 Thread Peter Hansen
Serge Orlov wrote:
> Dmitry Anikin wrote:
>>I want to read stdin in chunks of fixed size until EOF
>>I want to be able (also) to supply data interactively in console
>>window and then to hit Ctrl+Z when finished
> 
> [snip fighting with windows]
> 
>>Read at most size bytes from the file (less if the read hits EOF before 
>>obtaining size bytes).
>>According to that, stdin.read(3), when supplied with "12^Z" should return 
>>immediately
>>with two-character string instead of waiting for third character after EOF.
> 
> On windows EOF is recognized only in the beginning of a line. That is
> how almost all console applications work on windows. So you have to use
> either .readline() method or .read(1)

Weird... I never knew this, although I had noticed-in-passing that 
hitting ^Z to exit the interpreter didn't always work as intended.  Nice 
to have an explanation why.

On a related note though: EOF _is_ recognized in mid-line if you are 
just reading from a file (in text mode, obviously, not binary mode).  I 
wonder what freakish design decisions led to that situation...

-Peter

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


Re: can I get the index number in for x in y loop?

2006-04-03 Thread JuHui
which one has best performance?

a:for i in range(0,len(a))
b:for x in a
c:for x,y in enumerate(a)

but, it seems I cann't get index number with b format..:(

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


Re: mod_python and PHP sharing same session

2006-04-03 Thread Jim Gallacher
Scott wrote:
> I am trying to get a mod_python application to read an existing PHP
> session.  I need some data that was set in the session by the PHP
> application.  I am using the mod_python Session class but even when I
> specify the session id that PHP uses the Sesssion(req, sid) call
> returns a new session id.  The session file exists in /tmp as
> mp_sess.dbm and I have verified that PHP is reading/writing it and from
> what I have read mod_python will use the same file.  I have used the
> PythonOption session DbmSession in the Apache configuration to force
> this and specified the filename as well but to no avail.
> 
> Has anyone attermpted what I am trying to perform and if so a short
> snippet of code or explanation of how to interface to PHP session via
> mod_python would be great.  I am not an experiecne PHP users but have
> used mod_python extensively.
> Scott

It shouldn't be a suprise that this doen't work. Mod_python stores its 
session data as a python pickle. PHP stores its session data as... well 
I have no idea, but I'm pretty sure it won't be a python pickle. ;) 
Mod_python creates a new session if it can't load valid session data 
from the dbm file, which will always be the case here as that file 
contains PHP formatted session data.

You have 2 choices: Rewrite PHP session handling to write the data as a 
python pickle, or subclass mod_python BaseSession to read the PHP data 
format.  Once that's done you'll need to figure out how to handle 
session locking between the 2 modules, which may not be trivial.

I'd suggest joining the mod_python mailing list if you want to discuss 
this in detail.

Jim

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


Convertion of Unicode to ASCII NIGHTMARE

2006-04-03 Thread ChaosKCW
Hi

I am reading from an oracle database using cx_Oracle. I am writing to a
SQLite database using apsw.

The oracle database is returning utf-8 characters for euopean item
names, ie special charcaters from an ASCII perspective.

I get the following error:
>SQLiteCur.execute(sql, row)
>UnicodeDecodeError: 'ascii' codec can't decode byte 0xdc in position 12: 
>ordinal not in >range(128)

I have googled for serval days now and still cant get it to encode to
ascii.

I encode the SQL as follows:

sql = "insert into %s values %s" % (SQLiteTable, paramstr)
sql.encode('ascii', 'ignore')

I then code each of the row values returned from Oracle like this:

 row = map(encodestr, row)
 SQLiteCur.execute(sql, row)

where encodestr is as follows:

def encodestr(item):
if isinstance(item, types.StringTypes):
   return unicodedata.normalize('NFKD', unicode(item, 'utf-8',
'ignore')).encode('ASCII', 'ignore')
else:
   return item

I have tried a thousand of similiar functions to the above,
permitations of the above from various google searches. But I still get
the above exception on the line:

 SQLiteCur.execute(sql, row)

and the exception is reslated to the data in one field.

Int the end I resorted to using oracles convert function in the SQL
statement but would like to  understand why this is happening and why
its so hard to convert the string in python. I have read many
complaints about this from other people some of whom have written
custom stripping routines. I havent tried a custom routine yet, cause I
think it should be possilble in python.

Thanks,

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


question about nasty regex

2006-04-03 Thread Peter
I'm wondering if someone can tell me whether the following set of 
regex substitutions is possible. I want to convert parallel legal 
citations into single citations. What I mean is, I want to change, e.g.:

"Doremus v. Board of Education of Hawthorne, 342 U.S. 429, 434, 72 
S. Ct. 394, 397, 96 L.Ed. 475 (1952)."

into:

"Doremus v. Board of Education of Hawthorne, 342 U.S. 429, 434 (1952)."

Generally, the beginning pattern would consist of:

1. Two names, consisting of one or more words, always separated by a 
"v."

2. One, two, or three citations, each of which always has a volume 
number ("342") followed by a name, consisting of one or two word 
units always ending with "." ("U.S."), followed by a page number ("429")

3. Each citation may contain a comma and a second page number (", 434")

4. Optionally, a parenthesized year ("(1952)")

5. A final "."

I am thinking this is impossible, but I thought that if it were 
possible to translate this into Python code, someone here could put 
me on the right track.

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


Re: can I get the index number in for x in y loop?

2006-04-03 Thread Felipe Almeida Lessa
Em Seg, 2006-04-03 às 08:47 -0700, JuHui escreveu:
> which one has best performance?

Let's see...

> a:for i in range(0,len(a))

$ python2.4 -mtimeit -s 'a=[None]*100' 'for i in range(len(a)):
j = a[i]
'
10 loops, best of 3: 17.7 usec per loop

$ python2.4 -mtimeit -s 'a=[None]*100' 'for i in xrange(len(a)):
j = a[i]
'
10 loops, best of 3: 16.8 usec per loop

> b:for x in a

$ python2.4 -mtimeit -s 'a=[None]*100' 'i = 0
for j in a:
i += 1
'
10 loops, best of 3: 15.7 usec per loop

> c:for x,y in enumerate(a)

$ python2.4 -mtimeit -s 'a=[None]*100' 'for i, j in enumerate(a):
pass
'
10 loops, best of 3: 12.9 usec per loop


Using enumerate is cleaner and faster.

HTH,

-- 
Felipe.

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

Re: Convertion of Unicode to ASCII NIGHTMARE

2006-04-03 Thread Paul Boddie
ChaosKCW wrote:
> Hi
>
> I am reading from an oracle database using cx_Oracle. I am writing to a
> SQLite database using apsw.
>
> The oracle database is returning utf-8 characters for euopean item
> names, ie special charcaters from an ASCII perspective.

And does cx_Oracle return those as Unicode objects or as plain strings
containing UTF-8 byte sequences? It's very important to distinguish
between these two cases, and I don't have any experience with cx_Oracle
to be able to give advice here.

> I get the following error:
> >SQLiteCur.execute(sql, row)
> >UnicodeDecodeError: 'ascii' codec can't decode byte 0xdc in position 12: 
> >ordinal not
> > in range(128)

It looks like you may have Unicode objects that you're presenting to
sqlite. In any case, with earlier versions of pysqlite that I've used,
you need to connect with a special unicode_results parameter, although
later versions should work with Unicode objects without special
configuration. See here for a thread (in which I seem to have
participated, coincidentally):

http://mail.python.org/pipermail/python-list/2002-June/107526.html

> I have googled for serval days now and still cant get it to encode to
> ascii.

This is a tough thing to find out - whilst previous searches did
uncover some discussions about it, I just tried and failed to find the
enlightening documents - and I certainly didn't see many references to
it on the official pysqlite site.

Paul

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


Re: Convertion of Unicode to ASCII NIGHTMARE

2006-04-03 Thread Robert Kern
ChaosKCW wrote:
> Hi
> 
> I am reading from an oracle database using cx_Oracle. I am writing to a
> SQLite database using apsw.
> 
> The oracle database is returning utf-8 characters for euopean item
> names, ie special charcaters from an ASCII perspective.

I'm not sure that you are using those terms correctly. From your description
below, it seems that your data is being returned from the Oracle database as
unicode strings rather than regular strings containing UTF-8 encoded data. These
European characters are not "special characters from an ASCII perspective;" they
simply aren't characters in the ASCII character set at all.

> I get the following error:
> 
>>   SQLiteCur.execute(sql, row)
>>UnicodeDecodeError: 'ascii' codec can't decode byte 0xdc in position 12: 
>>ordinal not in >range(128)
> 
> I have googled for serval days now and still cant get it to encode to
> ascii.

Don't. You can't. Those characters don't exist in the ASCII character set.
SQLite 3.0 deals with UTF-8 encoded SQL statements, though.

http://www.sqlite.org/version3.html

> I encode the SQL as follows:
> 
> sql = "insert into %s values %s" % (SQLiteTable, paramstr)
> sql.encode('ascii', 'ignore')

The .encode() method returns a new value; it does not change an object inplace.

  sql = sql.encode('utf-8')

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: binascii.a2b_binary

2006-04-03 Thread Scott David Daniels
Ed Swarthout wrote:
> Why is there no binascii.a2b_binary(bitstr) which returns the binary data 
> represented by the bit string?  Like:
> 
 binascii.a2b_binary('0011001100110101')
> '35'
 > perl has pack("B*", "0011001100110101");

What, you mean like:
 int('0011001100110101', 2)
Which you could show as:
 hex(int('0011001100110101', 2))

I guess because Python is not so wonderful as Perl.  Apparently Python
stupidly forgot to follow Perl's great naming conventions.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Capturing stdout without waiting for the process end

2006-04-03 Thread [EMAIL PROTECTED]
What OS are you doing this on?

I had an issue similar to this and it was due to default buffering
behavior of my tty's.  If I recall correctly I executed a bunch of
settty to eliminate the buffering behavior of stdout.  The set the
terminal back to it's original setting when my program was done.

Anand

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


Re: can I get the index number in for x in y loop?

2006-04-03 Thread JuHui
thanks a lot!
:)

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


Re: Convertion of Unicode to ASCII NIGHTMARE

2006-04-03 Thread Diez B. Roggisch
> Don't. You can't. Those characters don't exist in the ASCII character set.
> SQLite 3.0 deals with UTF-8 encoded SQL statements, though.

That is not entirely correct - one can, if losing information is ok. The OPs
code that normalized UTF-8 to NFKD, an umlaut like ä is transformed to a
two-character-sequence basically saying "a with two dots on top". With
'ignore' specified as parameter to the encoder, this should be result in
the letter a.


Regards,

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

Re: Convertion of Unicode to ASCII NIGHTMARE

2006-04-03 Thread Paul Boddie
Oh, and it occurs to me, as I seem to have mentioned a document about
PgSQL rather than pysqlite (although they both have the same principal
developer), that you might need to investigate the client_encoding
parameter when setting up your connection. The following message gives
some information (but not much):

http://groups.google.com/group/comp.lang.python/msg/f27fa9866c9b7b5f

Sadly, I can't find the information about getting result values as
Unicode objects, but I believe it involves some kind of SQL comment
that you send to the database system which actually tells pysqlite to
change its behaviour.

Paul

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


  1   2   >