Re: ignore specific data

2005-11-21 Thread Bengt Richter
On 21 Nov 2005 13:59:12 -0800, [EMAIL PROTECTED] wrote:

>I tried the solutions you provided..these are not as robust as i
>thought would be...
>may be i should put the problem more clearly...
>
>here it goes
>
>I have a bunch of documents and each document has a header which is
>common to all files. I read each file process it and compute the
>frequency of words in each file. now I want to ignore the header in
>each file. It is easy if the header is always at the top. but
>apparently its not. it could be at the bottom as well. So I want a
>function which goes through the file content and ignores the common
>header and return the remaining text to compute the frequencies..Also
>the header is not just one line..it includes licences and all other
>stuff and may be 50 to 60 lines as well..This "remove_header" has to be
>much more efficient as the files may be huge. As this is a very small
>part of the whole problem i dont want this to slow down my entire
>code...
>
Does this "header" have fixed-constant-string beginning and similar
fixed end with possibly variably text between? I.e., and can there be
multiple headers (i.e., header+ instead of header)?

Assuming this is a grammar[1] of your file:

datafile: [leading_string] header+ [trailing_string]
header: header_start header_middle header_end

0) is this a text file of lines? or?
1) is header_start a fixed constant string?
2) does header_start begin with the first character of a line?
3) does it end with the end of the same or 3a) subsequent line?
4) does header_end begin at the beginning of a line?
4a) like 3
4b) like 3a
5) can we ignore header_middle as never containing header_end in any
   form (e.g. in quotes or comments etc)?
6) Anything else you can think of ;-)


[1] using [x] to mean optional x and some_name to mean a string composed
by some rules given by some_name: ... (or described in prose as here ;-)
and some_name+ to mean one or more some_name. (BTW some_name would mean
exactly one, [some_name] zero or one, some_name* zero or morem and somename+
one or more). What's needed is the final resolution to actual constants
or patterns of primitives. Can you define

header_start: "The actual fixed constant character string defining the 
header"
header_end: "whatever?"

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


Re: Backwards compatibility [was Re: is parameter an iterable?]

2005-11-21 Thread Fredrik Lundh
Alex Martelli wrote:

> > In the specific case of iter(), are there good
> > alternative ways of detecting an iterable without
> > consuming it?
>
> Not a problem I've had often, but when I did, if I recall correctly, I
> did something like:
>
> try:
>   iter
> except NameError:
>   def isiterable(x):
> try: x[0]
> except Exception: return 0
> else: return 1
> else:
>   def isiterable(x):
> try: iter(x)
> except TypeError: return 0
> else: return 1
>
> Not True/False because they wouldn't be available in 2.0 any more than
> iter would.  "Consuming" didn't really come into consideration for the
> backwards compatibility part because only objects indexable with
> integers, 0 and up (and raising IndexError at some point) were usable in
> for statements in old Pythons, there was no "consuming".

Before the iterator protocol was added, using the sequence protocol
to implement "forward-only iterators" weren't uncommon. e.g.

class my_file_iterator:
def __init__(self, file):
self.file = file
def __getitem__(self, index):
line = self.file.readline()
if not line:
raise IndexError
return line

(for extra points, add code that makes sure that the index matches
the line number)

To test for this, you could look for __getitem__ methods on instance
objects, and use operator.isSequenceType on everything else, but that
doesn't distinguish between sequences and mappings.

> short of actually trying the loop, there's no infallible way that I know of.

Exactly.  And iter() can fail too, even if it's far less likely that you
stumble upon an iterable that misbehaves if you call __iter__ one
extra time.  Which is why the portable pragmatic pythonic solution
is to design your program so it doesn't depend on type/interface
testing.

If you want to loop over things, loop over things, and leave it to
Python to raise an exception if you get something that doesn't
support looping.

And unless you have very good reasons, you should treat that
exception as a bug in your program.





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


Re: Any royal road to Bezier curves...?

2005-11-21 Thread Claudio Grondi
> http://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm
> has a Python example implementation of qubic Bezier curves available.

Here my port to Tkinter (doesn't need PIL)

from Tkinter import *
master = Tk()
objTkCanvas = Canvas(master, width=110, height=180)
objTkCanvas.pack()

def midpoint((x1, y1), (x2, y2)):
  return ((x1+x2)/2, (y1+y2)/2)

MAX_LEVEL = 5
def drawCubicBezierCurveToCanvas(P1, P2, P3, P4, level=1):
  # global MAX_LEVEL
  # global objTkCanvas
  if level == MAX_LEVEL:
objTkCanvas.create_line(P1[0],P1[1],P4[0],P4[1], fill='red', width=1.5)
  else:
L1 = P1
L2 = midpoint(P1, P2)
H  = midpoint(P2, P3)
R3 = midpoint(P3, P4)
R4 = P4
L3 = midpoint(L2, H)
R2 = midpoint(R3, H)
L4 = midpoint(L3, R2)
R1 = L4
drawCubicBezierCurveToCanvas(L1, L2, L3, L4, level+1)
drawCubicBezierCurveToCanvas(R1, R2, R3, R4, level+1)
  #:if/else level == MAX_LEVEL
#:def draw_curve(P1, P2, P3, P4, level=1)

objTkCanvas.create_rectangle(10, 10, 100, 100, fill="yellow")
objTkCanvas.create_line( 10, 20, 100,  20, fill="green")
objTkCanvas.create_line( 10, 30, 100,  30, fill="green")
objTkCanvas.create_line( 10, 40, 100,  40, fill="green")
objTkCanvas.create_line( 10, 50, 100,  50, fill="green")
objTkCanvas.create_line( 10, 60, 100,  60, fill="green")
objTkCanvas.create_line( 10, 70, 100,  70, fill="green")
objTkCanvas.create_line( 10, 80, 100,  80, fill="green")
objTkCanvas.create_line( 10, 90, 100,  90, fill="green")
objTkCanvas.create_line( 20, 10,  20, 100, fill="green")
objTkCanvas.create_line( 30, 10,  30, 100, fill="green")
objTkCanvas.create_line( 40, 10,  40, 100, fill="green")
objTkCanvas.create_line( 50, 10,  50, 100, fill="green")
objTkCanvas.create_line( 60, 10,  60, 100, fill="green")
objTkCanvas.create_line( 70, 10,  70, 100, fill="green")
objTkCanvas.create_line( 80, 10,  80, 100, fill="green")
objTkCanvas.create_line( 90, 10,  90, 100, fill="green")

drawCubicBezierCurveToCanvas((10,10),(100,100),(100,10),(100,100))

objTkCanvas.create_text( 10, 130, anchor='sw', text='Bezier curve:',
font='Arial   10')
objTkCanvas.create_text( 10, 140, anchor='sw', text=' P1=( 10, 10)',
font='Courier  8')
objTkCanvas.create_text( 10, 150, anchor='sw', text=' P2=(100,100)',
font='Courier  8')
objTkCanvas.create_text( 10, 160, anchor='sw', text=' P3=(100, 10)',
font='Courier  8')
objTkCanvas.create_text( 10, 170, anchor='sw', text=' P4=(100,100)',
font='Courier  8')

mainloop() # show the Tkinter window with the diagram of the cubic Bezier
curve


> http://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm
>
> has a Python example implementation of qubic Bezier curves available.
>
> Claudio
>
> "Warren Francis" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
> news:[EMAIL PROTECTED]
> > I'm fairly new to Python (2-3 months) and I'm trying to figure out a
> simple
> > way to implement Bezier curves...  So far I've tried the following:
> >
> > http://runten.tripod.com/NURBS/
> > ...which won't work because the only compiled binaries are for Windows
> 2000,
> > python 2.1.  I'm on Windows XP (for now), using Python 2.4.  I
downloaded
> > the source distribution, but the header files aren't included, so I'm
not
> > sure how to compile it.
> >
> > It appears there's some bezier functionality in the python that comes
> > Blender... but I'm not savvy enough yet to try and extract whatever
makes
> > beziers work there, to make it work in my general-purpose Python
programs.
> >
> > Basically, I'd like to specify a curved path of an object through space.
> 3D
> > space would be wonderful, but I could jimmy-rig something if I could
just
> > get 2D...  Are bezier curves really what I want after all?
> >
> > Any thoughts would be much appreciated.  I've got some ideas I want to
> test,
> > but if I can't find a simple implementation of curves, I'm going to get
so
> > bogged down in trying to do that part, I'll never get to what I'm
excited
> > about. :-P
> >
> > Warren
> >
> >
>
>


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


Re: How to paste python code on wordpress?

2005-11-21 Thread could ildg
Thank you very much Dan.I settle the problem according to you tips.On 11/22/05, Dan Lowe <[EMAIL PROTECTED]
> wrote:On Nov 22, 2005, at 12:30 AM, could ildg wrote:> Thank you~
> It works!> but how can paste "<" and ">", please?> these 2 symbols will also confuse wordpress and I can't publish> what I want.Replace < with <
Replace > with >(where those abbreviations stand for "less than" and "greater than")Before: if x < 5:After: if x < 5:Another common character in code that you "should" do similarly is
the double quote ("). For that, use "Before: if x == "foo":After: if x == "foo":  -dan--Any society that needs disclaimers has too many lawyers.  -Erik Pepke

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

Re: Any royal road to Bezier curves...?

2005-11-21 Thread Claudio Grondi
http://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm

has a Python example implementation of qubic Bezier curves available.

Claudio

"Warren Francis" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> I'm fairly new to Python (2-3 months) and I'm trying to figure out a
simple
> way to implement Bezier curves...  So far I've tried the following:
>
> http://runten.tripod.com/NURBS/
> ...which won't work because the only compiled binaries are for Windows
2000,
> python 2.1.  I'm on Windows XP (for now), using Python 2.4.  I downloaded
> the source distribution, but the header files aren't included, so I'm not
> sure how to compile it.
>
> It appears there's some bezier functionality in the python that comes
> Blender... but I'm not savvy enough yet to try and extract whatever makes
> beziers work there, to make it work in my general-purpose Python programs.
>
> Basically, I'd like to specify a curved path of an object through space.
3D
> space would be wonderful, but I could jimmy-rig something if I could just
> get 2D...  Are bezier curves really what I want after all?
>
> Any thoughts would be much appreciated.  I've got some ideas I want to
test,
> but if I can't find a simple implementation of curves, I'm going to get so
> bogged down in trying to do that part, I'll never get to what I'm excited
> about. :-P
>
> Warren
>
>


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


Re: Any college offering Python short term course?

2005-11-21 Thread Neal Norwitz
There is the BayPiggies user group:  [EMAIL PROTECTED]  It meets
monthly alternating between Mt. VIew (Google) and San Bruno (IronPort).

n
--

bruce wrote:
> hey...
>
> i'm looking for classes (advanced) in python/php in the bay area as well...
> actually i'm looking for the students/teachers/profs of these classes... any
> idea as to how to find them. calling the various schools hasn't really been
> that helpful. The schools/institutions haven't had a good/large selection...
> it appears that some of the classes are taught by adjunct/part-time faculty,
> and they're not that easy to get to...
>
> if anybody knows of user-groups that also have this kind of talent, i'd
> appreciate it as well...
>
> send responses to the list as well!!!
>
> thanks
>
> -bruce
>
>
> -Original Message-
> From: [EMAIL PROTECTED]
> [mailto:[EMAIL PROTECTED] Behalf
> Of arches73
> Sent: Sunday, November 20, 2005 4:04 PM
> To: python-list@python.org
> Subject: Any college offering Python short term course?
>
>
> Hi,
>
> I want to learn Python.  I appreciate if someone point me to the
> colleges / institutions offering any type of course in Python
> programming in the Bay area CA. Please send me the links to my email.
>
> Thanks,
> Arches
> 
> 
> 
> --
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Command line

2005-11-21 Thread Bengt Richter
On Mon, 21 Nov 2005 19:39:42 -0500, Peter Hansen <[EMAIL PROTECTED]> wrote:

>amfr wrote:
>> Thanks for your help.  Another question, is there an built in md5/sha1
>> function in python?
>
>Yes.
>
>Although it's a long list, it is worthwhile as a newbie for one to 
>peruse the list of standard modules from time to time, until you gain a 
>familiarity with what is there.
>
>http://docs.python.org/modindex.html
>
Worthwhile as oldbies too ;-)

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


Re: How to paste python code on wordpress?

2005-11-21 Thread Dan Lowe

On Nov 22, 2005, at 12:30 AM, could ildg wrote:

> Thank you~
> It works!
> but how can paste "<" and ">", please?
> these 2 symbols will also confuse wordpress and I can't publish  
> what I want.

Replace < with <

Replace > with >

(where those abbreviations stand for "less than" and "greater than")

Before: if x < 5:

After: if x < 5:

Another common character in code that you "should" do similarly is  
the double quote ("). For that, use "

Before: if x == "foo":

After: if x == "foo":

  -dan

-- 
Any society that needs disclaimers has too many lawyers.  -Erik Pepke


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


Looking for magic method to override to prevent dict(d) from grabbing subclass inst d contents directly

2005-11-21 Thread Bengt Richter
Has anyone found a way besides not deriving from dict?
Shouldn't there be a way?
TIA
(need this for what I hope is an improvement on the Larosa/Foord OrderedDict ;-)

I guess I can just document that you have to spell it dict(d.items()), but I'd
like to hide the internal shenanigans ;-)

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


Re: Backwards compatibility [was Re: is parameter an iterable?]

2005-11-21 Thread Steven D'Aprano
Alex Martelli wrote:

> "Consuming" didn't really come into consideration for the
> backwards compatibility part because only objects indexable with
> integers, 0 and up (and raising IndexError at some point) were usable in
> for statements in old Pythons, there was no "consuming".

Ah yes, of course. How quickly we forget: you couldn't 
say "for line in file...". No generators either.

But there was still at least one object that was 
consumable: xreadlines.

Still, I think using an xreadlines object is an unusual 
enough case that I'm not going to lose any sleep about 
it. Document it as a known issue and forget it *wink*

[snip]

> This kind of spaghetti code is what gives backwards compatibility its
> bad name, of course.  Be sure that you're getting paid for this in
> proportion to its ugliness, and your finances should be set for life.

Hah, I wish!


Thanks for the assistance, I learnt a lot. Let's hope I 
don't have to use it ever again...


-- 
Steven.

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


Re: keys in dictionary

2005-11-21 Thread Martin v. Löwis
Shi Mu wrote:
> I run the following code and got wrong message, but I still want to 
> make [1,2],[4,3] and [6,9] to be keys of the dictionary or change the
> style a little bit. How to do that?

Make them tuples:

 >>> p=[[1,2],[4,3],[6,9]]
 >>> n=dict([(tuple(x),[]) for x in p])
 >>> n
{(6, 9): [], (1, 2): [], (4, 3): []}

Regards,
Martin

P.S. Please don't cross-post.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: linking one extension module to another (Mac OSX)

2005-11-21 Thread Martin v. Löwis
Simon Burton wrote:
> I'm having some trouble linking one extension module to another because
> the linker expects a "lib" prefix and my python modules cannot have
> this prefix.

This is a Good Thing (tm) :-) Don't link extension modules to each
other; this is really asking for trouble. Instead, come up with a
function pointer API in one module, put that into a CObject, and
access the CObject through import statements.

Alternatively, make both extension modules link to the same
backend library.

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


Re: IPv6 RFC 3542 with socket module?

2005-11-21 Thread Martin v. Löwis
Roy Smith wrote:
> Is there any way to access the RFC 3542 defined macros such as 
> ICMP6_FILTER_SETPASSALL() from within the socket module? 

No. Not sure it would belong into the socket module, though:
an icmp module could be developed independently from the socket
module if needed.

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


keys in dictionary

2005-11-21 Thread Shi Mu
I run the following code and got wrong message, but I still want to
make [1,2],[4,3] and [6,9]
to be keys of the dictionary or change the style a little bit. How to do that?
Thanks!

>>> p=[[1,2],[4,3],[6,9]]
>>> n=dict([(x,[]) for x in p])
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: list objects are unhashable
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


python gui using boa

2005-11-21 Thread Ashok
hi,
i am trying to develop a small gui app using boa constructor. say this
app has one frame which has one static text control. i want the frame
to resize itself to the width of the text contrl when i change the
label of the text control via SetLabel(). how can i do this in boa
constructor?

can anybody guide me to a good source for learning the use of sizers in
boa?

thanks

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


Re: How to paste python code on wordpress?

2005-11-21 Thread could ildg
Thank you~It works!but how can paste "<" and ">", please?these 2 symbols will also confuse wordpress and I can't publish what I want.On 11/22/05, 
Dan Lowe <[EMAIL PROTECTED]> wrote:
On Nov 21, 2005, at 8:17 PM, could ildg wrote:> Wordpress.com blog will eat up the spaces before a line,> just as it will trim every line of my article. So I can't paste
> python code indentedly.> Does any one use wordpress blog here?> Please tell me how to leave the sapces as they are when publishing> ariticles on the blog,You can enclose the code in a PRE block, like this:
def foobar(): print "abc" if x == 3: print "def" print "ghi"If you don't care for how it renders in a browser, hack your CSS to
make PRE render in a way you like.  -dan--Well sure the government lies, and the press lies, but in a democracythey aren't the same lies.-Alexis A. Gilliland

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

Re: bsddb185 question

2005-11-21 Thread Martin v. Löwis
thakadu wrote:
> So it seems I am forced to use the bsddb185 module
> which does not have convenient record level methods.
> Am I missing something here or have others eperienced
> tha same?

I think you are missing that bsddb185 implements the
dictionary interface. So you can use [key] to access
the value for a certain key.

Regards,
Martin

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


linking one extension module to another (Mac OSX)

2005-11-21 Thread Simon Burton

Hi,

I'm having some trouble linking one extension module to another because
the linker expects a "lib" prefix and my python modules cannot have
this prefix.

I found two ways of doing it on a linux box (either symlink or create a
dummy .so that links to extension module) but I can get neither of them
work on OSX (let alone windows).

Simon.

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


Re: ownership problem?

2005-11-21 Thread Alex Martelli
Jeffrey Schwab <[EMAIL PROTECTED]> wrote:
   ...
> > You may be gratified to learn that Python's main storage model
> > is reference counted objects, and when an object falls out of
> > all referenced scopes its finalizers run immediately.
> 
> Thanks, that's good to know!  For some reason I had it in my head that
> Python always used mark & sweep.  I'm used to ref-counted collection in
> Perl, but I never relied on it because of a nagging (probably 
> ill-founded) worry about cyclic references.  Does Python have any way
> around this?  Is there a Python equivalent to C++ destructors?

Python (main implementation, known as CPython) uses mark-and-sweep (with
generations &c) to deal with cyclic garbage -- but destructors (__del__
methods) *interfere* with cyclic garbage collection (there may be no
safe order of freeing a bunch of cyclic garbage when objects have
__del__ methods, and Python can't find it if there is, anyway).

> I think Java has had a big influence, too.  People just don't seem to
> want to be bothered with thinking about object life cycles at all.  This
> seems unfortunate to me, because cleanup still has to be done, so it 
> just ends up getting moved outside the objects where it belongs.  I 
> think this hurts abstraction.

Python 2.5 should introduce a 'with' statement that may go partways
towards meeting your qualms; it's an approved PEP, though I do not
recall its number offhand.


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


IPv6 RFC 3542 with socket module?

2005-11-21 Thread Roy Smith
Is there any way to access the RFC 3542 defined macros such as 
ICMP6_FILTER_SETPASSALL() from within the socket module?  A dir() on the 
socket module (Python 2.4.1, built on a solaris box with IPv6 support) 
doesn't show anything that looks like it (and socket.has_ipv6 is True).
-- 
http://mail.python.org/mailman/listinfo/python-list


Application Plugin Framework

2005-11-21 Thread Ron
Hello,

I'm attempting to develop a  plugin framework for an application that I'm 
working on.  I wish to develop something in which all plugins exist in a 
directory tree.  The framework need only be given the root of the tree.  The 
framework then uses os.path.walk to search all for all files named 
'plugin.pyc'.  These are then loaded using imp.load_compiled().  They need 
contain only one variable called 'plugin' which is a reference to an 
instance of the plugin object.  This is extrated from the loaded module 
using getattr.  After that, the plugins are easy to work with since they 
implement a standard interface.  Or so the theory goes.  And this does work 
fine provided the plugin is implemented entirely within that one file.  If 
there are support modules that the main plugin module imports, which exist 
in the plugin's directory, then I get problems.  The imports fail.  I get 
"ImportError:  No module named "

Here's PluginManager.py:


import os


class PluginManager( object ):
   def __init__( self, pluginDir ):
  self._plugins = { }

  os.path.walk( pluginDir, self._addPlugin, None )

   def _addPlugin( self, arg, dirname, names ):
  import imp

  for filename in names:
 fullFilename = os.path.join( dirname, filename )
 if os.path.isfile( fullFilename ) and (filename == 'plugin.pyc'):
module = imp.load_compiled( 'plugin', fullFilename )
self._plugins[ plugin.name ] = getattr( module, 'plugin' )
return

PM = PluginManager( r'C:\Personal\SWDev\ModuleTest' ) # Root of the 
plugin directory tree

print 'Plugin List: ', PM._plugins.keys()

for name,plugin in PM._plugins.iteritems():
   plugin.doSomething( )

print 'done!'

###
My plugin.py file is in C:\Personal\SWDev\ModuleTest\Plugins\MyPlugin.  It's 
called plugin.pyc (which I compiled from the following source by importing 
it into the interactive python shell.
###

import work


class MyPlugin( object ):
   def __init__( self ):
  self.name  = 'MyPlugin'

   def doSomething( self ):
  work.foo( )


plugin = MyPlugin( )

###
Finally, work.py is in the same directory as plugin.py
###

def foo( ):
   print 'foo called'

##
Does anybody have any thoughts on how to get this, or something similar, to 
work?  I really just want to be able to load plugins into my app without 
having to modify my app's source code, or modify some list of plugins.  I 
also would like to allow each plugin to have its own subdirectory so they 
are easily installed or removed.

Thanks for your help.




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


Re: Preventing modules to be read from current working directory

2005-11-21 Thread ssjassal
Great, thanks.

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


Re: Backwards compatibility [was Re: is parameter an iterable?]

2005-11-21 Thread Alex Martelli
Steven D'Aprano <[EMAIL PROTECTED]> wrote:
   ...
> In the specific case of iter(), are there good 
> alternative ways of detecting an iterable without 
> consuming it?

Not a problem I've had often, but when I did, if I recall correctly, I
did something like:

try:
  iter
except NameError:
  def isiterable(x):
try: x[0]
except Exception: return 0
else: return 1
else:
  def isiterable(x):
try: iter(x)
except TypeError: return 0
else: return 1

Not True/False because they wouldn't be available in 2.0 any more than
iter would.  "Consuming" didn't really come into consideration for the
backwards compatibility part because only objects indexable with
integers, 0 and up (and raising IndexError at some point) were usable in
for statements in old Pythons, there was no "consuming".  The tests here
are not 100% reliable, of course -- in 2.0, a dict which just happens to
have a 0 key would erroneously pass; but short of actually trying the
loop, there's no infallible way that I know of.

One possibility (that I haven't tried in real life) to deal with the
hellish situation of having to write code that's able to loop on an
iterable but fail softly otherwise, while not hiding errors in the
loop's body, would be the suitably hellish...:

class NotATypeError(Exception):
  def __init__(self, e, t):
self.e = e
self.t = t

try:
  try:
  for item in whatever:
  try:
  ...loop body here...
  except TypeError, e, t:
  raise NotATypeError(e, t)
  except TypeError:
  fail-softly code...
except NotATypeError, x:
  raise TypeError, x.e, x.t


This kind of spaghetti code is what gives backwards compatibility its
bad name, of course.  Be sure that you're getting paid for this in
proportion to its ugliness, and your finances should be set for life.


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


Re: Preventing modules to be read from current working directory

2005-11-21 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] wrote:

> Is there a way to instruct Python to import modules from standard
> library even if there is one with the same name in the current working
> directory? I was trying to import BaseHTTPServer.py from standard
> library but was prevented by a python file with the same name in
> current working directory (but there was no __init__.py). Can I use
> some warning switch to print a warning on stdout?
> 
> Thanks,
> Sunpreet.

Sure, just modify sys.path so the current directory is not included.  See 
the documentation for the sys module in the library reference for more 
details.
-- 
http://mail.python.org/mailman/listinfo/python-list


Preventing modules to be read from current working directory

2005-11-21 Thread ssjassal
Is there a way to instruct Python to import modules from standard
library even if there is one with the same name in the current working
directory? I was trying to import BaseHTTPServer.py from standard
library but was prevented by a python file with the same name in
current working directory (but there was no __init__.py). Can I use
some warning switch to print a warning on stdout?

Thanks,
Sunpreet.

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


Backwards compatibility [was Re: is parameter an iterable?]

2005-11-21 Thread Steven D'Aprano
Fredrik Lundh wrote:

> Steven D'Aprano wrote:
> 
> 
>>Alas and alack, I have to write code which is backwards
>>compatible with older versions of Python:

[snip]

>>What should I do when I can't rely on functions that
>>don't exist in older versions of Python?
> 
> 
> python 2.1 doesn't support iterators, so that question doesn't
> make much sense.

The _question_ doesn't make much sense? I could 
understand you saying that backwards-compatibility is 
"not important [to me]" but to say that the very 
question of how to maintain backwards compatibility 
makes little sense is a bit extreme, don't you think?

Fredrik, I bow to your superior knowledge about Python, 
no sarcasm intended, and I've learnt a lot from your 
posts, thank you. But this is not one of your shining 
moments. Your attitude was utterly dismissive: the 
"right way" to solve the problem of recognising 
iterables was to use iter, and that's all that needs to 
be said.

The problem of how to recognise iterables did not come 
into existence with version 2.2, and backwards 
compatibility is sometimes a real requirement. A few 
months back I had to mangle some Py2.4 code so that it 
would run under version 2.0, and wasn't that fun.


> if you want to write code that runs under 2.1, you have to write
> your code in terms of what 2.1 supports.

Do you think I don't know this?

I never imagined for an instant that Python 2.1 would 
somehow magically be able to use features that didn't 
exist in Python 2.1. But then it wasn't me saying that 
there was nothing to discuss, the "right way" is to use 
iter(), end of story.

If I have to write code that can't rely on iter() 
existing in the language, what should I do?

Are there practical idioms for solving the metaproblem 
"solve problem X using the latest features where 
available, otherwise fall back on older, less powerful 
features"?

For instance, perhaps I might do this:

try:
 built_in_feature
except NameError:
 # fall back on a work-around
 from backwards_compatibility import \
 feature as built_in_feature

Do people do this or is it a bad idea?

Are there other techniques to use? Obviously refusing 
to run is a solution (for some meaning of "solution"), 
it may even be a practical solution for some cases, but 
is it the only one?

In the specific case of iter(), are there good 
alternative ways of detecting an iterable without 
consuming it?



-- 
Steven.

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


Re: path module / class

2005-11-21 Thread [EMAIL PROTECTED]
Peter Hansen wrote:
> Okay, granted.  I guess this is the same as in any other case of
> deprecation (e.g. some people still have to work with code that uses
> apply() or string module methods).

Yup, this is exactly what will have to happen.  Most or all of os.path
and maybe some of os/glob/fnmatch/stat will have to be deprecated and
kept around for a release or two.  Perhaps a large section of the
PEP-to-come should deal with this.

> > Peter Hansen:
> >> We've mandated use of path.py internally for all projects because
> >> we've noticed (especially with non-expert Python programmers... i.e.
> >> junior and intermediate types, and senior types new to Python) a
> >> decrease in errors.

My personal experience has always been that when it comes time to write
the part of the project that interacts with the filesystem, I have to
decide once again if I want to use the standard library, or use
path.py.  And I usually decide against using path.py; not because I
don't like it, but because I don't like bundling code that I didn't
write as part of my project.  A lot of the programs that I write in
python are pretty simple single file scripts that help manage machines
on an intranet.  I like to be able to simply copy these scripts around
and run them without worrying about their dependencies.

Another personal observation is that the current os.path / fnmatch /
glob / stat modules give a very C-like interface to the filesystem.
There's a lot of repetition of things like os.path.join(),
os.path.splitext(), as well as repetition of the reference to the
string object which defines the path being operated on.  This seems to
violate the DRY principle to a small degree, and it also makes code
that much harder to maintain.

Cheers,
Chris

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


Re: Hot to split string literals that will across two or more lines ?

2005-11-21 Thread Mohammad Jeffry
On 11/22/05, Paul McGuire <[EMAIL PROTECTED]> wrote:
Or for a large literal string:"""lots of text hundreds of characters long
more text on another line but we really don't want any line breaksin our final stringso we replace newlines in this multiline stringwith an empty string thus""".replace('\n','')-- Paul


I love your method. The only drawbacks for this method is I can't tell
whether there is blank space at the end of each lines. For EG: the
above string might be

lots of text hundreds of characters longmore text on another.
   
^
or

lots of text hundreds of characters long more text on another.
   
^ 


-- And whoever does an atom's weight of evil will see it.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: mxODBC sql MSAccess

2005-11-21 Thread BartlebyScrivener
Works!!

Thank you all so much. I didn't know it was coming back as a tuple, and
I'm sure that would have taken me four hours to figure out.

Appreciate it!

bs



Chris Curvey wrote:
> mxODBC implements the Python DB-API spec, which states that each "row"
> of query results is  returned as a tuple.  If you want the data
> displayed differently, you can do it yourself.
> 
> for row in rows:
> print "\t".join(row)
> 
> should do it.

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


pipe related question

2005-11-21 Thread David Reed

Is there any way to have one program run another arbitrary program  
with input from stdin and display the output as if you had run it in  
a shell (i.e., you'd see some of the output followed by the input  
they typed in and then a newline because they pressed return followed  
by subsequent output, etc.).

I can't use readline with the pipe because I don't know how much  
output the arbitrary program has before it calls an input statement.  
I've googled and understand that calling read() will deadlock when  
the program is waiting for input.

When I first write all the input to the input pipe and then call read  
on the output pipe it works just the same as if I had run the program  
as: program < input_file

What I'd like to see is the input intermixed with the output as if  
the user had typed it in.

Thanks,
Dave

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


Re: How to paste python code on wordpress?

2005-11-21 Thread Dan Lowe

On Nov 21, 2005, at 8:17 PM, could ildg wrote:

> Wordpress.com blog will eat up the spaces before a line,
> just as it will trim every line of my article. So I can't paste  
> python code indentedly.
> Does any one use wordpress blog here?
> Please tell me how to leave the sapces as they are when publishing  
> ariticles on the blog,

You can enclose the code in a PRE block, like this:


def foobar():
 print "abc"
 if x == 3:
 print "def"
 print "ghi"


If you don't care for how it renders in a browser, hack your CSS to  
make PRE render in a way you like.

  -dan

-- 
Well sure the government lies, and the press lies, but in a democracy
they aren't the same lies.-Alexis A. Gilliland


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


Re: mxODBC sql MSAccess

2005-11-21 Thread Chris Curvey
mxODBC implements the Python DB-API spec, which states that each "row"
of query results is  returned as a tuple.  If you want the data
displayed differently, you can do it yourself.

for row in rows:
print "\t".join(row)

should do it.

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


Re: mxODBC sql MSAccess

2005-11-21 Thread [EMAIL PROTECTED]

BartlebyScrivener wrote:
> Hello, I'm new to python and trying to get records from an MSAccess
> database using mxODBC. It works, but the output is not formatted the
> way I want it.
>
> Here's the script:
>
> import mx.ODBC.Windows as odbc
>
> driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:/Access
> Databases/Quotations2005'
>
> conn = odbc.DriverConnect(driv)
> c = conn.cursor()
> c.execute ("SELECT Author, Topic1, Topic2, Quote FROM QuotesToTxt WHERE
> Author LIKE 'Mencken%'")
>
> rows = c.fetchall()
> for r in rows:
> print r
>
> And here's what I get:
>
> ('Mencken, H.L.', 'Americans', 'Democracy', 'Democracy is the theory
> that the common people know what they want, and deserve to get it good
> and hard.')
> ('Mencken, H.L.', 'Conscience', 'Mother-In-Law', 'Conscience is a
> mother-in-law whose visit never ends.  The inner voice which warns us
> that someone may be looking.')
>
> Where are the parenthese and single quotes coming from? SQL or mxODBC?

>From Python. You data is stored as a list of tuples.

> And how can I get just simple tab-delimited records with a standard
> carriage return separating the records?

for r in rows:
 print "%s\t%s\t%s\t%s" % r

> 
> Thanks so much for any help.
> 
> bs

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


Re: Any royal road to Bezier curves...?

2005-11-21 Thread Scott David Daniels
The Bezier gives control points with natural interpretations and a
nice "within the convex hull" property.  I happen to like Beziers to
control curves which are aestheticly, rather than computationally
defined.


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


How to paste python code on wordpress?

2005-11-21 Thread could ildg
Wordpress.com blog will eat up the spaces before a line,
just as it will trim every line of my article. So I can't paste python code indentedly.
Does any one use wordpress blog here?
Please tell me how to leave the sapces as they are when publishing ariticles on the blog,
Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list

mxODBC sql MSAccess

2005-11-21 Thread BartlebyScrivener
Hello, I'm new to python and trying to get records from an MSAccess
database using mxODBC. It works, but the output is not formatted the
way I want it.

Here's the script:

import mx.ODBC.Windows as odbc

driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:/Access
Databases/Quotations2005'

conn = odbc.DriverConnect(driv)
c = conn.cursor()
c.execute ("SELECT Author, Topic1, Topic2, Quote FROM QuotesToTxt WHERE
Author LIKE 'Mencken%'")

rows = c.fetchall()
for r in rows:
print r

And here's what I get:

('Mencken, H.L.', 'Americans', 'Democracy', 'Democracy is the theory
that the common people know what they want, and deserve to get it good
and hard.')
('Mencken, H.L.', 'Conscience', 'Mother-In-Law', 'Conscience is a
mother-in-law whose visit never ends.  The inner voice which warns us
that someone may be looking.')

Where are the parenthese and single quotes coming from? SQL or mxODBC?
And how can I get just simple tab-delimited records with a standard
carriage return separating the records?

Thanks so much for any help.

bs

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


Re: Python install minimum requirements

2005-11-21 Thread jepler
If I found the right "U3" when I googled, then maybe this is relevant:
http://www.voidspace.org.uk/python/movpy/

Jeff


pgp1AjuUdEskN.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Why are there no ordered dictionaries?

2005-11-21 Thread Alex Martelli
Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
   ...
> But I think the following rule is "natural" enough to consider it as THE
> standard behavior of ordered dictionaries:
> 
> "Insertion: If the key exists: Don't change the order. If it does not
> exist: Append it to the sequence of keys. Deletion: Remove from the 
> sequence of keys."
> 
> I think this is also the behavior of associative arrays in PHP or Perl

Perl hashes now keep track of 'order of keys'?  That's new to me, they
sure didn't back when I used Perl!  It's been a while, but a little
googling shows me, e.g at
, assertions such as:
"""
Hashes don't maintain key order. To get them in sorted order try:

foreach $i (sort keys(%afiliacao))
"""
which fully match my memories.  Could you produce a URL to support the
hypothesis that Perl has changed its behavior?  What about PHP?  Thanks!

> and could be considered as the "ONE unambiguous definition".

"first insertion (since the last deletion if any)" is ONE unambiguous
definition, but surely not "_the_ ONE" with emphasis on ``the''.  I see
nothing _ambiguous_ (nor _unnatural_) in being interested in the *last*
insertion, for example; indeed if phrased as "upon insertion, put the
key at the end of the sequence" (whether it was already elsewhere in the
sequence of not), with no need for conditionals regarding previous
existence, it might appear more "conceptually compact".

Anyway -- subclassing dict to implement your definition is reasonably
easy, and we could put the resulting package on the Cheese Shop.  I hope
python.org keeps good enough statistics to be able to tell us, a couple
months later, how many people downloaded said package, vs how many
people downloaded a complete Python distro; of course, that ratio is
biased (in favour of the package) by the fact that many people already
have a complete distro available, while initially nobody would have the
package, but if we measure when things settle, after letting a month of
two or 'transient' pass, that effect might be lessened.

If we ran such an experiment, what fraction do you think would serve to
convince Guido that a dict 'ordered' by your definition is necessary in
Python 2.5's standard library (presumably in module 'collections')?


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


Re: Command line

2005-11-21 Thread Peter Hansen
amfr wrote:
> Thanks for your help.  Another question, is there an built in md5/sha1
> function in python?

Yes.

Although it's a long list, it is worthwhile as a newbie for one to 
peruse the list of standard modules from time to time, until you gain a 
familiarity with what is there.

http://docs.python.org/modindex.html

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


Re: BaseHTTPServer module

2005-11-21 Thread amfr
Thanks, all I wanted to know where the post data was stored from the
request

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


Re: Command line

2005-11-21 Thread amfr
Thanks for your help.  Another question, is there an built in md5/sha1
function in python?

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


Re: the name of a module in which an instance is created?

2005-11-21 Thread Mardy
Hi Steven,

Le die Mon, 21 Nov 2005 11:37:37 -0700, Steven Bethard ha scribite:
[...]
> In the basic situation, where the instance is created in the same
module
> as the class, I can figure out 'mod' and 'name' like::
> 
>  cls = type(self)
>  name = cls.__module__
>  mod = __import__(cls.__module__)

I'm not sure I got your problem correctly, however see if this helps:

$ cat > test.py
class myclass:
name = __module__
^D
$ python
Python 2.3.5 (#2, Jun 19 2005, 13:28:00)
[GCC 3.3.6 (Debian 1:3.3.6-6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> a = test.myclass()
>>> a.name
'test'

This works, as we define "name" to be a class attribute. 
Is this useful to you?


-- 
Saluti,
Mardy
http://interlingua.altervista.org

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


Re: Advice on distutils and distribution policies

2005-11-21 Thread Mardy
Hi Magnus,
  thanks a lot for your posting, you made me clear several things.
However, there something I still want to discuss:

Le die Mon, 21 Nov 2005 20:08:24 +0100, Magnus Lycka ha scribite:
[...]
> In an apache cgi-bin directory: The main Python CGI script(s) that are
> called by the web server. These might be scripts that are modified as a
> part of the installation process to e.g. point out data files. These
> should be short files. Import a module, set up configuration and run
> something in the imported module.

Good point!

> Under /usr/lib/python2.x/site-packages/ you keep the bulk of your
> software (as described above).
> 
> HTML and CSS files that are to be handled directly by the web browser is
> placed under Apache's DOCUMENT_ROOT etc. E.g. $DOCUMENT_ROOT/eligante.

Actually, for the moment, this is just the CSS file.

> Data files that are read and processed by you own programs (i.e. not
> directly by the web server) van be anywhere under /var, e.g.
> /var/eligante.

And this is the HTML one (which is a template that is used by the python
scripts).
The number of HTML might even grow in the future, but it's extremely
unlikely they'll be ever more than 5.

I'm even thinking of including the HTML in a python file, that will save
me the trouble of storing it elsewhere.
The other files accessed by the webserver will be the CSS and eventually
some images (and the favicon). For these I'll follow your advice of
storing them under DOCUMENT_ROOT.
This variable, though, seems to be defined only in the processes spawned
by the webserver; so my guess is that I'll have to instruct the setup.py
script to ask the user where his webserver's document root is (either
interactively, or from the command line when invoking the setup script).
I guess this involves subclassing some Distutils class, does anyone have a
starter for this?
Thanks again for your help,
  Alberto

-- 
Saluti,
Mardy
http://interlingua.altervista.org

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


Re: Why are there no ordered dictionaries?

2005-11-21 Thread Bengt Richter
On 21 Nov 2005 01:54:38 -0800, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

>
>Fredrik Lundh wrote:
>> [EMAIL PROTECTED] wrote:
>>
>> > If I need the dict feature 90% of the time, and the list feature 10% of
>> > the time.
>>
>> Wasn't your use case that you wanted to specify form fields in
>> a given order (LIST), render a default view of the form in that
>> order (LIST), and, later on, access the field specifiers in an
>> arbitrary order, based on their key (DICT).  Sure looks like it's
>> the LIST aspect that's important here...
>Yes. But whether LIST aspect or DICT is important is well, opinion. So
>let's leave it there.

>>
>> > I want an ordered dict. Rather than a list and create this new view every
>> > time and every where I want to use it as a dict.
>>
>> You want an ordered dict because you say you want one, not be-
>> cause it's the best way to address your use case.  That's fine, but
>> it's not really related to the question asked in the subject line.
>Again, best way is decided by ME. If I am entering a coding contest
>which is organized by YOU, that is a different story. As for related to
>the subject line, since when I said my preference or use case has
>anything to do with the subject line ? I have said in another post that
>I don't think there should be  one in the standard library, which is
>directly about the subject line.
Ok, so if not in the standard library, what is the problem? Can't find what
you want with google and PyPI etc.? Or haven't really settled on what your
_requirements_ are? That seems to be the primary problem people who complain
with "why no sprollificator mode?" questions. They don't know what they really
mean when it comes down to a DYFR (Define Your Felicitous Requirements) 
challenge.
So DYFR ;-)
Then someone can take less time than many of these posts takes to make a
list subclass that also acts like the dict when you want or a dict subclass that
also acts like a list when you want. Which methods from which would you like
as-is, and which modified? Any additional methods or properties? DYFR ;-)

>
>>
>> > parsing or not parsing is not the point, and parsing/converting is
>> > still "create a new view" of an existing data structure.
>>
So you'd like the mechanics to be automated and hidden? Then you need to
DYFR for using the black box you want. Methods, semantics.

>> Copying the entire data structure hardly qualifies as "creating a
>> new view".  dict() doesn't do that; in this use case, it doesn't cost
>> you anything to use it.
>doesn't cost me anything ? That is good news to me.
Well, if you want something specific, it WILL cost you the effort to DYFR in 
detail ;-)

( posting delayed >12 hrs due to news server prob ;-/ )

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


Re: setattr for secondary attribute

2005-11-21 Thread Bengt Richter
On 20 Nov 2005 20:34:39 -0800, "Alex" <[EMAIL PROTECTED]> wrote:

>I apologize for asking  maybe a very trivial question.
>I have a new class object A with slots. One of the slots is, for
>example, object spam. Object spam, in turn, also has slots and one of
>them is attribute eggs. I need to assign a new value to eggs. In other
>words, I need to perform the following:
>
>A.spam.eggs=newValue
>
>The problem is that I have only a string s='spam.eggs' with which to
>work, so I cannot write an expression written above. I tried to use
>setattr:
>
>setattr(A, s, newValue)
>
>but this does not work. It says that object A does not have attribute
>spam.eggs
>
>How would you do it? TIA.
>
A.spam.eggs=newValue

(which would work) really means, if you break it into steps

(A.spam).eggs = newValue

which is

setattr(getattr(A, 'spam'), 'eggs', newValue)

so you just need to break 'spam.eggs' apart and plug in the pieces.
assuming exactly one dot and no spaces to worry about,

s_spam, s_eggs = s.split('.')

then

setattr(getattr(A, s_spam), s_eggs, newValue)

ought to do the job.

If you have more than one dot, e.g., s = 'spam.eggs.ham'
and eggs has a slot ham that you want to assign to, then you need to
loop on getattr for all but the last name, which you use for the setattr.
Something like (untested)

def setbydots(A, s, val):
names = s.split('.')
for name in names[:-1]:
A = getattr(A, name)
setattr(A, names[-1], val)

This should work for no dots or any number, so long as the reference chain is 
valid.
E.g.,
setbydots(A, 'spam.eggs', newValue)
should accomplish
A.spam.eggs=newValue
as you wanted. I hope ;-)

( posting delayed >12 hrs due to news server prob ;-/ )

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


Re: best cumulative sum

2005-11-21 Thread Bengt Richter
On Mon, 21 Nov 2005 15:23:20 +1100, Steven D'Aprano <[EMAIL PROTECTED]> wrote:

>David (Alan) Isaac wrote:
>
>> What's the good way to produce a cumulative sum?
>> E.g., given the list x,
>> cumx = x[:]
>> for i in range(1,len(x)):
>>  cumx[i] = cumx[i]+cumx[i-1]
>> 
>> What's the better way?
>
>Is there something that this doesn't do, or something 
>it does do that it shouldn't?
>
>You could do it this way:
>
># untested
>def cumulative_sum(L):
> CL = []
> csum = 0
> for x in L:
> csum += x
> CL.append(csum)
> return CL
>
>Whether it is better or worse depends on what you 
>consider better or worse.

I think x[:] ought to be a faster space allocation than building by appending,
but I think there is too much indexing in the OP's version,
so I think I would combine ideas, e.g.,

 # (still ;-) untested
 def cumulative_sum(L):
  CL = L[:]
  csum = 0
  for i, x in enumerate(L):
  csum += x
  CL[i] = csum
  return CL

I minor nit might be in how/when promotions to long or float happen if L has
mixed types. The OP didn't mention any requirements, but e.g. his version won't 
ever
promote the first output element, since he walks replacements from L[1] on.

( posting delayed >12 hrs due to news server prob ;-/ )

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


Re: Why are there no ordered dictionaries?

2005-11-21 Thread Bengt Richter
On Mon, 21 Nov 2005 01:27:22 +0100, Christoph Zwerschke <[EMAIL PROTECTED]> 
wrote:

>Fredrik Lundh wrote:
>> if you restructure the list somewhat
>> d = (
>> ('pid', ('Employee ID', 'int')),
>> ('name', ('Employee name', 'varchar')),
>> ('sal', ('Salary', 'float'))
>> )
>> you can still loop over the list
>> ...
>> but you can easily generate an index when you need it:
>> index = dict(d)
>
>That's exactly the kind of things I find myself doing too often and what 
>I was talking about: You are using *two* pretty redundant data 
>structures, a dictionary and a list/tuple to describe the same thing. 
>Ok, you can use a trick to automatically create the dictionary from the 
>tuple, but still it feels somewhat "unnatural" for me. A "ordered 
>dictionary" would be the more "natural" data structure here.
>
But, as has been mentioned**n, this is only one example of an ordering one
could make default for an "ordered" dictionary. Suppose you say it should
be ordered by insertion order, so
  d = OrderedDict(); d[1]='one'; d[2]='two' =>> list(d) => [1, 2]
ok, now we do d[1]='ein' and what is the order? list(d) => [2, 1] ??
Or do replacements not count as "insertions"? The devil is always going
to be in the details. Maybe you want a model that works more like a list
of key:value pairs with just optimized access to a pair by key name as
well as position in the list. Or maybe you want to permit append and
NOT prevent [('a',1), ('a':2)] and maybe d['a'] => [1, 2] ???

The point is that Python is a nice lego set, and pre-molded castles
don't re-use well, even if they suit a particular you to a t ;-)

Note that is isn't hard to snap a few pieces together to make an ordered
dict to your own specs. But IMO it belongs in pyPI or such, not in the system
library. At least until it gets a lot of mileage -- and MMV ;-)

>I also wanted to mention the uglyness in the definition (nested tuples), 
>but then I understood that even an ordered dictionary would not 
>eliminate that uglyness, since the curly braces are part of the Python 
>syntax and cannot be used for creating ordered dictionaries anyway. I 
>would have to define the ordered dictionary in the very same ugly way:
>
>d = odict(('pid', ('Employee ID', 'int')),
>   ('name', ('Employee name', 'varchar')),
>   ('sal', ('Salary', 'float')))
>
>(Unless the Python syntax would be extend to use double curly braces or 
>something for ordered dictionaries - but I understand that this is not 
>an option.)
>
Whatever your odict does, if I had type a lot of definitions for it
I think I would write a QnD helper to make this work:

 d = odict(prep("""

 pid,  Employee ID,   int
 name, Employee name, varchar # (comments to be ignored)
 sal, Salary, float   # alignment as above not mandatory
 other, Something else, long, additional elements, allowed in second tuple?
 """))

( posting delayed >12 hrs due to news server prob ;-/ )

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


Re: Tkinter's coordinates setting

2005-11-21 Thread Steve Juranich
On 11/17/05, Shi Mu <[EMAIL PROTECTED]> wrote:
> why subtract 1 from max_y - original_y?

Because in the computer science world we like starting to count at 0.

image_size = 1000
original_y = 25 # Really the 26th pixel line.
new_y = 1000 - 25 - 1 # 26 pixels from the bottom of the screen.

--
Steve Juranich
Tucson, AZ
USA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why are there no ordered dictionaries?

2005-11-21 Thread Bengt Richter
On 20 Nov 2005 21:12:52 -0800, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

>
>Bengt Richter wrote:
>> On Sun, 20 Nov 2005 22:03:34 +0100, Christoph Zwerschke <[EMAIL PROTECTED]> 
>> wrote:
>> >> Ordering the keys isn't the normal case, and can be done easily when
>> >> needed.
>> >
>> >That depends. Maybe I do not want the keys to be sorted alphabetically,
>> >but according to some criteria which cannot be derived from the keys
>> >themselves.
>> You mean involving also the values? What's wrong with
>> sorted(plaindict.items(), key=your_ordering_function) ?
>>
>Not according to the content of the data, not just the "key". Or in
>other words, some other metadata that is not present in the data. A
>typical thing, like order of creation. Or some arbitary order. For
>example :
>
>I present a data grid/table in a HTML form and the user just drag and
>drop and rearrange the columns order.
  ^^[1]
[1] implies known info of before and after rearrangement. Where do these
come from, and are the two states expressed as ordered sets of keys generated 
and stored somewhere?
The point is, to re-order, you need a mapping from unordered data dict keys to 
values which the sorted
builtin function will order in the way you want. (BTW, if you use DSU, make 
sure the data is not modifying
your sort in an undesired way. Passing a key function to sorted makes it easy 
to exclude unwanted data from
the sort). If you have data that determines a new ordering of keys, it has to 
be accessed somehow, so
you just need to make it accessible to a handy helper that will generate your 
key function. E.g,
with before and after lists of keys expressing e.g. drag-drop before and after 
orderings, lambda can do the
job of getting you dict items in the new order, e.g., where bef and aft are 
lists that define the desired orderings
before and after in the sense of sort_precedence = bef.index[key_in_bef] and 
same for aft.

sorted(thedict.items(),key=lambda t:dict(zip(bef,((k in aft and 
aft.index(k) or len(aft)+bef.index(k)) for k in bef))[t[0]])

Ok, that one-liner grew a bit ;-)
>
>Of course, you may say, just put another column that represent
>this(some reporting programs I have seen do it this way) and that is an
>option but not the only option.
>
Maybe you could keep the rearranged_keys vector in a per-user cookie, if it's a 
web app
and amounts to a user personalization?

( posting delayed >12 hrs due to news server prob ;-/ )

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


Re: Command line

2005-11-21 Thread Bengt Richter
On 20 Nov 2005 12:00:02 -0800, "amfr" <[EMAIL PROTECTED]> wrote:

>Hoe would I call something on the command line from python, e.g. "ls
>-la"?
>
Depends on how much control you want over where the output goes.
If you want the result as a multi-line string formatted the way
the system utility (ls here) formats it, and that you can process
further (or print etc.) in your python script or interactive session,
you may want

 >>> import os
 >>> result = os.popen('ls -la').read()
 >>> print result
 Usage: LS [/FrqRdlt1sSvu] [files]

Oops, the ls I have on NT doesn't support "a" ;-)
But you get the idea.

You might have found this via the second link in Fredrik's post
( http://docs.python.org/lib/os-newstreams.html#os-newstreams )
but I thought you might miss it ;-)

If you don't want the original system utility formatting, the
python functions Fredrik showed make more sense, and are easier
to use.

( posting delayed >12 hrs due to news server prob ;-/ )

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


Re: Hot to split string literals that will across two or more lines ?

2005-11-21 Thread Paul McGuire
"Ben Finney" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Xiao Jianfeng <[EMAIL PROTECTED]> wrote:
> > I need to print a long sting, which is two long so it must expand
> > two lines.
>
> How is this string being constructed in the source? If it exists as a
> single long string, why must it be so long?
>
> Some techniques you may not be aware of:
>
> >>> chunks = ["abc", "def", "ghi"]
> >>> s = ''.join(chunks)
> >>> print s
> abcdefghi
>
> >>> s = "#" * 10
> >>> print s
> ##
>
> You can, of course, modify the above so that they join or multiply to
> create much longer strings.
>
> -- 
>  \  "Everything is futile."  -- Marvin of Borg |
>   `\   |
> _o__)  |
> Ben Finney

Or for a large literal string:

"""
lots of text hundreds of characters long
more text on another line but we really don't want any line breaks
in our final string
so we replace newlines in this multiline string
with an empty string thus
""".replace('\n','')

-- Paul


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


Re: need help about time.sleep, timer

2005-11-21 Thread Bengt Richter
On Mon, 21 Nov 2005 10:35:20 +0200, Sinan Nalkaya <[EMAIL PROTECTED]> wrote:

>Dennis Lee Bieber wrote:
>
>>On Fri, 18 Nov 2005 22:45:37 -0500, Peter Hansen <[EMAIL PROTECTED]>
>>declaimed the following in comp.lang.python:
>>
>>  
>>
>>>It's quite unclear whether the last part, above, is one of your 
>>>*requirements*, or a description of a problem you are having with your 
>>>current approach.  Do you *want* it to wait forever if you don't enter 
>>>anthing?
>>>
>>>
>>>
>>  As I understand it, he (?) wants to accumulate characters to be
>>passed to a certain function -- but the function is not to be invoked
>>until after a time period has expired; the time period resetting on each
>>character entered.
>>
>>  Something I'd do with threads, queues, and sleep...
>>
>>PSEUDOCODE
>>
>>thread1:
>>  while not Shutdown:
>>  ch = getChar()
>>  q.put(ch)
>>
>>
>>thread2: #or main
>>  while not Shutdown:
>>  chars = []
>>  while True:
>>  sleep(max_interval)
>>  if q.empty(): break #no input since start of sleep
>>  while not q.empty():#collect all input from sleep
>>  chars.append(q.get())
>>  inp = "".join(chars)
>>  function(inp)
>>
>>
>>
>>  
>>
>i appreciate your comments and ideas. Dennis told exactly what i tried 
>to say :), code seems to be fine but during sleep action i think the 
>above code does not execute
>
>if q.empty(): break #no input since start of sleep
>   while not q.empty():
>   chars.append(q.get())
>
>i need something, while sleeping, executes the function that waits for 
>input from keyboard.
>i imagined something like that, i have a queu, it both stores the keys 
>that pressed and pressing times of these keys, then i`ll proccess these 
>times. here is scenario
>input : 5
>after 10 seconds later input 5 is being proccessed
>return back to main function
>input : 1
>after 5 seconds , other input 5
>after 5 more seconds , 15 is being proccessed
>Thanks.

If I understand, you really don't want to sleep, you want to wait a max time of 
5 seconds
for a character. You can get that from a queue.get(True,5) hence, you could try 
the
following as a start (untested, and I don't have much experience with python 
threading,
so will wait for bug reports ;-)

Note that it uses getch for input, which doesn't echo. (Change to getche if you 
want echo)
You can run this from the command line with one arg: the number of seconds you 
want to
have the test continue. At the end of that time it will set the Shutdown event, 
and
thread2 should empty the queue and wait 5 seconds and then do its last function 
call and
see the shutdown event.

< tqinp.py 
>---
# tqinp.py -- test queued input of unechoed character input until a 5-second 
delay
import threading
import Queue
import msvcrt
queue = Queue.Queue(10) # 2 is prob enough for this thing
Shutdown = threading.Event()

def getChar(): return msvcrt.getch() # blocks
def function(s): print 'function(%r)'%s

def thread1(q):
while not Shutdown.isSet():
ch = getChar()
q.put(ch)

def thread2(q): #or main
while not Shutdown.isSet():
chars = ''
try:
while True: chars += q.get(True, 5)
except Queue.Empty, e:
print 'No input for 5 seconds. Using %r'%chars
function(chars)

import time
def test(trial_time):
thr1 = threading.Thread(target=thread1, args=(queue,))
thr1.start()
thr2 = threading.Thread(target=thread2, args=(queue,))
thr2.start()
t0 = time.clock()
time.sleep(trial_time)
print 'Ending trial after %s seconds' % (time.clock()-t0)
Shutdown.set()

if __name__ == '__main__':
import sys
if not sys.argv[1:]: raise SystemExit,'Usage: python tqinp.py'
test(float(sys.argv[1]))
---

Ok, in the following I'll type 123  abc 

[ 5:40] C:\pywk\clp\threadstuff>py24 tqinp.py 15
No input for 5 seconds. Using '123'
function('123')
No input for 5 seconds. Using 'abc'
function('abc')
Ending trial after 14.9948775627 seconds
No input for 5 seconds. Using ''
function('')

[ 5:41] C:\pywk\clp\threadstuff>

Except it didn't die until I hit another key to let thread1 loop and see its 
Shutdown test.
But this is alpha 0.01, so you can fix that various ways. Or maybe get the real 
requirements down ;-)
HTH
(once I get it posted -- news reads ok now but news server is not accepting 
posts.
I suspect they do system-hogging chores Sun night wee hours ;-/

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


Re: Any royal road to Bezier curves...?

2005-11-21 Thread Tom Anderson
On Mon, 21 Nov 2005, Tom Anderson wrote:

> On Sun, 20 Nov 2005, Warren Francis wrote:
>
>> Basically, I'd like to specify a curved path of an object through space. 3D 
>> space would be wonderful, but I could jimmy-rig something if I could just 
>> get 2D...  Are bezier curves really what I want after all?
>
> No. You want a natural cubic spline:

In a fit of code fury (a short fit - this is python, so it didn't take 
long), i ported my old java code to python, and tidied it up a bit in the 
process:

http://urchin.earth.li/~twic/splines.py

That gives you a natural cubic spline, plus my blended quadratic spline, 
and a framework for implementing other kinds of splines.

tom

-- 
Gin makes a man mean; let's booze up and riot!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Command line

2005-11-21 Thread amfr
What I am trying to do is call perl on the command line.  Also, do any
of these functions return the data recievved from the command?

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


Python install minimum requirements

2005-11-21 Thread Philippe C. Martin
Hi,

I am attemtping to package Python in a "U3" install program for Windows.

I got Python to compile/link and prior to adding the necessary code for the
U3 SDK registration, I would like to know where I can find the actual list
of files needed for a minimum installation (are DLLs and libs enough ?)

Regards,

Philippe

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


Re: Web-based client code execution

2005-11-21 Thread Kent Johnson
Paul Watson wrote:
> My desire to have the code distributed through a web page is just to 
> ensure that the user is running the correct version and has not hacked 
> it in any way.  I suppose I can checksum the local client application 
> and compare it with what is on the server.  Then, make a way to 
> update... ARGH!

I have used Java Web Start to distribute Jython applications from a web page. 
There are a few glitches getting it set up but then it works well. Solves 
'ensure that the user is running the correct version' nicely. Not sure if it 
protects against hacking.

My Jython and Web Start recipe is here:
http://personalpages.tds.net/~kent37/Python/JythonWebStart.html

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


Re: Aproximative string matching

2005-11-21 Thread Irmen de Jong
javuchi wrote:
> I'm searching for a library which makes aproximative string matching,
> for example, searching in a dictionary the word "motorcycle", but
> returns similar strings like "motorcicle".
> 
> Is there such a library?
> 

Perhaps the get_close_matches function that is presentt in the standard 
library (in the difflib module) could be useful ?"

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


Re: compiling Python under Windows

2005-11-21 Thread Philippe C. Martin
Thanks,

Regards,

Philippe


"Martin v. Löwis" wrote:

> Philippe C. Martin wrote:
>>>My mistake: The makefile (as written in the readme!) looks for bzip 1.0.2
>>>
>> 
>> PS: since bzip.org does not have 1.0.2 source anymore, can I just rename
>> 1.0.3 ?
> 
> That should work; alternatively, you can change the project file.
> 
> Regards,
> Martin

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


Help with modal in Gtk::FileChooserDialog

2005-11-21 Thread Thierry Lam
Does anyone know how to set modal to True for Gtk::FileChooserDialog?

Thanks
Thierry

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


Re: Aproximative string matching

2005-11-21 Thread Steven D'Aprano
On Mon, 21 Nov 2005 19:47:45 +0100, Diez B. Roggisch wrote:

> The idea is that otherwise e.g. "cat" and "hippopothamus" have a 
> l-distance of only 3, which one would consider good at the first look.

???

I make it that the L-distance between cat and hippopothamus is twelve, not
three. With len(cat)=3 and len(hippopothamus) = 13, you need ten
insertions just to get the lengths equal, so the L-distance must be at
least ten.


-- 
Steven.

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


Piecewise-cubic lookup table generator

2005-11-21 Thread Will Ware
I needed to generate some C code for a fast lookup table using
piecewise-cubic interpolation. If anybody else needs this, the Python
code for it is at http://tinyurl.com/92zcs (alt.source, Google Groups).

Will Ware

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


bsddb185 question

2005-11-21 Thread thakadu
I have an application that needs to create and delete
records in a Berkeley DB version 1.85 database.
If I use the bsdddb185 module I dont see any
of the record manipulation methods in there that
are available in the newer bsddb module.
(put(), get(), pop() etc)

I know the docs say that one should always use
the newer bsddb module however it appears that the bsddb module
is unable to open version 1.85 databases.

So it seems I am forced to use the bsddb185 module
which does not have convenient record level methods.
Am I missing something here or have others eperienced
tha same?

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


Re: Why are there no ordered dictionaries?

2005-11-21 Thread Christoph Zwerschke
Fredrik Lundh wrote:
> I'll repeat this one last time: for the use cases presented by Zwerschke
> and "bonono", using a list as the master data structure, and creating the
> dictionary on demand, is a lot faster than using a ready-made ordered
> dict implementation.  if you will access things via the dictionary a lot,
> you can cache the dictionary somewhere.  if not, you can recreate it
> several times and still get a net win.

You're right in pointing out that the advantage of ordered dictionaries 
(unless you use an omptimized C implementation) is not a performance gain.

But please see my other reply: If the dictionary has more than 3 items 
(say 10 or 20), and an effective ordered dict is used, it's not really 
"a lot" slower. At least if we are talking about a situation were "on 
demand" is "always". So, on the other side there isn't such a big 
performance loss when using ordered dictionaries as well.

The advantage of using an ordered dictionary is that you can set up your 
ordered dictionary (say, describing your database columns) once, and 
then can access it in any way you like in the following: Iterate over it 
in a guaranteed order or access item, always refering to the same 
object, without needing to care about building and caching auxiliary 
objects with different names depending on what you are doing.

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


Re: running functions

2005-11-21 Thread [EMAIL PROTECTED]
Tom Anderson wrote:
> > If you program threads with shared nothing and communication over Queues
> > you are, in effect, using processes.  If all you share is read-only
> > memory, similarly, you are doing "easy" stuff and can get away with it.
> > In all other cases you need to know things like "which operations are
> > indivisible" and "what happens if I read part of this from before an
> > update and the other after the update completes, .
>
> Right, but you have exactly the same problem with separate processes -
> except that with processes, having that richness of interaction is so
> hard, that you'll probably never do it in the first place!

It's not all that hard, but you do have to think about it and really
engineer your communications (and SHM segments) ahead of time.  Which
is a good thing, IMO.

Really the only difference between threads and processes is that
threads share all your memory.  When you consider that OS designers
spent a lot of time and effort to implement protected memory, maybe
that's not often the right thing.  Certainly threads have their place,
but I avoid them whenever there's an equally easy multiprocess solution
(which is the overwhelming majority of the time, but certainly not
always).

To diverge from the Python world for a moment, imagine a network server
that services each connection with a thread (possibly from a thread
pool rather than creating a new one for each connection).  And imagine
another that uses multiple process.  Now suppose there's a bug in some
extension that segfaults (for instance, when serving large media
files).  It's very easy for such a bug to bring down the whole server
in the multithreaded server; in the multiprocess server it naturally
brings down only the one connection, so the rest of the site continues
to run happily.  Many other stability and security holes are easy to
introduce when you eliminate memory protection.

I don't really understand the "process are really hard" thing, either.
It's a 5 line wrapper or so to make it look just like the threads
interface if you really want to, and you only have to do that once.
You do need to worry about IPC, but that is generally simpler than just
mucking about in process-wide memory, especially when it comes to
maintenance.  But...

> I've done a fair amount of threads programming, although in java rather
> than python (and i doubt very much that it's less friendly in python than
> java!), and i found it really fairly straightforward.

Java certainly doesn't have any real support for multiprocess
programming.  I view the lack of good multiprocess solutions in Java to
be one of the few major design flaws therein.  Indeed, I view the poor
performance of processes on Windows (and the accompanying need to use
threads for reasons other than memory sharing) to be the biggest single
problem with Windows.

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


Re: ignore specific data

2005-11-21 Thread pkilambi
I tried the solutions you provided..these are not as robust as i
thought would be...
may be i should put the problem more clearly...

here it goes

I have a bunch of documents and each document has a header which is
common to all files. I read each file process it and compute the
frequency of words in each file. now I want to ignore the header in
each file. It is easy if the header is always at the top. but
apparently its not. it could be at the bottom as well. So I want a
function which goes through the file content and ignores the common
header and return the remaining text to compute the frequencies..Also
the header is not just one line..it includes licences and all other
stuff and may be 50 to 60 lines as well..This "remove_header" has to be
much more efficient as the files may be huge. As this is a very small
part of the whole problem i dont want this to slow down my entire
code...

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


Re: How to install python2.4.2 on IRIX6.5 ?

2005-11-21 Thread Martin v. Löwis
Xiao Jianfeng wrote:
> self.assertEquals(result, expected)
> AssertionError: '-0' != '0'
> 
> Can somebody tell me what's the problem ?

It looks like there is some minor bug in the floating
point libraries of your operating system: Python expects
that the strings for both numbers are the same in the test,
but actually, one number is formatted as -0, and the other
as 0.

It's not clear what the test_locale failure is; when
you run it again, it says that test_frozen has been run
instead. Are you sure the commands worked precisely as
entered? In any case, test_locale failures are typically
also of minor importance only, as well.

This is a minor issue only, and shouldn't affect Python's
functionality for most cases. Given that the rest of
the test suite passed, just go ahead and make install.

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


Re: compiling Python under Windows

2005-11-21 Thread Martin v. Löwis
Philippe C. Martin wrote:
>>My mistake: The makefile (as written in the readme!) looks for bzip 1.0.2
>>
> 
> PS: since bzip.org does not have 1.0.2 source anymore, can I just rename
> 1.0.3 ?

That should work; alternatively, you can change the project file.

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


Re: ownership problem?

2005-11-21 Thread Jeffrey Schwab
Donn Cave wrote:
> In article <[EMAIL PROTECTED]>,
>  Jeffrey Schwab <[EMAIL PROTECTED]> wrote:
> 
> 
>>Yes it is.  Memory is only one type of resource.  There are still files 
>>and sockets to close, pipes to flush, log messages to be printed, GDI 
>>contexts to free, locks to release, etc.  In C++, these things are 
>>generally done by destructors, which are called automatically and 
>>deterministically.  I am not a Python Guru, but in Perl, Java, and other 
>>languages that have built-in garbage collectors, these tasks have to be 
>>done explicitly.  I find that this forces a procedural approach, even in 
>>an otherwise object-oriented program.
>>
>>If you want something like automatic garbage collection in C++, I 
>>recommend the use of Factories with destructors that release the 
>>Factories' products.  The zeitgeist in c.l.c++.moderated seems to prefer 
>>the use of smart (reference-counted) pointers, which also rely on 
>>destructors to release resources automatically.  Plentry of free, 
>>open-source implementations are available.
> 
> 
> You may be gratified to learn that Python's main storage model
> is reference counted objects, and when an object falls out of
> all referenced scopes its finalizers run immediately.

Thanks, that's good to know!  For some reason I had it in my head that 
Python always used mark & sweep.  I'm used to ref-counted collection in 
Perl, but I never relied on it because of a nagging (probably 
ill-founded) worry about cyclic references.  Does Python have any way 
around this?  Is there a Python equivalent to C++ destructors?

> This is however true only of the C implementation.  The Java
> implementation naturally has Java's limitations in this matter,
> so documentation generally avoids the issue.  The C implementation
> has been around for over a decade, wonder if it had any influence
> on your C++ zeitgeist?

Possibly.  Python has really caught on with the C++ crowd in a way that 
other languages never did.  I'm not sure why; not that I don't love 
Python, but there are other good, dynamic languages that haven't made 
the same in-roads.

I think Java has had a big influence, too.  People just don't seem to 
want to be bothered with thinking about object life cycles at all.  This 
seems unfortunate to me, because cleanup still has to be done, so it 
just ends up getting moved outside the objects where it belongs.  I 
think this hurts abstraction.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading a subprocesses stdout on Windows

2005-11-21 Thread Do Re Mi chel La Si Do
Hi!

Let down subprocess, and remember  popen4.

Here, an example (with  CMD, under w-XP) :

import os

def lcmd(lst=None):
a = os.popen4(lst[0])
for i in lst[1:]:
if i!='':
a[0].write(i+'\r\n')
a[0].flush()
return a[1].readlines()

l=[
'CMD /K',
'DIR *.c /B',
'DATE /T',
'TIME /T',
'EXIT'
]
lret = lcmd(l)
for n in lret:
print n[:-1]



Attention : don't read data inside the loop (for)...



@-salutations

Michel Claveau



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


Re: ownership problem?

2005-11-21 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 Jeffrey Schwab <[EMAIL PROTECTED]> wrote:
...
> Yes it is.  Memory is only one type of resource.  There are still files 
> and sockets to close, pipes to flush, log messages to be printed, GDI 
> contexts to free, locks to release, etc.  In C++, these things are 
> generally done by destructors, which are called automatically and 
> deterministically.  I am not a Python Guru, but in Perl, Java, and other 
> languages that have built-in garbage collectors, these tasks have to be 
> done explicitly.  I find that this forces a procedural approach, even in 
> an otherwise object-oriented program.
>
> If you want something like automatic garbage collection in C++, I 
> recommend the use of Factories with destructors that release the 
> Factories' products.  The zeitgeist in c.l.c++.moderated seems to prefer 
> the use of smart (reference-counted) pointers, which also rely on 
> destructors to release resources automatically.  Plentry of free, 
> open-source implementations are available.

You may be gratified to learn that Python's main storage model
is reference counted objects, and when an object falls out of
all referenced scopes its finalizers run immediately.

This is however true only of the C implementation.  The Java
implementation naturally has Java's limitations in this matter,
so documentation generally avoids the issue.  The C implementation
has been around for over a decade, wonder if it had any influence
on your C++ zeitgeist?

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric array in unittest problem

2005-11-21 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
> Sorry Peter,
> Try this
> 
> import unittest
> import Numeric
> 
> class myTest(unittest.TestCase):
> def runTest(self):
> var1 = Numeric.array([1,22])
> var2 = Numeric.array([1,33])
> self.assertEqual(var1,var2)
> 
> if __name__ == '__main__':
> unittest.main()

My apologies, as I thought I was pointing out an obvious error, but it 
turns out I was totally wrong about it.

My own use of module unittest has always involved defining methods whose 
names start with "test", as in "def test01(self):" and "def 
test_this(self):" and so forth.

I had no idea that there was a method runTest() that you could override, 
so I was trying to point out that the test case wasn't even executing -- 
though clearly it was!

(Try defining even a single method starting with "test" in addition to 
the runTest() method you have above, and you'll see that runTest() stops 
executing... but obviously this isn't your problem.)

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


Re: ignore specific data

2005-11-21 Thread Mike Meyer
[EMAIL PROTECTED] writes:

> thanks for that. But this will check for the exact content of the
> "start of block.." or "end of block". How about if the content is
> anywhere in the line?

Then the test is '"start of block." in line'. You could also use
the line.find or line.index methods, but those don't return booleans,
and so require some extra work to get what you want.

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


Re: Reading a subprocesses stdout on Windows

2005-11-21 Thread brolewis
commands is Unix only. This is Windows specific

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


Re: Advice on distutils and distribution policies

2005-11-21 Thread Magnus Lycka
Mardy wrote:
> Hi,
>   I've built a small project (http://eligante.sf.net) which I'm actually
> trying to package using distutils.
...
> However, I don't know if this directory layout is suitable for
> site-packages, since at a first glance it looks to me that datafiles might
> not be welcome under it. Is it so?

In general, it's a good idea to keep code and data separated:

  - Different people might need to access code and data. People who
add content to a web site shouldn't be able to make a mess of the
software that controls that web site (or vice versa).
  - Lifecycles are different, so different backup strategies might apply.
  - Directory structures such as /usr under unix are typically fairly
static on production systems, and there might be assumptions that
required space doesn't grow over time, whereas data, kept under
/var is expected to change more over time. Also, if e.g. web content
is kept in a separate disk partition, filling that partition won't
mess up other parts of the computer system.
  - It should be easy to upgrade the software without messing up data.
It's practical if it's safe to e.g. do
"rm -rf /usr/lib/python2.3/site-packages/eligante" followed by
a new "python setup.py install" in case a sys admin thinks that
his old install was broken.

For a CGI-based app on e.g. a linux box with Apache, I think it would
be typical to partition things like this:

In an apache cgi-bin directory: The main Python CGI script(s) that
are called by the web server. These might be scripts that are modified
as a part of the installation process to e.g. point out data files.
These should be short files. Import a module, set up configuration
and run something in the imported module.

Under /usr/lib/python2.x/site-packages/ you keep the bulk of your
software (as described above).

HTML and CSS files that are to be handled directly by the web browser
is placed under Apache's DOCUMENT_ROOT etc. E.g.
$DOCUMENT_ROOT/eligante.

Data files that are read and processed by you own programs (i.e. not
directly by the web server) van be anywhere under /var, e.g.
/var/eligante.


> In that case, where should I move the .html files, and how should I access
> them from inside python?

Asolute path defined by an environment variable?

I think Apache defines a DOCUMENT_ROOT variable. You
could decide that your HTML files etc should reside in
some particular place relative to DOCUMENT_ROOT, and
use something like...

import os
SUB_FOLDER = 'my_folder'
dir = os.path.join(os.environ['DOCUMENT_ROOT'],SUB_FOLDER)

...to locate your files.

As I wrote above, hardcoding in a main CGI-script is also
common practice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading a subprocesses stdout on Windows

2005-11-21 Thread Klaus Alexander Seistrup
BroLewis wrote:

> I have been trying for several weeks now to write a program that 
> allows me to read the stdout of a process that I spawn and once 
> I receive feedback, act appropriately.

Have you looked into the 'commands' module?

Cheers,

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


Reading a subprocesses stdout on Windows

2005-11-21 Thread brolewis
I have been trying for several weeks now to write a program that allows
me to read the stdout of a process that I spawn and once I receive
feedback, act appropriately.

More specifically, I need to create an SSH tunnel using plink on
Windows XP. Once the tunnel is successfully created, then I need to run
my program over that tunnel. If there is an error in the creation of
the tunnel, then I need to abort and warn the users.

My needs are 'small' but I just lack the know-how to get it done. I
need to be able to spawn off plink so that it can continue to run in
the background without interferring with the flow of my program.
However, I would like to get the feedback to know if/when a successful
connection has been made so that I know the appropriate actions to
take.

In the past, I spawned off a process using os.spawnl set into a thread
and would pause for 10 seconds to give plink time to connect. However,
it probably goes without saying this is not the best solution by any
stretch of the imagination.

My old command was (with obviously fake data):
os.spawnl(os.P_NOWAIT, 'plink', 'plink', '[EMAIL PROTECTED]', '-N',
'-L 111:200.200.200.200:7000')
Then I would poll Windows to see if plink had started. If it hadn't
started, I would raise an exception. However, there are plenty of times
where plink starts but no connection is made.

As with most questions like this one, any and all help would be greatly
appreciated.

Lewis

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


Re: ignore specific data

2005-11-21 Thread pkilambi
thanks for that. But this will check for the exact content of the
"start of block.." or "end of block". How about if the content is
anywhere in the line?

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


Help in File selector window in pygtk

2005-11-21 Thread Thierry Lam
Let's say I have a main window which has a File menu. When I click on
the File menu and the open button, I have a File selector window which
comes in front of my main window.  How do I make the main window
unselectable?

Thanks
Thierry

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


Re: Why are there no ordered dictionaries?

2005-11-21 Thread Kay Schluehr
Fredrik Lundh wrote:

> huh?  if you want a list, use a list.
>
> d = [('a', {...}), ('b', {})]

If one wants uniform access to a nested data structure like this one
usually starts writing a wrapper class. I do not think the requirement
is anyhow deeper than a standard wrapper around such a list ( as a
model ) but the implementation may be different with respect to optimal
time complexitiy of element access. But the interface of the wrapper
class of d might resemble that of a dict. While the interface is that
of a dict the implementation is closer to a nested list. An "ordered
dict" would lower the impedance between a dict and a list. 

Kay

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


Re: best cumulative sum

2005-11-21 Thread David Isaac

> Alan Isaac wrote:
>> Like SciPy's cumsum.


"Colin J. Williams" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Doesn't numarray handle this?

Sure.
One might say that numarray is in the process of becoming scipy.
But I was looking for a solution when these are available.
Something like:
def cumreduce(func, seq, init = None):
"""Return list of cumulative reductions.

Example use:
>>> cumreduce(operator.mul, range(1,5),init=1)
[1, 2, 6, 24]
>>>

:author: Alan Isaac
:license: public domain
"""
if not seq:
cr = [init]*bool(init)
else:
cr = [seq[0]] * len(seq)
if init:
cr[0] = func(cr[0],init)
for idx in range(1,len(seq)):
cr[idx] = func(cr[idx-1],seq[idx])
return cr


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


Re: ignore specific data

2005-11-21 Thread Mike Meyer
[EMAIL PROTECTED] writes:
> Hi I need help. What I want to do is If I read a file with some text
> content...
> I would like to ignore a block of lines and consider the rest..
> so if the block starts with
>
> "start of block."
> fjesdgsdhfgdlgjklfjdgkd
> jhcsdfskdlgjkljgkfdjkgj
> "end of block"
>
> I want to ignore this while processing the file .This block could
> appear anywhere in the file.It could at the start or end or even middle
> of file content.

The best way depends on how you're going to use the data. For
instance, if you're going to be processing line at a time, you might
consider writing an interator:

# Untested code:

def filter(rawfile):
for line in rawfile:
if line == "start of block..":
   break
yield line
for line in rawfile:
if line == "end of block":
   break
for line in rawfile:
yield line

Then you use it like:

myfile = open(...)
for line in filter(myfile):
process(line)

This is a straightforward translation of your description, and avoids
loading the entire file into memory at once. You might be able to cons
up something more efficient from itertools.

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


Re: compiling Python under Windows

2005-11-21 Thread Philippe C. Martin
Philippe C. Martin wrote:

> My mistake: The makefile (as written in the readme!) looks for bzip 1.0.2
> 
PS: since bzip.org does not have 1.0.2 source anymore, can I just rename
1.0.3 ?

Regards,

Philippe


> Sorry,
> 
> Philippe
> 
> 
> 
> Philippe C. Martin wrote:
> 
>> Hi,
>> 
>> I'm currently blocking on bzip2:
>> 
>> python is in c:\python.2.4.2
>> and bz2 is in c:\bzip2-1.0.3
>> 
>> Since the readme say subprojects should be two directories above PCbuild,
>> I assume I'm OK.
>> 
>> I added c:\bzip2-1.0.3 to the include and link path, but I get:
>> """
>> Performing Pre-Link Event ...
>> The system cannot find the path specified
>> NMAKE: fatal error U1052: file 'makefile.msc' not found
>> 
>> c:\bzip2-1.0.3 does hold a makefile.msc.
>> 
>> Any clue ?
>> 
>> Thanks,
>> 
>> Philippe

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


Re: Underscores in Python numbers

2005-11-21 Thread Eric Jacoboni
[EMAIL PROTECTED] (Bengt Richter) writes:

>>Eric Jacoboni, ne il y a 1435938104 secondes
> Um, about your sig ... ;-)

Well, i confess it's Ruby code... Maybe, one day, i will try to write
a Python Version (with DateTime, i guess?) but i'm afraid it doesn't
change the result.
-- 
Eric Jacoboni, ne il y a 1436041406 secondes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compiling Python under Windows

2005-11-21 Thread Philippe C. Martin
My mistake: The makefile (as written in the readme!) looks for bzip 1.0.2

Sorry,

Philippe



Philippe C. Martin wrote:

> Hi,
> 
> I'm currently blocking on bzip2:
> 
> python is in c:\python.2.4.2
> and bz2 is in c:\bzip2-1.0.3
> 
> Since the readme say subprojects should be two directories above PCbuild,
> I assume I'm OK.
> 
> I added c:\bzip2-1.0.3 to the include and link path, but I get:
> """
> Performing Pre-Link Event ...
> The system cannot find the path specified
> NMAKE: fatal error U1052: file 'makefile.msc' not found
> 
> c:\bzip2-1.0.3 does hold a makefile.msc.
> 
> Any clue ?
> 
> Thanks,
> 
> Philippe

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


compiling Python under Windows

2005-11-21 Thread Philippe C. Martin
Hi,

I'm currently blocking on bzip2:

python is in c:\python.2.4.2
and bz2 is in c:\bzip2-1.0.3

Since the readme say subprojects should be two directories above PCbuild, I
assume I'm OK.

I added c:\bzip2-1.0.3 to the include and link path, but I get:
"""
Performing Pre-Link Event ...
The system cannot find the path specified
NMAKE: fatal error U1052: file 'makefile.msc' not found

c:\bzip2-1.0.3 does hold a makefile.msc.

Any clue ?

Thanks,

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


Re: Why are there no ordered dictionaries?

2005-11-21 Thread Tom Anderson
On Sun, 20 Nov 2005, Alex Martelli wrote:

> Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
>
>> The 'sorted' function does not help in the case I have indicated, where 
>> "I do not want the keys to be sorted alphabetically, but according to 
>> some criteria which cannot be derived from the keys themselves."
>
> Ah, but WHAT 'some criteria'?  There's the rub!  First insertion, last 
> insertion, last insertion that wasn't subsequently deleted, last 
> insertion that didn't change the corresponding value, or...???

All the requests for an ordered dictionary that i've seen on this group, 
and all the cases where i've needed on myself, want one which behaves like 
a list - order of first insertion, with no memory after deletion. Like the 
Larosa-Foord ordered dict.

Incidentally, can we call that the "Larosa-Foord ordered mapping"? Then it 
sounds like some kind of rocket science discrete mathematics stuff, which 
(a) is cool and (b) will make Perl programmers feel even more inadequate 
when faced with the towering intellectual might of Python. Them and their 
Scwartzian transform. Bah!

tom

-- 
Baby got a masterplan. A foolproof masterplan.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any royal road to Bezier curves...?

2005-11-21 Thread Tom Anderson
On Sun, 20 Nov 2005, Warren Francis wrote:

> Basically, I'd like to specify a curved path of an object through space. 
> 3D space would be wonderful, but I could jimmy-rig something if I could 
> just get 2D...  Are bezier curves really what I want after all?

No. You want a natural cubic spline:

http://mathworld.wolfram.com/CubicSpline.html

This is a fairly simple curve, which can be fitted through a series of 
points (called knots) in space of any dimensionality, without the need to 
specify extra control points (unlike a Bezier curve), and which has the 
nice property of minimising the curvature of the curve - it's the shape 
you'd get if you ran a springy wire through your knots. It usually looks 
pretty good too.

Google will help you find python implementations.

There are other kinds of splines - Catmull-Rom, B-spline (a generalisation 
of a Bezier curve), Hermite - but they mostly don't guarantee to pass 
through the knots, which might make them less useful to you.

In the opposite direction on the mathematical rigour scale, there's what i 
call the blended quadratic spline, which i invented as a simpler and more 
malleable alternative to the cubic spline. It's a piecewise parametric 
spline, like the cubic, but rather than calculating a series of pieces 
which blend together naturally, using cubics and linear algebra, it uses 
simple quadratic curves fitted to overlapping triples of adjacent knots, 
then interpolates ('blends') between them to draw the curve. It looks very 
like a cubic spline, but the code is simpler, and the pieces are local - 
each piece depends only on nearby knots, rather than on all the knots, as 
in a cubic spline - which is a useful property for some jobs. Also, it's 
straightforward to add the ability to constrain the angle at which the 
curve passes through a subset of the knots (you can do it for some knots, 
while leaving others 'natural') by promoting the pieces to cubics at the 
constrained knots and constraining the appropriate derivatives. Let me 
know if you want more details on this. To be honest, i'd suggest using a 
proper cubic spline, unless you have specific problems with it.

tom

-- 
... a tale for which the world is not yet prepared
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Aproximative string matching

2005-11-21 Thread Diez B. Roggisch
Steven D'Aprano wrote:
> [EMAIL PROTECTED] wrote:
> 
>> This algorithm is called soundex. Here is one implementation example.
>>
>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52213
>>
>> here is another:
>> http://effbot.org/librarybook/soundex.htm
> 
> 
> Soundex is *one* particular algorithm for approximate string matching. 
> It is optimised for matching Anglo-American names (like Smith/Smythe), 
> and is considered to be quite old and obsolete for all but the most 
> trivial applications -- or so I'm told.
> 
> Soundex will not match arbitrary changes -- it will match both cat and 
> cet, but it won't match cat and mat.
> 
> A more sophisticated approximate string matching algorithm will use the 
> Levenshtein distance. You can find a Useless implementation here:
> 
> http://www.uselesspython.com/download.php?script_id=108
> 
> 
> Given a function levenshtein(s1, s2) that returns the distance between 
> two strings, you could use it for approximate matching like this:
> 
> def approx_matching(strlist, target, dist=1):
> """Matches approximately strings in strlist to
> a target string.
> 
> Returns a list of strings, where each string
> matched is no further than an edit distance of
> dist from the target.
> """
> found = []
> for s in strlist:
> if levenshtein(s, target) <= dist:
> found.append(s)
> return s

I compute a relative metric based on th every same implementation like this:

def relative(a, b):
 """
 Computes a relative distance between two strings. Its in the range
 (0-1] where 1 means total equality.
 @type a: string
 @param a: arg one
 @type b: string
 @param b: arg two
 @rtype: float
 @return: the distance
 """
 d = levensthein(a,b)
 longer = float(max((len(a), len(b
 shorter = float(min((len(a), len(b
 r = ((longer - d) / longer) * (shorter / longer)
 return r


The idea is that otherwise e.g. "cat" and "hippopothamus" have a 
l-distance of only 3, which one would consider good at the first look.


Regards,

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


Re: ignore specific data

2005-11-21 Thread skip

pkilambi> I would like to ignore a block of lines and consider the
pkilambi> rest..  so if the block starts with

pkilambi> "start of block."
pkilambi> fjesdgsdhfgdlgjklfjdgkd
pkilambi> jhcsdfskdlgjkljgkfdjkgj
pkilambi> "end of block"

pkilambi> I want to ignore this while processing the file .This block
pkilambi> could appear anywhere in the file.It could at the start or end
pkilambi> or even middle of file content.

How about (untested):

class FilterBlock:
def __init__(self, f, start, end):
self.f = f
self.start = start
self.end = end

def __iter__(self):
return self

def next(self):
line = self.f.next()
if line == self.start:
line = self.f.next()
while line != self.end:
line = self.f.next()
return line

Then use it like

filterfile = FilterBlock(open("somefile", "r"),
 "start of block..",
 "end of block")

for line in filterfile:
process(line)

I'm not sure what you mean by all the dots in your start of block line.  If
"start of block" can be followed by other text, just use 

if line.startswith(self.start):

instead of an exact comparison.

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


the name of a module in which an instance is created?

2005-11-21 Thread Steven Bethard
The setup: I'm working within a framework (designed by someone else) 
that requires a number of module globals to be set.  In most cases, my 
modules look like:
(1) a class definition
(2) the creation of one instance of that class
(3) binding of the instance methods to the appropriate module globals

I'm trying to hide the complexity of step (3) by putting it in a common 
base class.  That way, when I'm writing a new module, I never have to 
see the step (3) code.  Right now, that code is in the __init__ method 
of the common base class and looks something like::

 setattr(mod, 'creole_%s' % name, self._call)
 setattr(mod, 'creole_%s_Initialize' % name, self._initialize)
 setattr(mod, 'creole_%s_Finish' % name, self._finish)

where 'mod' is the module and 'name' is the name of the module.

In the basic situation, where the instance is created in the same module 
as the class, I can figure out 'mod' and 'name' like::

 cls = type(self)
 name = cls.__module__
 mod = __import__(cls.__module__)

However, this fails whenever the instance is not created in the same 
module as the class was defined (e.g. when I've factored a common base 
class into another module, and only imported this class to do steps (2) 
and (3)).  How can I figure out 'name' if the class was created in a 
different module?

One option, of course, is to pass it explicitly, e.g.::

 import C
 instance = C(__name__, ...)

This isn't a horrible option, but it does mean that I'm not hiding all 
of the step (3) machinery anymore

Another option would be to declare a dummy class, e.g.::

 import C
 class Dummy(C):
 pass
 instance = Dummy(...)

Again, this isn't horrible, but it also fails to hide some of the step 
(3) machinery.

Any other possibilities?

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


Re: Numeric array in unittest problem

2005-11-21 Thread Roman Bertle
* Alex Martelli <[EMAIL PROTECTED]>:
>  [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> 
> > Sorry Peter,
> > 
> > Try this
> > 
> > import unittest
> > import Numeric
> > 
> > class myTest(unittest.TestCase):
> > def runTest(self):
> > var1 = Numeric.array([1,22])
> > var2 = Numeric.array([1,33])
> > self.assertEqual(var1,var2)
> > 
> > if __name__ == '__main__':
> > unittest.main()
> 
> 
>  i.e., thanks to element-by-element evaluation, == will generally return
>  a true value for ANY comparison of Numeric arrays, causing a very
>  frequent beginner's bug to be sure.  Try Numeric.alltrue(c), or
>  Numeric.allclose(a,b) ...

I extend unittest.TestCase as follows (uses numarray, not Numeric):


class NumTestCase(unittest.TestCase):

"""Extends TestCase with equality tests for numarrays.
"""

def numAssertEqual(self, a1, a2):
"""Test for equality of numarray fields a1 and a2.
"""
self.assertEqual(a1.shape, a2.shape)
self.assertEqual(a1.type(), a2.type())
self.assertTrue(N.alltrue(N.equal(a1.flat, a2.flat)))

def numAssertAlmostEqual(self, a1, a2):
"""Test for approximately equality of numarray fields a1 and a2.
"""
self.assertEqual(a1.shape, a2.shape)
self.assertEqual(a1.type(), a2.type())
if a1.type() == 'Float64' or a1.type() == 'Complex64':
prec = 15
else:
prec = 7
if isinstance(a1.type(), N.ComplexType):
af1, af2 = a1.flat.real, a2.flat.real
for ind in xrange(af1.nelements()):
self.assertAlmostEqual(af1[ind], af2[ind], prec)
af1, af2 = a1.flat.imag, a2.flat.imag
for ind in xrange(af1.nelements()):
self.assertAlmostEqual(af1[ind], af2[ind], prec)
else:
af1, af2 = a1.flat, a2.flat
for ind in xrange(af1.nelements()):
self.assertAlmostEqual(af1[ind], af2[ind], prec)

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


ignore specific data

2005-11-21 Thread pkilambi
Hi I need help. What I want to do is If I read a file with some text
content...
I would like to ignore a block of lines and consider the rest..
so if the block starts with

"start of block."
fjesdgsdhfgdlgjklfjdgkd
jhcsdfskdlgjkljgkfdjkgj
"end of block"

I want to ignore this while processing the file .This block could
appear anywhere in the file.It could at the start or end or even middle
of file content.

Hope I'm clear...

somethin like

f = open("file")
clean_data = ignore_block(f)

here ignore_data should filter the block

def ignore_data(f):
   .
   return data # may be an array of remaining lines...

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


Advice on distutils and distribution policies

2005-11-21 Thread Mardy
Hi,
  I've built a small project (http://eligante.sf.net) which I'm actually
trying to package using distutils.
The directory structure is going to be like this:

eligante/
eligante.py
sitobase.py
personas.py
[...other python files...]
modulos/
mbox.py
gaim.py
[...other python files...]
web/
indice.py
cerca.py
[...other python files...]
stylo.css
testata.html
[and maybe, in the future, other HTML files]

The python files in the eligante/web directory are intended to be called
by a webserver (now Apache, but soon I'll switch to the python
module CGIHTTPServer for simplicity) as CGIs. Currently, these CGIs read
the testata.html file and use it as the beginning of their output, while
the style.css is served by the HTTP server.

However, I don't know if this directory layout is suitable for
site-packages, since at a first glance it looks to me that datafiles might
not be welcome under it. Is it so?
In that case, where should I move the .html files, and how should I access
them from inside python?

If, on the other hand, this layout is OK for site-packages, how do I
instruct distutils to put the .html and .css files under the eligante/web
directory?

Sorry for the long post, and thanks in advance for any help or suggestion.


-- 
Saluti,
Mardy
http://interlingua.altervista.org

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


Re: Numeric array in unittest problem

2005-11-21 Thread Robert Kern
Alex Martelli wrote:

import Numeric
a=Numeric.array([1,22])
b=Numeric.array([1,33])
c = a==b
c
> 
> array([1, 0])
> 
assert(c)
> 
> i.e., thanks to element-by-element evaluation, == will generally return
> a true value for ANY comparison of Numeric arrays, causing a very
> frequent beginner's bug to be sure.

Indeed. This is why numarray and scipy_core have made arrays raise an
exception when someone tries to use them as truth values.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: Why are there no ordered dictionaries?

2005-11-21 Thread Aahz
In article <[EMAIL PROTECTED]>,
Alex Martelli <[EMAIL PROTECTED]> wrote:
>
>I think you're wrong here.  People in the past who have requested or
>implemented stuff they called 'ordered dicts' in the past had in mind
>drastically different things, based on some combination of insertion
>orders, keys, and _values_.  So, ambiguity is definitely present in the
>phrase 'ordered dictionary', because there are so many different
>criteria whereby the 'ordering' could take place.
>
>Note the plural in 'insertion orderS': some people care about the FIRST
>time a key was added to a dict, some about the LAST time it was added,
>some about the latest time it was 'first inserted' (added and wasn't
>already there) as long as it's never been deleted since that occasion --
>and these are just a few of the multifarious orders based on the time of
>insertions and deletions of keys.  

Ayup.  In our application, not only do we have ordered dicts, we also
have something called a "sectioned dict", which is a dict-like object
that also looks like a regular class instance with attribute access.  The
section part actually has multiple dicts (the sections) which are
layered, so that a dict key in the top layer overrides the value of the
key in lower layers.  We traditionally have used it such that the
sections are accessed in MRU orders; last week, we added a new feature
that allows setting section values without changing section order (to
allow setting a default, essentially).
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about sort and dictionary

2005-11-21 Thread George Sakkis
"Shi Mu" wrote:

> Got confused by the following code:
> >>> a
[6, 3, 1]
> >>> b
[4, 3, 1]
> >>> c

> {1: [[6, 3, 1], [4, 3, 1]], 2: [[6, 3, 1]]}
> >>> c[2].append(b.sort())
> >>> c

> {1: [[6, 3, 1], [1, 3, 4]], 2: [[6, 3, 1], None]}
> #why c can not append the sorted b??


In python 2.4, you can use the sorted() builtin instead:

c[2].append(sorted(b))

George

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


Re: about sort and dictionary

2005-11-21 Thread George Sakkis
"Shi Mu" wrote:

> Got confused by the following code:
> >>> a
[6, 3, 1]
> >>> b
[4, 3, 1]
> >>> c

> {1: [[6, 3, 1], [4, 3, 1]], 2: [[6, 3, 1]]}
> >>> c[2].append(b.sort())
> >>> c

> {1: [[6, 3, 1], [1, 3, 4]], 2: [[6, 3, 1], None]}
> #why c can not append the sorted b??


In python 2.4, you can use the sorted() builtin instead:

c[2].append(sorted(b))

George

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


Re: about sort and dictionary

2005-11-21 Thread Magnus Lycka
[EMAIL PROTECTED] wrote:
> most built-in function/method don't return the "object" but None. This
> I believe is the language creator's preference for everything being
> explicit. 

The list methods .sort() and .reverse() don't create copies,
but rather change the existing object. The reson for this is
to save RAM. If you have 512MB RAM and a 300 MB list, it's
nice that you can sort it without swapping virtual memory to
disk. That would slow down the sort operation a lot, and that
would be a shame, considering all the efforts that went into
Python's excellent sort implementation.

If you sort (or reverse) a list l, and don't need to keep the
unsorted list, you simply do l.sort() (or l.reverse()). If
you need to keep the original as well, you must make a copy
before the sort, like this: sorted_l = l[:]; sorted_l.sort().

If the sort operation had returned self, it would have been
easy to write:

sorted_l = l.sort()

and while sorted_l would contain what one might expect, it
would in fact just be another name referencing exactly the
same sorted list as l, and it would probably be surprising
that l was also sorted, and that subsequent changes would
show up in both sorted_l and l, and that sorted_l might not
be sorted and longer even though you only modified l. It's
this particular gotcha that the language creator wanted to
avoid.

With newer versions of Python, the builtin functions sorted()
and reversed() have been added, so those who think it's ugly
to call a list sorted before it actually *is* sorted, can
simply write:

sorted_l = sorted(l)

With older Python's you need to do the hard work to add this
to your program:

def sorted(l): s=l[:];s.sort();return s
def reversed(l): r=l[:];r.reverse();return r

Actually, I guess it's possible that sorted() is done so
that it works like below, but I don't think pre-sorted()
versions of Python support keyword arguments to list.sort()
anyway...

def sorted(l, *p, **kw): s=l[:];s.sort(*p, **kw);return s
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best cumulative sum

2005-11-21 Thread Colin J. Williams
David Isaac wrote:
> <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> 
>>He seems to want scanl
> 
> 
> Yes.  But it's not in Python, right?
> (I know about Keller's version.)
> 
> Robert Kern wrote:
> 
>>Define better. More accurate? Less code?
> 
> 
> Good point.
> As Bonono (?) suggested: I'd most like a solution that
> relies on a built-in to give me both of those.
> (Pretty is good too.)  Like SciPy's cumsum.
> 
> Thanks,
> Alan Isaac
> 
> 
Doesn't numarray handle this?

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


Re: Why are there no ordered dictionaries?

2005-11-21 Thread Christoph Zwerschke
Alex Martelli wrote:

> Note the plural in 'insertion orderS': some people care about the FIRST
> time a key was added to a dict, some about the LAST time it was added,
> some about the latest time it was 'first inserted' (added and wasn't
> already there) as long as it's never been deleted since that occasion --
> and these are just a few of the multifarious orders based on the time of
> insertions and deletions of keys.

Ok, I start to understand that ambiguity emerges when you delete and 
insert items. I didn't think much about this problem because  my use 
cases usually do not involve inserttion or deletion after the ordered 
dictionary has been created.

But I think the following rule is "natural" enough to consider it as THE 
standard behavior of ordered dictionaries:

"Insertion: If the key exists: Don't change the order. If it does not 
exist: Append it to the sequence of keys. Deletion: Remove from the 
sequence of keys."

I think this is also the behavior of associative arrays in PHP or Perl 
and could be considered as the "ONE unambiguous definition".

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


  1   2   >