Re: Little Q: how to print a variable's name, not its value?

2005-03-30 Thread Stewart Midwinter
thanks Aaron, I'll pick what's behind door no. 1 !
That is, I liked your first solution.  Having said that, I would only
have to place either solution once in my code, then I could call it
again and again.  So either one would be just as 'light' in actual
usage.

Taking this idea a little further, I'd like to build a 'variable
inspector' for my GUI app, so that I don't have to resort to debug
statements.  Instead, I could pop open a window that lists every
variable that has an expected None, string, int or float value, and
select any one in order to see its value at that time.  I believe your
method would be useful in that situation as well, no?

cheers,
-- 
Stewart Midwinter
[EMAIL PROTECTED]
[EMAIL PROTECTED]
Skype: midtoad
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter destroy()

2005-03-30 Thread [EMAIL PROTECTED]
Your app seems to give the right state values only if you select 'Freni
a posto'.   But I see you recognize that with your 'FIXME' note.

also the app seems to have too many variables and widgets defined as
self objects.  That isn't necessary unless they will be used outside
the method they were created in (which labels and buttons usually
aren't), so all you are doing is using up more memory than necessary.


Reading the code with Italian names adds a little difficulty in
understanding your code (non parlo italiano ma si parlo espagnol), but
I'm left feeling that your app is more complicated than it needs to be
- unless I'm missing something.  What you are doing is just showing how
you can capture the state of the checkbuttons for use elsewhere, right?
And also, that the state in the 2nd window should be live, so that it
updates with the change in value in the 1st window?   And just a matter
of personal taste, but splitting up widget configuration over many
lines for me impedes readiblity and makes the code look like java or
c++ : surely not what we want?

I also think you could get away with no frames in your initial window,
at least if you use grid() instead of pack().  Also your three state
variables could be members of a list, so you don't have to have
separate constructors for each of them.

Anyway here's a version of your app that makes use of a 'for' statement
to draw the labels and checkbuttons, so it's only half as long as your
original app.  It also does the right thing - the key pont you were
missing was to use a 'textvariable' argument in defining your label
widgets in the 2nd window.

cheers
Stewart in Calgary

---
#tested on Windows XP with Python 2.4

from Tkinter import *

class MiaApp:
def __init__(self, genitore):
self.debug = 1  #debug flag
self.fonte = ("Helvetica", 12)
self.fonteVar = ("Helvetica", 14)

msg = Label(genitore, font = self.fonte, wraplength = "10c",
justify = LEFT,
text = u"Sono qui sotto presentati tre pulsanti a
spunta. \
Premendo un pulsante, se ne varia lo stato di selezione e si \
imposta una variabile a un valore che indica lo stato del \
pulsante stesso. Premendo il pulsante \u00ABMostra \
Variabili\u00BB si possono vedere i valori correnti delle \
variabili.")
msg.grid(row=0, column=0, sticky='w')

testo = ["Tergicristalli a posto", "Freni a posto", "Autista
sobrio"]
self.testo = testo
variabili = []
pulsanti  = []
for i in range(0,3):
variabili.append(None)
variabili[i] = IntVar()
variabili[i].set(0)

pulsanti.append(None)
pulsanti[i] = Checkbutton(genitore, text = testo[i],
variable = variabili[i], relief = FLAT)
pulsanti[i].grid(row=i+1, column=0,pady = 2,sticky = 'w')

self.variabili = variabili

var1 = Button(genitore, text = "Mostra Variabili",
command = self.pulsanteMostraVariabiliPremuto)
var1.grid(row=4, column=0)

annulla = Button(genitore, text = "Annulla",
command = genitore.destroy)
annulla.grid(row=4, column=1)


def pulsanteMostraVariabiliPremuto(self):
argomenti = []
for i in range(0,len(self.variabili)):
argomenti.append(self.variabili[i].get())
if self.debug:
print "%s=%i" % (self.testo[i],
self.variabili[i].get())
self.mostraVariabili(argomenti)


def mostraVariabili(self, *argomenti):
dialogo = Toplevel()
dialogo.wm_title("Valori delle variabili")
self.dialogo = dialogo

titolo = Label(dialogo,
text = "Valori delle variabili:", width = 20,
font = self.fonteVar )
titolo.grid(row=0, column=0, sticky='w' )

massimo = len(max(self.testo)) + 2
valore   = []
pulsanti = []
for i in range(0,3):
pulsanti.append(None)

pulsanti[i] = Label(dialogo,
text = 'self.%s' % self.testo[i].split()[0],
width = massimo)
pulsanti[i].grid(row=1+i, column=0, pady = 2,sticky = 'w')
valore.append(None)
valore[i] = Label(dialogo, text = self.variabili[i].get(),
textvariable = self.variabili[i])
valore[i].grid(row=i+1, column=1, pady = 2, sticky = 'w')

vaBene = Button(dialogo, text = "Va Bene",
command = self.pulsanteVaBenePremuto)
vaBene.bind("", lambda e=1:
self.pulsanteVaBenePremuto() )
vaBene.focus_force()
#items can span more than one column if desired
vaBene.grid(row=4, column=0, pady = 2, sticky='e')

def pulsanteVaBenePremuto(self):
self.dialogo.destroy()


radice = Tk()
radice.wm_title("Dimostrazione Pulsanti a Spunta")
radice.wm_iconname("spunta")
miaApp = MiaApp(radice)
radice.mainloop()

-- 
http://mail.python.org/mailman/l

Re: PyParsing module or HTMLParser

2005-03-30 Thread Lad
Paul, thanks a lot.
It seems to work but I will have to study the sample hard to be able to
 do the exercise (the extraction of the
description ) successfully. Is it possible to email you if I need some
help with that exercise?
Thanks again for help
Lad.

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


Re: math - need divisors algorithm

2005-03-30 Thread Ed Suominen
Philp Smith wrote:

> Hi
> 
> Does anyone have suggested code for a compact, efficient, elegant, most of
> all pythonic routine to produce a list of all the proper divisors of an
> integer (given a list of prime factors/powers)

Is this compact enough? :-)

def properDivisors(N):
return [x for x in range(1,N-2) if not divmod(N,x)[1]]

---
Ed Suominen
Registered Patent Agent
Open-Source Software Author (yes, both...)
Web Site: http://www.eepatents.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: McMillan Installer vs. Python 2.4

2005-03-30 Thread Simon John
[EMAIL PROTECTED] wrote:

[snip]
> First, I got the latest Installer, 6a2, from the Vaults of Parnassus.
> This version is listed as the 'Windows' version.  This means two
> things:  The .py files are sprinkled with DOS-style line endings
> (CR/LF) and file endings (^Z), and the runtime support files for
Linux
> are not prebuilt.

I have a Linux version of 6a2 at
http://www.the-jedi.co.uk/downloads/installer/

Could you build that using 2.4 and see if it works (I'm in the middle
of moving house, so don't have my Linux box to hand)?

It should work out of the box I guess, as I assume the Linux version
already has the carriage returns fixed. I'm not sure what else is
different, but it seems to be about half the size of the Windows one
(also on my website).

[...]
> This takes care of the management roadblock of "Your script is only a
> couple K in length, but you turn in into an executable and it takes
HOW
> MANY meg?!!?  Well, Python is obviously too inefficient for our use."

That's unfortunate. Did they never see a C++ program statically linked
with a few libs that comes to something huge? How big are you typically
looking at?

Maybe you need to explain to them your binary (including interpreter)
is the equivalent of shipping the 20Mb JVM with a Java program, or the
200Mb CLR with a C# program!

> At least, on some platforms.  Sadly, no upx on our main delivery
> platform, which is AIX.  Does anyone know of a better
executable-packer
> for AIX than gzexe?

Don't forget the --strip option in Installer, and call it using 'python
-OO', that will take it down a few Kbytes

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


Re: Actor pattern in GUI

2005-03-30 Thread M Ali
Hmm... no takers? Too bad, the pattern and it's implementation in
python is pretty interesting...

[EMAIL PROTECTED] (M Ali) wrote in message news:<[EMAIL PROTECTED]>...
> Hi,
> 
> I am trying to grok using actor patterns in a gui as explained here by
> Andrew Eland:
> http://www.andreweland.org/code/gui-actor.html 
> 
> The short article explains it using java with which i am not used to
> at all. But he does provide a python example using pygtk:
> http://www.andreweland.org/code/gui-actor.py
> 
> Could anyone look into it and maybe explain it a bit as i don't really
> get at all what's happening?
> 
> In addition I am getting these error when I try to run it:
> 
> GLib-WARNING **: giowin32.c:1654: 3 is neither a file descriptor or a
> socket
> GLib-CRITICAL **: g_io_add_watch_full: assertion `channel != NULL'
> failed
> GLib-CRITICAL **: g_io_channel_unref: assertion `channel != NULL'
> failed
> 
> Any ideas?
> 
> Thanks...
-- 
http://mail.python.org/mailman/listinfo/python-list


Mac OS X Installer for Python 2.4.1 available

2005-03-30 Thread Anthony Baxter
Thanks to Bob Ippolito, there's now an installer for Python 2.4.1
available for Mac OS X 10.3 and later. 

Grab it from the Python 2.4.1 page - http://www.python.org/2.4.1/

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


Re: LD_LIBRARY_PATH - how to set?

2005-03-30 Thread Roman Yakovenko
Thanks for help. But it is not exactly solution I am looking for. I
would like to do it from python script. For example

update_env() #<- this function will change LD_LIBRARY_PATH
import extension_that_depends_on_shared_library

Roman

On Mar 31, 2005 9:35 AM, John Abel <[EMAIL PROTECTED]> wrote:
> With Solaris 8+ you would use the command crle, with Linux
> (RedHat/SuSE/Mandrake) you need to add the relevant directories
> /etc/ld.so.conf and run ldconfig.  I've not got a Debian box to hand, so
> I can't say if it matches, but that should give you a pointer.

I think I should have permissions to do it. (more over users of my
scripts should have permissions )

> HTH
> 
> J
> 
> Roman Yakovenko wrote:
> 
> >On Mar 31, 2005 9:20 AM, John Abel <[EMAIL PROTECTED]> wrote:
> >
> >
> >>What OS?  Linux?  Solaris?
> >>
> >>
> >
> >Does it matter? If so, please explain why ( lack of knowledge )
> >I am using Linux ( Debian Surge  )
> >
> >Thanks
> >
> >
> >
> >
> >>J
> >>
> >>Roman Yakovenko wrote:
> >>
> >>
> >>
> >>>Hi. I have small problem. I need to load extension module that depends
> >>>on shared library. Before actually importing module I tried to edit
> >>>os.environ or to call directly to os.putenv without any success -
> >>>shared library was not found. I tried to search the Internet for the
> >>>answer. The only approach I saw was to set LD_LIBRARY_PATH before
> >>>invoking python script. I don't like this solution.
> >>>
> >>>Roman
> >>>
> >>>
> >>>
> >>>
> >
> >
> >
> 
> --
> *John Abel
> Senior Unix Administrator*
> PA News Limited
> www.pa.press.net 
> E-Mail address: [EMAIL PROTECTED] 
> Telephone Number : 01430 43
> Fax Number : 0870 1240192
> Mobile Number : 07971 611356
> The Bishop's Manor, Market Place, Howden, DN14 7BL
> PA News Limited, 292 Vauxhall Bridge Road, London SW1V 1AE. Registered
> in England No. 3891053.
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Pari Python

2005-03-30 Thread Philp Smith
Hi

I'm interested to try Pari Python but haven't had much success in the past 
compiling such packages for Windows.

Has anyone any advice or is there somewhere out there a precompiled version?

Thanks

Phil 


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


Re: math - need divisors algorithm

2005-03-30 Thread Philp Smith
excellent - thanks
in the meantime I managed to write something myself which
a)works
b)looks reasonably elegant and pythonic
but
c)   is recursive
d)  requires a mainroutine and co-routine

I have a feeling if I analysed it it would prove to be relatively 
inefficient as I'm sure it creates a lot of temporary objects (partial 
lists)

So I will gratefully try your version - and for interest's sake post mine at 
some point (its on other computer) for comment.

Phil

"Tim Peters" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> [Philp Smith]
>> Does anyone have suggested code for a compact, efficient, elegant, most 
>> of
>> all pythonic routine to produce a list of all the proper divisors of an
>> integer (given a list of prime factors/powers)
>
> If the canonical factorization of N is the product of p_i**e_i, the
> number of divisors is the product of e_i+1.  This can be
> astronomically large, so it's important to minimize the number of
> multiplications performed, and to write a generator to produce the
> divisors (it may, e.g., be impossible to materialize a list of all of
> them).
>
> This one's easy and efficient:
>
> def gen_divisors(prime_list):
>elts = sorted(set(prime_list))
>numelts = len(elts)
>
># Split on the number of copies of elts[i].
>def gen_inner(i):
>if i >= numelts:
>yield 1
>return
>thiselt = elts[i]
>thismax = prime_list.count(thiselt)
>
># powers <- [thiselt**i for i in range(thismax+1)],
># but using only thismax multiplications.
>powers = [1]
>for j in xrange(thismax):
>powers.append(powers[-1] * thiselt)
>
>for d in gen_inner(i+1):
>for prime_power in powers:
>yield prime_power * d
>
>for d in gen_inner(0):
>yield d
>
> For example, do:
>
> for d in gen_divisors([2, 3, 2, 3, 2, 3, 5, 2, 3]):
>print d
>
> You're on your own for the "proper" business; try not to use more than
> one line to do it .
>
> I find recursion clearest here.  An iterative version is easy enough
> to do by incrementing from 0 thru product(e_i) (and just skipping the
> endpoints if you really want "proper") in a mixed-radix system defined
> by the e_i.  Exercise for the reader.
>
> Harder:  generate divisors in increasing order. 


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


Re: Little Q: how to print a variable's name, not its value?

2005-03-30 Thread Aaron Bingham
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> Restating:  I'm doing some debugging of some code.  I want to print out
> the value of two variables whose names are known.  Let's call them
> myTime and myPlace.
>
> #debug:
> if self.debug:
>print "myTime = %s, myPlace = %s" % (myTime, myPlace)
>
> Notice that I had to type the variable's name once as an object, and
> once as the string representation of that object, i.e. the object's
> name.
> I wondered whether it might not be possible to do something like this:
> if self.debug:
>print "%s = %s" % ( name(myTime), myTime )
> where 'name' is the method or trick I'm after.

I must admit this is a bit of a sore point with me: this could be
solved so easily with a nice little macro .  For the case where
you only want to print the name and value of a variable (as opposed to
that of an expression), you may find this little function helpful:

def print_variable(name, scope):
print "%s = %r" % (name, scope[name])

You can call it like this:

print_variable('myTime', locals())

Not perfect, because you have to repeat locals() every time, but it
does save the repetition of the variable name.

Printing expressions can also be accomplished in a similar but more
dangerous[*] fashion:

def print_expression(expression, local_scope, global_scope=None):
if global_scope is None:
global_scope = globals()
print "%s = %r" % (expression, 
   eval(expression, local_scope, global_scope))

Example:

print_expression('i+1', locals())

[*] The use of eval here would make allowing user-entered expressions
here very dangerous, but as long as as it is used as a debugging
aid, with the expression as a literal string in the program, there
should be no security issue.  I would never use either of these
functions except as debugging aids anyway.

Regards,

-- 

Aaron Bingham
Software Engineer
Cenix BioScience GmbH


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


Re: LD_LIBRARY_PATH - how to set?

2005-03-30 Thread John Abel
With Solaris 8+ you would use the command crle, with Linux 
(RedHat/SuSE/Mandrake) you need to add the relevant directories 
/etc/ld.so.conf and run ldconfig.  I've not got a Debian box to hand, so 
I can't say if it matches, but that should give you a pointer.

HTH
J
Roman Yakovenko wrote:
On Mar 31, 2005 9:20 AM, John Abel <[EMAIL PROTECTED]> wrote:
 

What OS?  Linux?  Solaris?
   

Does it matter? If so, please explain why ( lack of knowledge )
I am using Linux ( Debian Surge  )
Thanks
 

J
Roman Yakovenko wrote:
   

Hi. I have small problem. I need to load extension module that depends
on shared library. Before actually importing module I tried to edit
os.environ or to call directly to os.putenv without any success -
shared library was not found. I tried to search the Internet for the
answer. The only approach I saw was to set LD_LIBRARY_PATH before
invoking python script. I don't like this solution.
Roman
 

 

--
*John Abel
Senior Unix Administrator*
PA News Limited
www.pa.press.net 
E-Mail address: [EMAIL PROTECTED] 
Telephone Number : 01430 43
Fax Number : 0870 1240192
Mobile Number : 07971 611356
The Bishop's Manor, Market Place, Howden, DN14 7BL
PA News Limited, 292 Vauxhall Bridge Road, London SW1V 1AE. Registered 
in England No. 3891053.
--
http://mail.python.org/mailman/listinfo/python-list


Re: LD_LIBRARY_PATH - how to set?

2005-03-30 Thread Roman Yakovenko
On Mar 31, 2005 9:20 AM, John Abel <[EMAIL PROTECTED]> wrote:
> What OS?  Linux?  Solaris?

Does it matter? If so, please explain why ( lack of knowledge )
I am using Linux ( Debian Surge  )

Thanks


> J
> 
> Roman Yakovenko wrote:
> 
> >Hi. I have small problem. I need to load extension module that depends
> >on shared library. Before actually importing module I tried to edit
> >os.environ or to call directly to os.putenv without any success -
> >shared library was not found. I tried to search the Internet for the
> >answer. The only approach I saw was to set LD_LIBRARY_PATH before
> >invoking python script. I don't like this solution.
> >
> >Roman
> >
> >
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Making a DLL with python?

2005-03-30 Thread jppx1
Can I use python to make a regular Windows DLL that will be called from
other programs?

I know I can use the win32 extensions to make a COM server, but I need
a straight DLL.

Regards,
Phillip

Phillip Piper
A man's life does not consist in the abundance of his possessions

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


Re: LD_LIBRARY_PATH - how to set?

2005-03-30 Thread John Abel
What OS?  Linux?  Solaris?
J
Roman Yakovenko wrote:
Hi. I have small problem. I need to load extension module that depends
on shared library. Before actually importing module I tried to edit
os.environ or to call directly to os.putenv without any success -
shared library was not found. I tried to search the Internet for the
answer. The only approach I saw was to set LD_LIBRARY_PATH before
invoking python script. I don't like this solution.
Roman
 

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


Re: Weakrefs to classes that derive from str

2005-03-30 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 "Raymond Hettinger" <[EMAIL PROTECTED]> wrote:

> [Ron Garret]
> > Thanks for the detailed explanation.  I understand now why you can't
> > create weakrefs to these types.  What I don't understand still is why
> > you can't create weakrefs to user-defined classes that inherit from
> > these types.  I would think that instances of user-defined classes have
> > the same header structure regardless of what they inherit from.  This
> > would seem to be supported by the fact that you can create weakrefs to
> > instances of user-defined classes that inherit from int and float.
> 
> It is an over-statement to say that it can't be done.  In fact, Michael 
> Hudson
> is already working on a patch.
> 
> It is more accurate to say that the current mechanism doesn't allow it.
> Michael's solution is to build a new mechanism.
> 
> The existing mechanism has a subclass extend the superclass's structure:
> 
>   [--someobj--][--subclassdata--]
>^
>|
>   | offset to wr table ---
> 
> The offset is fixed for the type and must be the same across instances.
> 
> This is a problem for tuples and ints because someobj is of varying length:
> 
>  [--tuple header, elem0, elem1, elem2--]
>  [--tuple header, elem0 ]
> 
> In contrast, ints and floats floats have no problem because they are always 
> the
> same size:
> 
>  [--int header, int value--]
> 
> 
> Raymond Hettinger

I see.  Thanks!

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


UnicodeEncodeError in string conversion

2005-03-30 Thread Maurice LING
Hi,
I'm working on a script that searches a public database and retrives 
results using SOAP interface. However, it seems that the results may 
contains unicodes. When I try to pump the results into Firebird database 
using kinterbasdb module, some results will give me a 
UnicodeEncodeError. From what I've gathered, it looks like the 
conversion from the results from SOAP interface to string results in the 
error.

Is there any way to get thru this?
Thanks
maurice
--
http://mail.python.org/mailman/listinfo/python-list


Re: Little Q: how to print a variable's name, not its value?

2005-03-30 Thread [EMAIL PROTECTED]
my god, I've created a monster!

Maybe I should restate my original problem. Actually, the word
'problem' is too strong. I had a little curiosity about whether I could
write a couple of lines of code more succinctly, or more pythonically.
  I didn't realize that this would trigger a discussion about mixing
data and objects - though I can see the danger if you get into some
situations. Hopefully mine is not one of those.

Restating:  I'm doing some debugging of some code.  I want to print out
the value of two variables whose names are known.  Let's call them
myTime and myPlace.

#debug:
if self.debug:
   print "myTime = %s, myPlace = %s" % (myTime, myPlace)

Notice that I had to type the variable's name once as an object, and
once as the string representation of that object, i.e. the object's
name.
I wondered whether it might not be possible to do something like this:
if self.debug:
   print "%s = %s" % ( name(myTime), myTime )
where 'name' is the method or trick I'm after.

Creating a dictionary is already more work than it's worth, not to
mention some of the more involved solutions.   I'm left to conclude
that it's not possible to do what I wanted with Python.  If that's the
case, so be it and I'll move on to explore other curiosities.

But surely if you create an integer object and assign it a value, e.g.
a = 3,
why shouldn't Python be able to tell you something like the following:
name(a)  >>> 'a'
?

thanks
S

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


Re: Python List Issue

2005-03-30 Thread Greg Ewing
Nick L wrote:
I noticed that with python lists, generally when you
make a copy of a list (ie, List1 = List2) List1 just becomes a reference to
List2 and any modifications done to List1 affects List2. Ok I can live with
this but I want to make a completely seperate copy not attached to the
original in anyway.
Although your immediate question has been answered (you wanted
a deep copy, not a shallow one), I think you should take a
step back and consider whether you really need to do that much
copying in the first place.
With the proper approach, I find it's extremely rare to need to
copy anything in a Python program, and rarer still to need
deep copying. Generally, it's better for a function not to
modify objects passed to it, unless that's the purpose of
the function. If a function needs a local copy of an argument,
it should create one itself, and not put the burden on the
caller.
Also, there are some things about your code that suggest you
still do not fully understand how scoping and assignment work
in Python:
def ApplySourceFunc(bob, final):
> ...
bob = final
final = []
These last two statements do not accomplish anything useful.
All they do is change which objects are referred to by the
parameter names 'bob' and 'final', which are local to the
function, and have no effect on anything outside it.
def ApplyOperatorsLoop(aList):
> ...
final.append(iTemp)
...
Here you are referring to the global variable 'final', not
the one passed as a parameter to ApplySourceFunc(). To get
the effect you seem to be after, you would need to pass
'final' on as a parameter to ApplyOperatorsLoop().
Here is how I would write this:
  def ApplySourceFunc(bob, final):
for item in bob:
  ApplyOperatorsLoop(item, final)
  def ApplyOperatorsLoop(item, final):
new_item = AddGetSpeed(item)
if new_item:
  final.append(temp)
  def AddGetSpeed(tList):
if tList and tList[-1][0] == 0:
  new_tList = tList[:]
  new_tList[-1] = new_tList[-1][:]
  new_tList[-1][0] = "GetSpeed()"
  print "New Rule 'GetSpeed()' Added to the List"
  return new_tList
else:
  return None
Notice how all the copying is done inside AddGetSpeed(),
it only copies what is needed, and the fact that the copying
is needed is encapsulated within the function; its callers
don't need to know.
I have also made use of some other common Python idioms:
* Whenever possible, it is simpler and clearer to iterate
  directly over the items of a list, rather than iterating
  over its indices and then indexing it.
* Almost any object can be used as a truth value. Non-empty
  lists count as true; empty lists and None count as false.
* The 'and' and 'or' operators short-circuit: if the first
  operand determines the result, the second operand is not
  evaluated.
* Negative list indices are counted from the end of the
  list; e.g. aList[-1] means the last item of aList.
Hope that helps,
--
Greg Ewing, Computer Science Dept,
University of Canterbury,   
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: returning a list: IndexError

2005-03-30 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
Steven Bethard wrote:
py> import numarray as na
py> tbl = na.zeros((32, 16))
py> def get_value():
... data = test()
... c1 = data[0]
... c2 = data[1]
... print tbl[c1, c2]
...
py> def test():
... t1 = 0x0
... t2 = 0x1
... return tbl[t1, t2]
...
py> get_value()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in get_value
TypeError: unsubscriptable object
What i was intending to do is return a list with row and column values.
data[0] and data[1] are the list values i get from test.
Whats the best way to read these row and column values in function
get_value() when i return the list (return tbl[t1, t2])
Still not sure I understand you.  Are you wanting c1 and c2 to retrieve 
the values that t1 and t2 had?  (That is, 0x0 and 0x1?)  Or do you want 
c1 and c2 to hold the first row and the first column?  Or something else?

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


Re: math - need divisors algorithm

2005-03-30 Thread Tim Peters
[Philp Smith]
> Does anyone have suggested code for a compact, efficient, elegant, most of
> all pythonic routine to produce a list of all the proper divisors of an
> integer (given a list of prime factors/powers)

If the canonical factorization of N is the product of p_i**e_i, the
number of divisors is the product of e_i+1.  This can be
astronomically large, so it's important to minimize the number of
multiplications performed, and to write a generator to produce the
divisors (it may, e.g., be impossible to materialize a list of all of
them).

This one's easy and efficient:

def gen_divisors(prime_list):
elts = sorted(set(prime_list))
numelts = len(elts)

# Split on the number of copies of elts[i].
def gen_inner(i):
if i >= numelts:
yield 1
return
thiselt = elts[i]
thismax = prime_list.count(thiselt)

# powers <- [thiselt**i for i in range(thismax+1)],
# but using only thismax multiplications.
powers = [1]
for j in xrange(thismax):
powers.append(powers[-1] * thiselt)

for d in gen_inner(i+1):
for prime_power in powers:
yield prime_power * d

for d in gen_inner(0):
yield d

For example, do:

for d in gen_divisors([2, 3, 2, 3, 2, 3, 5, 2, 3]):
print d

You're on your own for the "proper" business; try not to use more than
one line to do it .

I find recursion clearest here.  An iterative version is easy enough
to do by incrementing from 0 thru product(e_i) (and just skipping the
endpoints if you really want "proper") in a mixed-radix system defined
by the e_i.  Exercise for the reader.

Harder:  generate divisors in increasing order.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: : Last Chance 2005 IORCC Entries

2005-03-30 Thread iorcc
Ivan

Actually, it was simply an oversite by me, not by anyone else in the
Ruby community.  I hope you don't take offense to this simple mistake
of mine.  The contest is open (for another 12 hours or so) and nobody
is discriminated against as you suggest.  Pythonists are MOST welcome
to contribute, in fact all 'colors' of coders are welcome, whatever
flavor or preference of code you choose.   I hope to see your entry and
may you have the best of luck!

Todd

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


LD_LIBRARY_PATH - how to set?

2005-03-30 Thread Roman Yakovenko
Hi. I have small problem. I need to load extension module that depends
on shared library. Before actually importing module I tried to edit
os.environ or to call directly to os.putenv without any success -
shared library was not found. I tried to search the Internet for the
answer. The only approach I saw was to set LD_LIBRARY_PATH before
invoking python script. I don't like this solution.

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


Re: return the last item in a list

2005-03-30 Thread Erik Max Francis
Raymond Hettinger wrote:
I'm looking for an 'easy' way to have the last item in a list returned.
Try mylist.pop() or mylist[-1].
Note that list.pop also removes the last element from the list in the 
process.

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  Granted that I must die, how shall I live?
  -- Michael Novak
--
http://mail.python.org/mailman/listinfo/python-list


Re: Turn of globals in a function?

2005-03-30 Thread Greg Ewing
Oren Tirosh wrote:
def noglobals(f):
.   import new
.   return new.function(
.   f.func_code, 
.   {'__builtins__':__builtins__},
.   f.func_name, 
.   f.func_defaults, 
.   f.func_closure
.   )
Be aware that this will render the function incapable
of seeing *any* globals at all, including other
functions and classes defined in the same module --
which you may find rather inconvenient!
--
Greg Ewing, Computer Science Dept,
University of Canterbury,   
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: ossaudiodev full duplex

2005-03-30 Thread Greg Ewing
[EMAIL PROTECTED] wrote:
fh= ossaudiodev.open("/dev/dsp", "rw")
fh.setparameters(ossaudiodev.AFMT_S16_LE, number_of_channels,
sample_rate)
fh.writeall(frames_out)
frames_in= fh.read(number_of_samples * sample_width)
fh.close()
One problem with this is that you can't use a single file
object for independent reading and writing at the same
time. C stdio implementations tend to get confused if
you try to do that.
You may have other problems as well, but you'll at least
need to open two separate file objects.
--
Greg Ewing, Computer Science Dept,
University of Canterbury,   
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: mysteriously nonfunctioning script - very simple

2005-03-30 Thread Greg Ewing
Sean McIlroy wrote:
I did try it, and it didn't work either. It appears there must be
something wrong with my computer, hopefully something benign.
Just a thought: Is your computer's clock set correctly?
--
Greg Ewing, Computer Science Dept,
University of Canterbury,   
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.4.1 build (configure) ?

2005-03-30 Thread Skip Montanaro

Venkat> When I checked the .py sources (in Lib folder) thru grep for
Venkat> 'ipv6', I see the same references I'd see, if I ran the
Venkat> configure command without the --enable-ipv6 option.  Is that
Venkat> normal or is there an issue I need to address here.

Yes, it's normal.  Configure settings affect the compilation of the C code.
Grep the C source for "ENABLE_IPV6".

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


AAC extracton

2005-03-30 Thread Lucas Raab
In a M4A file encoded with iTunes, persay, how does one extraction the 
AAC data?? I'm looking into a project using pymedia and I know it 
supports the AAC format, but how does the extraction of AAC data work?? 
Just going a certain number of bytes into the file??

TIA
--
--
Lucas Raab
lvraab"@"earthlink.net
dotpyFE"@"gmail.com
AIM:Phoenix11890
MSN:dotpyfe"@"gmail.com
IRC:lvraab
ICQ:324767918
Yahoo:  Phoenix11890
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem running the cgi module

2005-03-30 Thread chris patton
Thanks for the help.

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


Re: problem running the cgi module

2005-03-30 Thread pythonUser_07
I will take a guess that you might
1) make sure cgi is enabled in your webserver configuration
2) Probably must place the cgi script under $WEBSERVERDOCS/cgi-bin
unless you alter the configuration.

Also, the webserver might need to be configured to understand what
interpreter uses .py files. (not an issue on windows)

Good luck

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


Re: urllib.urlretireve problem

2005-03-30 Thread gene . tani
.from urllib2 import urlopen
.   try:
. urlopen(someURL)
.   except IOError, errobj:
.if hasattr(errobj, 'reason'): print 'server doesnt exist, is
down, DNS prob, or we don't have internet connect'
.if hasattr(errobj, 'code'): print errobj.code

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


Re: [Tkinter] LONG POST ALERT: Setting application icon on Linux

2005-03-30 Thread Jeff Epler
I have written a rather hackish extension to use NET_WM_ICON to set
full-color icons in Tkinter apps.  You can read about it here:
http://craie.unpy.net/aether/index.cgi/software/01112237744
you'll probably need to take a look at the EWMH spec, too.  If KDE
supports NET_WM_ICON, this may work for you (but you'll have to convert
your image manually to the format required for NET_WM_ICON)

Best of luck!  Unfortunately, the code is not supported.

Jeff


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

Re: Weakrefs to classes that derive from str

2005-03-30 Thread Raymond Hettinger
[Ron Garret]
> Thanks for the detailed explanation.  I understand now why you can't
> create weakrefs to these types.  What I don't understand still is why
> you can't create weakrefs to user-defined classes that inherit from
> these types.  I would think that instances of user-defined classes have
> the same header structure regardless of what they inherit from.  This
> would seem to be supported by the fact that you can create weakrefs to
> instances of user-defined classes that inherit from int and float.

It is an over-statement to say that it can't be done.  In fact, Michael Hudson
is already working on a patch.

It is more accurate to say that the current mechanism doesn't allow it.
Michael's solution is to build a new mechanism.

The existing mechanism has a subclass extend the superclass's structure:

  [--someobj--][--subclassdata--]
   ^
   |
  | offset to wr table ---

The offset is fixed for the type and must be the same across instances.

This is a problem for tuples and ints because someobj is of varying length:

 [--tuple header, elem0, elem1, elem2--]
 [--tuple header, elem0 ]

In contrast, ints and floats floats have no problem because they are always the
same size:

 [--int header, int value--]


Raymond Hettinger






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


Re: returning a list: IndexError

2005-03-30 Thread shama . bell

Steven Bethard wrote:
> [EMAIL PROTECTED] wrote:
> > from Numeric import *
> >
> > # Initialize the 32x16 global array to zeros
> > tbl = zeros((32, 16)
> >
> > def getValue( value):
> > data = test(value)
> > c1 = data[0]
> > c2 = data[1]
> > print tbl[c1, c2]
> >
> > def test( value):
> > t1 = 0x0
> > t2 = 0x1
> > return tbl[t1, t2]
>
> In test, tbl[0x0, 0x1] is just going to give you a single element of
> tbl, in this case a 0.  So data is a 0.  data[0] and data[1] doesn't
> really make much sense.  Is this the code you actually get the
> IndexError with?  I'm using numarray, not Numeric, and I know there
are
> some differences, but the code above doesn't give me an IndexError:
>
> py> import numarray as na
> py> tbl = na.zeros((32, 16))
> py> def get_value():
> ... data = test()
> ... c1 = data[0]
> ... c2 = data[1]
> ... print tbl[c1, c2]
> ...
> py> def test():
> ... t1 = 0x0
> ... t2 = 0x1
> ... return tbl[t1, t2]
> ...
> py> get_value()
> Traceback (most recent call last):
>File "", line 1, in ?
>File "", line 3, in get_value
> TypeError: unsubscriptable object
>
> STeVe

What i was intending to do is return a list with row and column values.

data[0] and data[1] are the list values i get from test.

Whats the best way to read these row and column values in function
get_value() when i return the list (return tbl[t1, t2])

Thanks,
-SB

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


Re: Suggesting methods with similar names

2005-03-30 Thread Terry Reedy

"Bengt Richter" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> BTW, when are we going to be able to write
>
> @classdeco
> class Foo(object):

That possibility is currently being discussed for 2.5 on the pydev list. 
There are mixed opinions, none yet from Guido that I noticed.

Terry J. Reedy



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


returning a list: IndexError

2005-03-30 Thread shama . bell
Hello,

I am getting the following error when returning a list:

return tbl[c1,c2]

"IndexError: each subindex must be either a slice, an integer,
Ellipsis, or NewAxis"

What does it mean?

Here's the code snippet

from Numeric import *

# Initialize the 32x16 global array to zeros
tbl = zeros((32, 16)

def getValue( value):
data = test(value)
c1 = data[0]
c2 = data[1]
print tbl[c1, c2]

def test( value):
t1 = 0x0
t2 = 0x1
return tbl[t1, t2]

Thanks,
-SB

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


Re: McMillan Installer vs. Python 2.4

2005-03-30 Thread Simon John
[EMAIL PROTECTED] wrote:

> 1. Does anyone know why McMillan Installer 5b5 does not work with
> Python 2.4 under Linux (works with Python 2.3 just fine), and how to
> fix it?

I expect so.

> 2. Will anyone be picking up the maintenance and development ball for
> McMillan Installer?

There was a 6a2 release for Linux and Windows, but I don't think
anyone's developing it further.

> 3. Is there another, better-supported solution for distributing a
> Python executable under Linux/Unix/AIX?  A single-file solution (ala
> Installer's '--onefile') is a requirement for me.

cx_Freeze is good, but makes multiple files, if you need single file
you could just make the files into an RPM or simply tar.bz2 them up,
then your installation is just one file, extracted to many (still just
one directory)

> 4. Installer supports the use of upx for those platforms that support
> it.  AIX does not.  Does anyone have any other solutions for
> compressing a Python executable which still leaves that executable
> executable?  Believe it or not, the biggest impediment to my using
> Python at work is the enormous size of the executable. (Installing
> Python itself on the target platforms is not allowed).

I don't particularly like the way UPX works, it uses more memory in the
end anyway, and disk space is cheaper. You could use strip and python
--OO to remove docstrings etc.

I've written a couple of pretty complex GUI applications and have never
seen them build to anything more than about 7Mb for wxPython or about
3Mb for PyQt.

You could just distribute the source and use movpy as the interpreter.

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


Re: Suggesting methods with similar names

2005-03-30 Thread Bengt Richter
On Wed, 30 Mar 2005 17:55:32 GMT, "Raymond Hettinger" <[EMAIL PROTECTED]> wrote:

>[Bearophile]
>> Working in the interactive window I receive an error like
>> this when I write the wrong method name:
>>
>> >>> table.addGlas()
>> Traceback (most recent call last):
>>   File "", line 1, in ?
>> AttributeError: 'Surface' object has no attribute 'addGlas'
>>
>> Is it possibile to make the object give a better answer: a short list
>> of few method names similar to the one I've misspelled?
>
>[Bearophile]
>> Thank you, __getattr__ does what I need :-)
>> A smart help can be designed easely...
>
>The idea is a winner.  When you're done, consider posting the result as an ASPN
>cookbook recipe.
>
Interactively, I often use dir(whatever) to find methods, but I sure wish dir 
had
some keyword arguments to limit the returned info various ways, e.g., methods
of the immediate class, not the whole mro, and optionally without the __xxx__ 
methods.
Ditto with help().


BTW, when are we going to be able to write

@classdeco
class Foo(object):
   ...

so we can implement smart help as a decorator?

I.e., the above decorator syntax would be a non-intrusive way of spelling

class Foo(object):
__metaclass__ = classdeco
...

(haven't thought about cascaded decorators in this context ;-)

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


Python plug-in Frameworks like Eclipse RCP...

2005-03-30 Thread Jim Hargrave
Eclipse provides a very nice application framework which supports 
plug-ins. It's easy to dynamically add new functionality, menu items, 
property editors, options etc.. using a combination of XML and Java code.

Is there a similar framework for Python? If not any hints on how such a 
framework would be implemented?

I'm building a client side tool using Python/wxPython for our 
translators and would like to have a pluggable architecture similar to 
Eclipse RCP

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


Re: Using something other than ';' to separate statements

2005-03-30 Thread Michael Hoffman
Ivan Van Laningham wrote:
Bad Michael.  Bad, bad Michael.
:(
Well personally I consider it better to tell people of hacks
like that with a warning not to use them than let them
discover them on their own (without such a warning).
Plus dubious Python hacks that should never be used in
production code are fun, which is what c.l.p. is all about!
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


McMillan Installer vs. Python 2.4

2005-03-30 Thread mrmakent
3 quick questions for the newsgroup:

1. Does anyone know why McMillan Installer 5b5 does not work with
Python 2.4 under Linux (works with Python 2.3 just fine), and how to
fix it?

2. Will anyone be picking up the maintenance and development ball for
McMillan Installer?

3. Is there another, better-supported solution for distributing a
Python executable under Linux/Unix/AIX?  A single-file solution (ala
Installer's '--onefile') is a requirement for me.

4. Installer supports the use of upx for those platforms that support
it.  AIX does not.  Does anyone have any other solutions for
compressing a Python executable which still leaves that executable
executable?  Believe it or not, the biggest impediment to my using
Python at work is the enormous size of the executable. (Installing
Python itself on the target platforms is not allowed).

OK, that was 4.

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


Python 2.4.1 build (configure) ?

2005-03-30 Thread Venkat B
Hi all,

While building the latest 2.4.1 version for Linux/RH9, I wanted to enable
IPV6
support (sockets). So, I ran the configure command ./configure --enable-ipv6
Then I ran the 'make' and 'make altinstall' commands.

When I checked the .py sources (in Lib folder) thru grep for 'ipv6', I see
the same
references I'd see, if I ran the configure command without the --enable-ipv6
option.
Is that normal or is there an issue I need to address here.

Thanks,
/venkat


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


Re: urllib.urlretireve problem

2005-03-30 Thread Skip Montanaro

>> For example, for Temporary Name Resolution Failure, python raises an
>> exception which I've handled well. The problem lies with obsolete
>> urls where no exception is raised and I end up having a 404 error
>> page as my data.

Diez> It makes no sense having urllib generating exceptions for such a
Diez> case. From its point of view, things work pefectly - it got a
Diez> result. No network error or whatsoever.

You can subclass FancyURLOpener and define a method to handle 404s, 403s,
401s, etc.  There should be no need to resort to grubbing around with file
extensions and such.

Skip

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


RE: IMAP4.search by message-id ?

2005-03-30 Thread Tony Meyer
> Can anyone tell me how to get a message's number from the message-id 
> using IMAP4.search?
> I've tried this:
> resp, items = server.search(None, 'HEADER', 
> '"Message-id"', msgID) but it gives me a 'bogus search criteria' error

>>> import imaplib
>>> i = imaplib.IMAP4("mail.example.com")
>>> i.login("username", "password")
[...]
>>> i.select()
[...]
>>> i.search(None, '(HEADER Message-ID
"<[EMAIL PROTECTED]>")')
('OK', ['4'])
>>> i.logout()
[...]

=Tony.Meyer

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


Re: returning a list: IndexError

2005-03-30 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
from Numeric import *
# Initialize the 32x16 global array to zeros
tbl = zeros((32, 16)
def getValue( value):
data = test(value)
c1 = data[0]
c2 = data[1]
print tbl[c1, c2]
def test( value):
t1 = 0x0
t2 = 0x1
return tbl[t1, t2]
In test, tbl[0x0, 0x1] is just going to give you a single element of 
tbl, in this case a 0.  So data is a 0.  data[0] and data[1] doesn't 
really make much sense.  Is this the code you actually get the 
IndexError with?  I'm using numarray, not Numeric, and I know there are 
some differences, but the code above doesn't give me an IndexError:

py> import numarray as na
py> tbl = na.zeros((32, 16))
py> def get_value():
... data = test()
... c1 = data[0]
... c2 = data[1]
... print tbl[c1, c2]
...
py> def test():
... t1 = 0x0
... t2 = 0x1
... return tbl[t1, t2]
...
py> get_value()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in get_value
TypeError: unsubscriptable object
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Weakrefs to classes that derive from str

2005-03-30 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 "Raymond Hettinger" <[EMAIL PROTECTED]> wrote:

> [Ron Garret]
> > Why doesn't this work?
> >
> > >>> from weakref import ref
> > >>> class C(str): pass
> > ...
> > >>> ref(C())
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> > TypeError: cannot create weak reference to 'C' object
>  . . .
> >  Everything but strs.
> 
> Also subclasses of tuple are not weak referencable.
> 
> The issue is in the design of the C structure as a variable-sized immutable
> object.  Both strings and tuples allocate as a single unit of memory that 
> holds
> both the header information and the content information (the characters in a
> string or the array of object pointers for a tuple).  Since the size varies 
> from
> one string or tuple to the next, there is no straight-forward way for a 
> subclass
> to add an additional header field pointing to a list of weak references.
> 
> For lists and dicts, this is not a problem because the object is allocated in
> two sections, a fixed size header component and a pointer to another area of
> memory to hold the contents of the collection.  This makes it possible for a
> subclass to graft-on a weak reference pointer at a known, fixed offset from 
> the
> beginning of the header.
> 
> There are two ways to fix this.  One is to add a weak reference pointer to 
> every
> string object -- that way you wouldn't even have to subclass it.  Another way 
> is
> to break the object into two pieces as is done for mutable containers like 
> dicts
> and lists.
> 
> Both approaches consume time and space.  In general, that is not a big deal, 
> but
> fast, memory efficient strings and tuples are at the center of all things
> Python.  The need to weak reference this objects is somewhat rare in 
> comparison
> to the frequency of their other uses.  It did not make sense to always pay a
> time/space penalty just to create the possibility of weak referencing.
> 
> While the design decision is unlikely to change, the docs could certainly be
> improved.  A doc patch would be welcome.
> 
> FWIW, the work-arounds are to weak-reference instances of UserString or to
> create a custom class with a has-a relationship instead of an is-a 
> relationship.

Thanks for the detailed explanation.  I understand now why you can't 
create weakrefs to these types.  What I don't understand still is why 
you can't create weakrefs to user-defined classes that inherit from 
these types.  I would think that instances of user-defined classes have 
the same header structure regardless of what they inherit from.  This 
would seem to be supported by the fact that you can create weakrefs to 
instances of user-defined classes that inherit from int and float.

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


problem running the cgi module

2005-03-30 Thread chris patton
Hi everyone. I'm trying to code an HTML file on my computer to make it
work with the cgi module. For some reason I can't get it running. This
is my HTML script:

--


HOWDY!






--

And here is the python program it's supposed to run with,
formprinter.py:

--

import cgi, cgitb
cgitb.enable()

form = cgi.FieldStorage()
print '%s' % form['name']

--

Whenever I press submit on the HTML document, it returns the code for
"formprinter.py". Can someone tell me what I'm doing wrong?

-Thanks for any help!

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


Re: Weakrefs to classes that derive from str

2005-03-30 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 Peter Hansen <[EMAIL PROTECTED]> wrote:

> Ron Garret wrote:
> foo(int)
> foo(float)
> foo(dict)
> foo(list)
> foo(str)
> > TypeError: cannot create weak reference to 'C' object
> > 
> foo(tuple) 
> > TypeError: cannot create weak reference to 'C' object
> > 
> foo(long)
> > TypeError: cannot create weak reference to 'C' object
> > 
> > Ah, it appears that non-immediate immutable types don't support 
> > weakrefs.  Hm...
> 
> I see the same results you do, and yet I don't understand
> the comment.  Can you please explain what "immediate"
> means in this context?

"Immediate" means a data type that will fit entirely in a machine 
register, and therefore doesn't need to actually be stored in memory.  
Ints and floats are the only two immediate types in Python.  They are 
immutable, but you can still create weakrefs to classes that derive from 
them.

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


Re: More decorator rumination

2005-03-30 Thread Scott David Daniels
Jack Diederich wrote:
On Wed, Mar 30, 2005 at 02:48:51PM -0800, Scott David Daniels wrote:
In particular, I thought about something like:
   @mousexy
   def OnRightClick(self, x, y):
   ...
so all event-responding methods tend to look like:
   def OnRightClick(self, event):
   x = event.GetX()
   y = event.GetY()
It might be plainer (and certainly more backwards compatible) to
wrap the function when setting the event handler.
EVT_BUTTON(self.frame, XRCID("ButtonName"), mousexy(self.OnRightClick))
As a matter of style & clairty, it just depends. 
I think this is probably the right approach.
> If this is for education ...
I came here because it seemed to be drifting off-topic for education.
Thanks for the feedback.
-Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


More decorator rumination

2005-03-30 Thread Scott David Daniels
Over on comp.python.education we were discussing a (generally seen as)
misuse of decorators to build the definite integral of a function.
On thinking over the definite integral decorator, I had almost
decided that one necessary, but not sufficient, criterion for a
good decorator is that it must not change a function's arg list.
I was happy with this until just now.
I've been fighting wxPython a lot recently, and suddenly a good
working definition for a decorator came to me:
*  A decorator mediates between a function and its environment.
In particular, I thought about something like:
@mousexy
def OnRightClick(self, x, y):
...
For those non-wx'ers, all GUI events come wrapped in an "event",
so all event-responding methods tend to look like:
def OnRightClick(self, event):
x = event.GetX()
y = event.GetY()
which looks like boilerplate to me.  I'm wondering whether others
think this is an interesting insight into what decorators are "for,"
or they think I'm working on "the moral equivalent of a macro."
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: initialize a dictionary

2005-03-30 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
I need to iterate values by row and column as well.
I tried this
w,x = 32, 16
A = [ [0x0]*w for i in range(x)]
print A
py> import numarray
py> print numarray.zeros((16, 8))
[[0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]]
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesting methods with similar names

2005-03-30 Thread bearophileHUGS
Diez B. Roggisch>it will make an object return always _something_ - and
thus you don't catch misspellings in non-interactive<

Uhm, I'm sorry, I don't understand you.
If you look at the code I've just posted, you can see that it still
raises AttributeError, the difference is just the error message...

Bearophile

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


Re: initialize a dictionary

2005-03-30 Thread shama . bell
The F.A.Q. does not explain how to create a 2 dimensional array and
initialize it to zero.

I need to iterate values by row and column as well.

I tried this
w,x = 32, 16
A = [ [0x0]*w for i in range(x)]
print A
It does not create a 2 dimensional array with 32 rows and 16 columns

Thanks,
-SB

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


pySerial- need help.

2005-03-30 Thread kamarudin samsudin
Hi all,

I try to invoke python serial script via my browser using PHP (exec
function). For the serial communication, i used pySerial module. It
fine when it run it as root but when i try to run it from browser, i
got this error in my httpd/error_log

  File "weather1.py", line 9, in ?
ser=serial.Serial('/dev/ttyS0',9600,timeout=1)
  File "/usr/lib/python2.3/site-packages/serial/serialutil.py", line
153, in __init__
self.open()
  File "/usr/lib/python2.3/site-packages/serial/serialposix.py", line
137, in open
raise SerialException("Could not open port: %s" % msg)
serial.serialutil.SerialException: Could not open port: [Errno 13]
Permission denied: '/dev/ttyS0'

i tried chmod go+wr /dev/ttyS0 but i still got the error.

BTW, i used apache 2.0.52, PHP 4.3.10 and Fedora Core 3 

Thanks in advance.

-- 
regards,
kamarudin samsudin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there a problem on this simple code

2005-03-30 Thread jrlen balane
a simple question regarding threading and timer:

if i put my timer control inside the thread, will the thread be exited
every time there is a timer event???

please help...

def someThreadHere()
 ...
 someTimer.start(3000)
 

def someTimerEvent()
 .


 
On Wed, 16 Mar 2005 07:38:09 GMT, Dennis Lee Bieber
<[EMAIL PROTECTED]> wrote:
> On Wed, 16 Mar 2005 09:47:01 +0800, jrlen balane <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
> > please post your suggestions? please ...
> >
>Since we don't have your hardware, nor have you been able supply
> the formal documentation of the protocol in use, all we can do is
> comment on coding styles and obvious errors in the code... If there is
> an flaw in the implementation of the protocol, we have no way to tell.
> 
> >
> 
> > > import sys
> > > import serial
> > > import sys, os
> > > import serial
> 
>How about cleaning that up... You've imported serial twice, and
> sys twice.
> 
> > > data_file = open('C:/Documents and Settings/nyer/Desktop/IRRADIANCE.txt', 
> > > 'r')
> > > data = data_file.readlines()
> > >
> > > def process(list_of_lines):
> > > data_points = []
> > > for line in list_of_lines:
> > > data_points.append(int(line))
> > > return data_points
> > >
> > > irradiance = process(data)
> 
>Well, this is legal, though confusing to stuff a function
> definition between lines of the main program. Common is to put the
> "def"s after the "imports" (though defining "constants" may be okay in
> there)
> 
>If "process" is only used once, it might not even be worth the
> "def"...
> 
> > >
> > > ser = serial.Serial()
> > > ser.baudrate = 9600
> > > ser.port = 0
> > > ser
>Delete that -- you've been told that it is meaningless for days
> now... If you don't want to take advice, why ask?
> 
> > >
> > > ser.open()
> > > tx_command = 67
> > > tx_no_databyte = 2
> > > tx_message_no = 1
> > > tx_len = len (irradiance)
> > >
> > > for j in range (tx_len)  :
> > > start_time = time.time()
> > >
> > > temp1 = []
> > > temp2 = []
> > > pyra1 = []
> > > pyra2 = []
> > > voltage = []
> > > current = []
> > >
> > > current_time = time.time()
> > >
> > > while( current_time >= start_time + 300):
> > >
>If current time is < start+300, the entire loop will be skipped
> -- a condition that is quite likely to happen unless you have a /very/
> slow machine.
> 
> > > data_hi, data_lo = divmod(irradiance[j], 0x100)
> > > tx_checksum = -(data_hi + data_lo + tx_command + tx_message_no
> > > + tx_no_databyte) & 0xff
> > > ser.write(pack('6B', tx_command, tx_message_no,
> > > tx_no_databyte, data_lo, data_hi, tx_checksum))
> > >
> > > rx_data = ser.read(19)
> > > rx_len = len(rx_data)
> > > byte = [ord(x) for x in rx_data]
> > >
> > > if rx_len < 10:
> > > #print 'it is not pumping data out as fast as we assumed'
> > > sys.exit(1)
> > >
> > > for k in range (rx_len-9):
> > > if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10])
> > > & 0xff == 0:
> > > #print byte[k:k+10]
> > >
> > > temp1.append(byte[k+3])
> > > temp2.append(byte[k+4])
> > > pyra1.append(byte[k+5])
> > > pyra2.append(byte[k+6])
> > > voltage.append(byte[k+7])
> > > current.append(byte[k+8])
> > > print temp1, temp2, pyra1, pyra2, voltage, current
> > >
>All these are lists, do you really mean to print the entire list
> each time, or only the most recent data value?
> 
> > > current_time = time.time()
> > >
> > > while theres no error in the output, there is also no response from
> > > the hardware or maybe communication is off.
> > >
> > > could somebody out there help me.
> > >
> 
> > > by the way, here is a working code: though here the data to be
> > > transmitted is just incrementing and not read from a text file:
> > >
> > > import serial
> > > import string
> > > import time
> > > from struct import *
> > > import os
> > >
> > > ser = serial.Serial()
> > >
> > > ser.baudrate = 9600
> > > ser.port = 0
> > > ser.timeout = 1
> > > ser
> > >
> > > ser.open()
> > > tx_command = 67
> > > tx_message_no = 1
> > > tx_no_databyte = 2
> > > item=1
> > > for item in range(1, 30001, 10):
> > >
> > > data_hi, data_lo = divmod(item, 0x100)
> > > tx_checksum = -(data_hi + data_lo + tx_command + tx_message_no +
> > > tx_no_databyte) & 0xff
> > > ser.write(pack('6B', tx_command, tx_message_no, tx_no_databyte,
> > > data_lo, data_hi, tx_checksum))
> > > #print tx_command, tx_message_no, tx_total_data, data_lo, data_hi,
> > > tx_checksum
> > >
> > >
> > > rx_data = ser.read(19)
> > > rx_len = len(rx_data)
> > > #print 'rx_len', rx_len
> > > byte = [ord(x) for x in rx_data]
> > > #print 'received', byt

Re: [maintenance doc updates]

2005-03-30 Thread "Martin v. Löwis"
Do Re Mi chel La Si Do wrote:
But, for previous versions of Python, I downloaded a CHM version; and, at 
http://docs.python.org/download.html, I don't found this format.

is this a lapse of memory?
It is there now.
Would it be possible to have a continuity in the availability of the 
formats?
Unfortunately, no. The only way to build the CHM file is using HTML
workshop, which requires Windows to run, yet Fred builds the rest of
the documentation on Linux (I believe). So the current process is that
Fred builds the HTML tarball (along with all other formats), uploads
it to python.org. I download it from there (which takes 12-36h due
to time zone differences, and other commitments, like taking exams
from students); I then build the CHM, and put it into the Windows
MSI file. 12 hours after that, I get home and find that I forgot to
upload the CHM file to python.org. I now have to find out where
precisely it is stored on python.org, and checkout docs.python.org.
I then upload the CHM file into the right location, edit download.ht,
regenerate download.html, invoke "make install", and commit the
change to CVS. I do this on Linux, so I first install xchm to verify
that the CHM I'm uploading is really the one for 2.4.1.
IOW, there is too many manual steps in the process to guarantee
continuity, and the process works differently each time (which
currently is only two times: 2.4, and 2.4.1)
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: initialize a dictionary

2005-03-30 Thread Sean Blakey
On 30 Mar 2005 13:02:05 -0800, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> Hello,
> 
> Can I do something like this?
> 
> table = {}
> table[32, 16] = 0x0
> 
> Where 32 specifies rows and 16 specifies columns and i am trying to
> initialize it to zero
> 
> I should be able to do comparisons like:
> table[t1, t2] == 0x1 etc.
> -SB
> 

Try it. It works. Sort of.

This code actually creates a dict named "table" mapping the key tuple
(32, 16) to the value 0x0. Note that you are NOT creating a
two-dimensional array, so this approach may be problematic if you ever
need to iterate values "by row" or "by column".

There is a python F.A.Q. on this, which you may find useful:
http://www.python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list



-- 
Sean Blakey
Saint of Mild Amusement, Evil Genius, Big Geek
Python/Java/C++/C(Unix/Windows/Palm/Web) developer
quine = ['print "quine =",quine,"; exec(quine[0])"'] ; exec(quine[0])
-- 
http://mail.python.org/mailman/listinfo/python-list


initialize a dictionary

2005-03-30 Thread shama . bell
Hello,

Can I do something like this?

table = {}
table[32, 16] = 0x0

Where 32 specifies rows and 16 specifies columns and i am trying to
initialize it to zero

I should be able to do comparisons like:
table[t1, t2] == 0x1 etc.
-SB

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


Re: itertools to iter transition

2005-03-30 Thread David M. Cooke
Steven Bethard <[EMAIL PROTECTED]> writes:

> Terry Reedy wrote:
>>>But if classmethods are intended to provide alternate constructors
>> But I do not remember that being given as a reason for
>> classmethod().  But I am not sure what was.
>
> Well I haven't searched thoroughly, but I know one place that it's
> referenced is in descrintro[1]:
>
> "Factoid: __new__ is a static method, not a class method. I initially
> thought it would have to be a class method, and that's why I added the
> classmethod primitive. Unfortunately, with class methods, upcalls
> don't work right in this case, so I had to make it a static method
> with an explicit class as its first argument. Ironically, there are
> now no known uses for class methods in the Python distribution (other
> than in the test suite).

Not true anymore, of course (it was in 2.2.3). In 2.3.5, UserDict,
tarfile and some the Mac-specific module use classmethod, and the
datetime extension module use the C version (the METH_CLASS flag).

And staticmethod (and METH_STATIC) aren't used at all in 2.3 or 2.4 :-)
[if you ignore __new__]

-- 
|>|\/|<
/--\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesting methods with similar names

2005-03-30 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> I have a class Surface with many methods. Working in the interactive
> window I receive an error like this when I write the wrong method name:
> 
 table.addGlas()
> Traceback (most recent call last):
>   File "", line 1, in ?
> AttributeError: 'Surface' object has no attribute 'addGlas'
> 
> Is it possibile to make the object give a better answer: a short list
> of few method names similar to the one I've misspelled?

Have you heard of rlcompleter2? It gives you tab-completion on the repl.

While your idea looks nice at first glance, what I don't like about it that
it will make an object return always _something_ - and thus you don't catch
misspellings in non-interactive, or at least not where they actually happen
but when you try to work with the results.

-- 
Regards,

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


Re: urllib.urlretireve problem

2005-03-30 Thread Diez B. Roggisch
> I'm coding a program for offline package management.
> The link that I provided could be obsolete by newer packages. That is
> where my problem is. I wanted to know how to raise an exception here so
> that depending on the type of exception I could make my program function.
> 
> For example, for Temporary Name Resolution Failure, python raises an
> exception which I've handled well. The problem lies with obsolete urls
> where no exception is raised and I end up having a 404 error page as my
> data.
> 
> Can we have an exception for that ?  Or can we have the exit status of
> urllib.urlretrieve to know if it downloaded the desired file.
> I think my problem is fixable in urllib.urlopen, I just find
> urllib.urlretrieve more convenient and want to know if it can be done with
> it.

It makes no sense having urllib generating exceptions for such a case. From
its point of view, things work pefectly - it got a result. No network error
or whatsoever.

Its your application that is not happy with the result - but it has to
figure that out by itself. 

You could for instance try and see what kind of result you got using the
unix file command - it will tell you that you received a html file, not a
deb.

Or check the mimetype returned - its text/html in the error case of yours,
and most probably something like application/octet-stream otherwise.

Regards,

Diez

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


Re: Newbiw - PypenGL and OpenGLContext

2005-03-30 Thread Mike C. Fletcher
Steve T wrote:

>I have been searching for a language to help with a product I am
>developing - last week I discovered PYOpenGL - looks really useful.  I
>found some demos which I studied to create part of what I need (a heap
>of boxes) but when I try and add an image to the box faces it looks as
>if I have to delve into OpenGLContext.  Now from here drawing boxes is
>no longer as simple.  My main driver is speed of _development_ (not
>graphics speed) so I would really like to be able to say
>box(position_vector, size_vector,texture_file).
>
>Am I on the wrong track entirely here, should I pursue OpenGLContext
>or am I misusing the visual.* parts of PYOpenGL?
>  
>
If you are really just drawing boxes, then raw PyOpenGL *may* be
appropriate, but you'll need to figure out the wonders of texturing. 
You can find some pretty good code for that in the NeHe demos (I believe
around the 6th or 7th).  They create a rotating textured, lit box, so if
that's all you need, you're golden.

If your goal is to eventually produce a more involved scene, you will
likely want one of the scenegraph engines.  Obviously I'm biased toward
OpenGLContext, but it's visual-alike package (i.e. a simplified
scenegraph model) is not yet ready for prime time, so you'd have to use
the full VRML97 model to create your boxes.  That would look something
like this:

from OpenGLContext import testingcontext
BaseContext, MainFunction = testingcontext.getInteractive()
from OpenGLContext.scenegraph.basenodes import *

class TestContext( BaseContext ):
def OnInit( self ):
"""Initialise and set up the scenegraph"""
self.sg = sceneGraph(
children = [
Transform(
rotation = (0,1,0,.8),
children = [
Shape(
geometry = Box( size=(4,4,2) ),
appearance = Appearance(
material = Material(
diffuseColor =(1,1,1)
),
texture = ImageTexture(
url =
"http://blog.vrplumber.com/images/ruminations.jpg";,
),
),
),
],
),
],
)
def getSceneGraph( self ):
"""With older OpenGLContext versions need to explicitly
return this"""
return self.sg

if __name__ == "__main__":
MainFunction( TestContext )

There are other retained-mode/scenegraph engines available besides
OpenGLContext, you can find a listing of some of them here:

http://www.vrplumber.com/py3d.py?category=retained

HTH,
Mike


  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com

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


Re: Using something other than ';' to separate statements

2005-03-30 Thread Ivan Van Laningham
Hi All--

Michael Hoffman wrote:
> 
> Jaime Wyant wrote:
> 
> > # This won't work
> > if a > 5: print "a > 5";else print "Doh"
> 
> This will:
> 
> ["Doh", "a > 5"][a > 5]
> 
> I highly discourage using it though--it's somewhat obtuse.
>

Bad Michael.  Bad, bad Michael.

Metta,
Ivan
--
Ivan Van Laningham
God N Locomotive Works
http://www.andi-holmes.com/
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN]: Last Chance 2005 IORCC Entries

2005-03-30 Thread Ivan Van Laningham
Hi All--

[EMAIL PROTECTED] wrote:
> 
> FOR IMMEDIATE RELEASE: Wed Mar 30 11:58:39 CST 2005
> LOCATION:  http://iorcc.dyndns.org/2005/press/033005.html
> ANNOUNCEMENT:  2005 IORCC Deadline Approaches
>Entry Deadline March 31st, 2005
>Less than 36 Hours Left, Great Prizes and Fun!
> 
> Dear Rubyists, Perlists, Shellists, Cists and Hackers,
> 

I still don't understand why we are receiving this.  Apparently,
Pythonistas are either not eligible or we are lumped under 'Hackers.' 
If the former, I can certainly understand; it is possible, but
fiendishly difficult, to write obfuscated code in Python, and thus, any
Pythonista submitting *any* obfuscated code would win almost by
default.  The others wouldn't even bother to enter, in that case.

If the latter, that shows what they think of us, and why should we enter
a contest where we are dissed by being shoehorned into someone else's
categories?

Metta,
Ivan
--
Ivan Van Laningham
God N Locomotive Works
http://www.andi-holmes.com/
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using something other than ';' to separate statements

2005-03-30 Thread Peter Hansen
Michael Hoffman wrote:
Jaime Wyant wrote:
# This won't work
if a > 5: print "a > 5";else print "Doh"

This will:
["Doh", "a > 5"][a > 5]
I highly discourage using it though--it's somewhat obtuse.
It's also limited to evaluating expressions, which is
probably not very useful to the OP...
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if program is installing using python

2005-03-30 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
does this help?
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52224
It's very rare that a program like Word is installed
in the PATH, so it's unlikely this helps.
Generally you would need to look in the registry, or
perhaps use os.popen() to parse the output of executing
the command "assoc .doc", to do what is required.
It might help for the OP to describe more about what
he plans to do with the information, since there might
be simpler/better approaches.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


[ANN]: Last Chance 2005 IORCC Entries

2005-03-30 Thread iorcc
FOR IMMEDIATE RELEASE: Wed Mar 30 11:58:39 CST 2005
LOCATION:  http://iorcc.dyndns.org/2005/press/033005.html
ANNOUNCEMENT:  2005 IORCC Deadline Approaches
   Entry Deadline March 31st, 2005
   Less than 36 Hours Left, Great Prizes and Fun!

Dear Rubyists, Perlists, Shellists, Cists and Hackers,

Well, it has boiled down to this, a great finish for the International
Obfuscated Ruby Code Contest, 2005 Edition.  There is still 30 hours
left to get your obscure and wacky Ruby code entered.  Surf on over to
the Official IORCC rules and website:

   http://iorcc.dyndns.org


With over $2000 USD in prizes from notable industry leaders like Stone
Design, OmniGroup, Luscious Monster, OpenBase, Bare Bones Software,
O'Reilly Press, Syngress, Purgatory Design, Running With Scissors,
BasaSoft, Ecto, Puzzles Forever, Pragmatic Programmer, Bartas Tech,
Macro Mates, Ambrosia Software, Sol Robots, Code Tek, dbSuite and more!
 You just won't believe the list of prizes these generous people have
committed to giving away!  Dust off your Ruby compiler, take your Perl,
Shell, Python and Tcl skills to the test, making a really obscure and
obfuscated entry for this years contest.

Entry window closes at 23:59:59 Universal Time March 31st, 2005.
Official Sponsors, Rules and Entry Guidelines are available online at
the IORCC Website.  Enter Today!  We'd like to also say thanks to the
following people and companies in chronological order of sponsorship:

- Dave Thomas, Signed copies of PickAxe and Ruby on Rails books!
- Syngress Press, Ruby the Developers Guide (700+ pages of real world
Ruby)
- Purgatory Design's Intaglio, graphics application for charting
obscure entries.
- O'Reilly and Associates, The Ruby Nutshell book, need we say more?
- Andrew Stone's, Stone Design Suite, Create, Graphics, WebApps,
Applets and more!
- Puzzles Forever, the folks that invented Solitaire Forever.
- OpenBase SQL, OpenStep and now OSX Database solutions for Linux,
Windows and MacOSX.
- Postal2: Share the Pain from the sick puppies at Running With
Scissors/Infamous Gary Coleman.
- Sol Robot's CrosswordForge, word finder and crossword puzzle
generator.  Fun for all.
- Bartas Technologies' CopyWrite, got a book or documents to publish?
Use CopyWrite.
- MacroMates' TextMate.  Lightweight and POWERFUL code project
management tool, really slick!
- CodeTek's Virtual Desktop.  The definitive way to expand and maximize
your desktop workspace.
- OmniGroup's OmniGraffle and OmniOutline, the way to go in
professional presentations.
- InterServices New Media's, dbSuite WebBuilder and SQL4X Manager J for
OS X.
- Ecto for OS X, the power of the blog!
- BasaSoft's, BasaOne, the Integrated Web Application Development
Environment.
- Bare Bones Software, with Mail Smith and BBEdit, the Professional
HTML editing for OS X.
- Pipe, simple, elegant, powerful.  The utility editor for OS X.
- Ambrosia Software, with SnapzProX 2 and WireTap Pro.  Make moves from
the desktop!
- Delicious Monster, with of course Delicious Library.  Catalog your
videos, music and more!

A big thank you to all the contestants, sponsors and support from the
Ruby community.  We have had a great time putting this together, and
now we can (almost) begin the judging process.  Winners will be
announced after noon April 1st, 2005.  A public voting forum for the
2005 IORCC People's Choice Award will be opened with voting continuing
thru the 15th of April, 2005.  Winners will be announced shortly after
the web voting is closed and counted.

Best of luck to you all!

Todd Nathan
IORCC Founder/Judge
irc://irc.freenode.net/iorcc (SeaForth)
http://iorcc.dyndns.org/
"What you talkin about Willis?" - GC


2005 IORCC Sponsor Home Page Links:

http://www.pragprog.com/
http://www.syngress.com/
http://www.purgatorydesign.com/
http://www.oreilly.com/
http://www.stone.com/
http://www.solitaireforever.com/
http://www.openbase.com/
http://www.gopostal.com/
http://www.solrobots.com/
http://www.bartastechnologies.com/
http://www.macromates.com/
http://www.codetek.com/
http://www.omnigroup.com/
http://www.dbsuite.de/
http://ecto.kung-foo.tv/
http://www.basasoft.com/
http://www.barebones.com/index.shtml
http://www.kcore.de/
http://www.ambrosiasw.com/news/
http://www.delicious-monster.com/

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


Re: Using something other than ';' to separate statements

2005-03-30 Thread Michael Hoffman
Jaime Wyant wrote:
# This won't work
if a > 5: print "a > 5";else print "Doh"
This will:
["Doh", "a > 5"][a > 5]
I highly discourage using it though--it's somewhat obtuse.
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem in designing a global directory in python

2005-03-30 Thread Bruno Desthuilliers
'@'.join([..join(['fred','dixon']),..join(['gmail','com'])]) a écrit :
noob warning:
what is so wonderful about the NEW class over the old ?
A whole lot of things. But the main thing to know is that old-style 
classes are deprecated, and will disappear in the future.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using something other than ';' to separate statements

2005-03-30 Thread Jaime Wyant
On Wed, 30 Mar 2005 14:26:20 -0500, Peter Hansen <[EMAIL PROTECTED]> wrote:
> Jaime Wyant wrote:
> > Well, I'm embedding python in an old C console app.  This app uses a
> > lot of ; delimited records.
> >
> > I want to allow the execution of arbitrary python statements inside
> > some of these records.  I was hoping there was an easy way to set the
> > statement terminator.  I will simply make up a new terminator and do
> > some string substitution to turn my new terminator into python's ';'.
> 
> You refer to it here as a statement terminator, but in
> the first posting you called it a statement separator.
> I believe it is just a separator, not a terminator, and
> as such is not even required unless you need/want to have
> two statements on the same line.

Yeah, my thinking was that a separator implied terminator, because to
separate something has to have a beginning / ending.  Sorry for the
inconsistency.

Anyway, I did want to be able to string a handful of statements
together in one "string".  The python statements were one of the
semicolon delimited fields I'm working with -- which is where my
problem lied.

After goofing around with this idea, I've realized you can't be very
expressive with a bunch of python statements strung together.  My
biggest problem is that I can't figure out (i don't think you can),
how to do conditionals that are strung together:

# This won't work
if a > 5: print "a > 5";else print "Doh"

I've decided to just call a function from the semicolon delimited
record, using the return value in my `C' app...

> In all the tens of thousands of lines of Python code
> I've written, I don't believe I've ever used a single
> semicolon to separate two statements.
> 
> Perhaps you don't need them either...

Yeah, I tried to "make it work", but it just won't.  At least not in a
satisfactory way.

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


Re: Problem in designing a global directory in python

2005-03-30 Thread Bruno Desthuilliers
Tian a écrit :
I googled about how to write singleton in python, but even if I use
Singleton, in which module's namespace should I keep the instance of
this singleton? 
You found the doc but I'm afraid you did not grasp the concept.
You don't have to 'keep the instance' anywhere - it's the job of the 
singleton to do this. The principle of the Singleton is that you can 
have *only one* instance of it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: AttributeError: ClassA instance has no attribute '__len__'

2005-03-30 Thread [EMAIL PROTECTED]
The most simple way to get this error I can think of is like this. It
happens because len does not know how to calculate the lenght of this
object.
-class classA:
-   def __init__(self):
-   pass

-a = classA()
-print len (a)

Traceback (most recent call last):
  File "./test.py", line 10, in ?
print len (a)
AttributeError: classA instance has no attribute '__len__'

You can fix it by adding a __len__ method:
class classA:
def __init__(self):
pass

def __len__(self):
return 0

a = classA()
print len (a)

See http://docs.python.org/ref/sequence-types.html

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


Python and USB

2005-03-30 Thread RaviPaike








Rogger,

I am trying to use wrapper for libusb. I downloaded the
Usb.py but I am not sure that I have the libusb installed on my Pc. Can you
help me in getting libusb.py or libusb.c .

 

Thank you,

Ravi






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

Re: Using something other than ';' to separate statements

2005-03-30 Thread André Roberge
Jaime Wyant wrote:
[snip]
After goofing around with this idea, I've realized you can't be very
expressive with a bunch of python statements strung together.  My
biggest problem is that I can't figure out (i don't think you can),
how to do conditionals that are strung together:
# This won't work
if a > 5: print "a > 5";else print "Doh"
I've decided to just call a function from the semicolon delimited
record, using the return value in my `C' app...
The following might work based on the context:
code = '''if a > 5: \nprint "a > 5"\nelse:\nprint "Doh"\n'''
or, formatted differently
code = '''
if a > 5:
print "a > 5"
else:
print "Doh"
'''
Then, you could do
exec(code)
Yeah, I tried to "make it work", but it just won't.  At least not in a
satisfactory way.
Thanks!
jw
André
--
http://mail.python.org/mailman/listinfo/python-list


TOC of Python Cookbook now online (was Re: author index for Python Cookbook 2?)

2005-03-30 Thread beliavsky
[EMAIL PROTECTED] wrote:
> Premshree Pillai wrote:
> > There's an index here:
> http://harvestman.freezope.org/cookbook/creds.html
>
> That lists the authors. Where is a list of the recipes?

I emailed the O'Reilly webmaster, and the table of contents are now
online at http://www.oreilly.com/catalog/pythoncook2/toc.html and also
listed below.

Table of Contents
Preface
1. Text
   1.1 Processing a String One Character at a Time
   1.2 Converting Between Characters and Numeric Codes
   1.3 Testing Whether an Object Is String-like
   1.4 Aligning Strings
   1.5 Trimming Space from the Ends of a String
   1.6 Combining Strings
   1.7 Reversing a String by Words or Characters
   1.8 Checking Whether a String Contains a Set of Characters
   1.9 Simplifying Usage of Strings' translate Method
   1.10 Filtering a String for a Set of Characters
   1.11 Checking Whether a String Is Text or Binary
   1.12 Controlling Case
   1.13 Accessing Substrings
   1.14 Changing the Indentation of a Multiline String
   1.15 Expanding and Compressing Tabs
   1.16 Interpolating Variables in a String
   1.17 Interpolating Variables in a String in Python 2.4
   1.18 Replacing Multiple Patterns in a Single Pass
   1.19 Checking a String for Any of Multiple Endings
   1.20 Handling International Text with Unicode
   1.21 Converting Between Unicode and Plain Strings
   1.22 Printing Unicode Characters to Standard Output
   1.23 Encoding Unicode Data for XML and HTML
   1.24 Making Some Strings Case-Insensitive
   1.25 Converting HTML Documents to Text on a Unix Terminal
2. Files
   2.1 Reading from a File
   2.2 Writing to a File
   2.3 Searching and Replacing Text in a File
   2.4 Reading a Specific Line from a File
   2.5 Counting Lines in a File
   2.6 Processing Every Word in a File
   2.7 Using Random-Access Input/Output
   2.8 Updating a Random-Access File
   2.9 Reading Data from zip Files
   2.10 Handling a zip File Inside a String
   2.11 Archiving a Tree of Files into a Compressed tar File
   2.12 Sending Binary Data to Standard Output Under Windows
   2.13 Using a C++-like iostream Syntax
   2.14 Rewinding an Input File to the Beginning
   2.15 Adapting a File-like Object to a True File Object
   2.16 Walking Directory Trees
   2.17 Swapping One File Extension for AnotherThroughout a
Directory Tree
   2.18 Finding a File Given a Search Path
   2.19 Finding Files Given a Search Path and a Pattern
   2.20 Finding a File on the Python Search Path
   2.21 Dynamically Changing the Python Search Path
   2.22 Computing the Relative Path from One Directory to Another

   2.23 Reading an Unbuffered Character in a Cross-Platform Way
   2.24 Counting Pages of PDF Documents on Mac OS X
   2.25 Changing File Attributes on Windows
   2.26 Extracting Text from OpenOffice.org Documents
   2.27 Extracting Text from Microsoft Word Documents
   2.28 File Locking Using a Cross-Platform API
   2.29 Versioning Filenames
   2.30 Calculating CRC-64 Cyclic Redundancy Checks
3. Time and Money
   3.1 Calculating Yesterday and Tomorrow
   3.2 Finding Last Friday
   3.3 Calculating Time Periods in a Date Range
   3.4 Summing Durations of Songs
   3.5 Calculating the Number of Weekdays Between Two Dates
   3.6 Looking up Holidays Automatically
   3.7 Fuzzy Parsing of Dates
   3.8 Checking Whether Daylight Saving Time Is Currently in Effect

   3.9 Converting Time Zones
   3.10 Running a Command Repeatedly
   3.11 Scheduling Commands
   3.12 Doing Decimal Arithmetic
   3.13 Formatting Decimals as Currency
   3.14 Using Python as a Simple Adding Machine
   3.15 Checking a Credit Card Checksum
   3.16 Watching Foreign Exchange Rates
4. Python Shortcuts
   4.1 Copying an Object
   4.2 Constructing Lists with List Comprehensions
   4.3 Returning an Element of a List If It Exists
   4.4 Looping over Items and Their Indices in a Sequence
   4.5 Creating Lists of Lists Without Sharing References
   4.6 Flattening a Nested Sequence
   4.7 Removing or Reordering Columns in a List of Rows
   4.8 Transposing Two-Dimensional Arrays
   4.9 Getting a Value from a Dictionary
   4.10 Adding an Entry to a Dictionary
   4.11 Building a Dictionary Without Excessive Quoting
   4.12 Building a Dict from a List of Alternating Keys and Values

   4.13 Extracting a Subset of a Dictionary
   4.14 Inverting a Dictionary
   4.15 Associating Multiple Values with Each Key in a Dictionary

   4.16 Using a Dictionary to Dispatch Methods or Functions
   4.17 Finding Unions and Intersections of Dictionaries
   4.18 Collecting a Bunch of Named Items
   4.19 Assigning and Testing with One Statement
   4.20 Using printf in Python

Re: RELEASED Python 2.4.1 (final)

2005-03-30 Thread Terry Reedy
The page http://www.python.org/download/ needs to be added to the list of 
things updated with a new release.  It would, for instance, have me 
download python-2.4.msi rather than the new python-2.4.1 msi, which is a 
couple of clicks farther away.  A naive visitor would be much less likely 
to find the new file.  (I also notified [EMAIL PROTECTED]).

And yes, thanks for the new edition.

Terry J. Reedy



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


Re: AttributeError: ClassA instance has no attribute '__len__'

2005-03-30 Thread vincent wehren
"MackS" <[EMAIL PROTECTED]> schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
| I'm new to Python. In general I manage to understand what is happening
| when things go wrong. However, the small program I am writing now fails
| with the following message:
|
| AttributeError: ClassA instance has no attribute '__len__'
|
| Following the traceback,I see that the offending line is
|
| self.x = arg1 + len(self.y) + 1
|
| Why should this call to the built-in len() fail? In a small test
| program it works with no problems:
|
| class foo:
|  def __init__(self):
|self.x = 0
|self.y = 'y'
|
|  def fun(self, arg1):
|  self.x = arg1 + len(self.y) + 1
|
| >>> a = foo()
| >>> a.fun(2)
| >>>
|
| No problems; can you help me make some sense of what is happening?

In your program, self.y is an instance of ClassA. The traceback tells you 
that ClassA has no __len__ attribute (i.e.
it is an object that has no no "special" method called __len__, which is 
what gets called
when you do len(obj).

In your test program, self.y is "y", a string, which has a __len__ method by 
design:
(see dir("y"), which gives you:

['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', 
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__', 
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', 
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', 
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 
'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 
'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 
'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 
'upper', 'zfill']

If you want len(self.y) to work, self.y must be an object that implements a 
__len__ method. In other words, your "ClassA" needs a __len__ method.

A trivial example:

class ClassA:
def __init__(self, text):
   self.text = text
def __len__(self):
   #return something useful
   return len(self.text)

y = ClassA("Hello")
print len(y) # prints 5


Regards,

--
Vincent Wehren


|
| Thanks in advance
|
| Mack
| 


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


Re: urllib.urlretireve problem

2005-03-30 Thread Ritesh Raj Sarraf
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Larry Bates wrote:

> I noticed you hadn't gotten a reply.  When I execute this it put's the
> following in the retrieved file:
> 
> 
> 
> 404 Not Found
> 
> Not Found
> The requested URL /pool/updates/main/p/perl/libparl5.6_5.6.1-8.9_i386.deb
> was no t found on this server.
> 
> 
> You will probably need to use something else to first determine if the URL
> actually exists.

I'm happy that at least someone responded as this was my first post to the
python mailing list.

I'm coding a program for offline package management.
The link that I provided could be obsolete by newer packages. That is where
my problem is. I wanted to know how to raise an exception here so that
depending on the type of exception I could make my program function.

For example, for Temporary Name Resolution Failure, python raises an
exception which I've handled well. The problem lies with obsolete urls 
where no exception is raised and I end up having a 404 error page as my
data.

Can we have an exception for that ?  Or can we have the exit status of
urllib.urlretrieve to know if it downloaded the desired file.
I think my problem is fixable in urllib.urlopen, I just find
urllib.urlretrieve more convenient and want to know if it can be done with
it.

Thanks for responding.

rrs
- -- 
Ritesh Raj Sarraf
RESEARCHUT -- http://www.researchut.com
Gnupg Key ID: 04F130BC
"Stealing logic from one person is plagiarism, stealing from many is
research".
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.5 (GNU/Linux)

iD8DBQFCSuYS4Rhi6gTxMLwRAu0FAJ9R0s4TyB7zHcvDFTflOp2joVkErQCfU4vG
8U0Ah5WTdTQHKRkmPsZsHdE=
=OMub
-END PGP SIGNATURE-

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


Re: checking if program is installing using python

2005-03-30 Thread Trent Mick
[EMAIL PROTECTED] wrote]
> does this help?
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52224

There is the "which" module that I wrote that does this a little more
robustly:
http://starship.python.net/~tmick/#which

However, I didn't see the original posting for this thread so I'm not
sure if this is what is being looked for.

Cheers,
Trent

-- 
Trent Mick
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using something other than ';' to separate statements

2005-03-30 Thread Peter Hansen
Jaime Wyant wrote:
Well, I'm embedding python in an old C console app.  This app uses a
lot of ; delimited records.
I want to allow the execution of arbitrary python statements inside
some of these records.  I was hoping there was an easy way to set the
statement terminator.  I will simply make up a new terminator and do
some string substitution to turn my new terminator into python's ';'.
You refer to it here as a statement terminator, but in
the first posting you called it a statement separator.
I believe it is just a separator, not a terminator, and
as such is not even required unless you need/want to have
two statements on the same line.
In all the tens of thousands of lines of Python code
I've written, I don't believe I've ever used a single
semicolon to separate two statements.
Perhaps you don't need them either...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesting methods with similar names

2005-03-30 Thread bearophileHUGS
Raymond Hettinger>When you're done, consider posting the result as an
ASPN cookbook recipe.<

I still cannot write in the cookbook... I think I have problems with
the registration. So you can put it there...
I've found that difflib is good enough for the string matching. This
idea isn't fully mine, it's modified from the Mathematica textual
interface. Here is the code with long lines:

| def __getattr__(self, name):
| "If a wrong method is called, suggest methods with similar
names."
| def match(str1, str2):
| "Return approximate string comparator measure (between 0.0
and 1.0) using difflib."
| if str1 == str2:
| return 1.0
| m1 = SequenceMatcher(None, str1, str2)
| m2 = SequenceMatcher(None, str2, str1)
| return (m1.ratio()+m2.ratio()) / 2.0 # average
|
| toRemove = """__delattr__ __dict__ __getattribute__ __module__
__new__ __reduce__ __copy__
|__reduce_ex__ __setattr__ __slot__ __weakref__ __str__
__class__ __doc__""".split()
| methods = set(dir(self.__class__)).difference(toRemove)
| name = name.lower()
| matchList = [ (match(name, m.lower()),m) for m in methods ]
| suggestions = sorted(matchList, reverse=True)[:5] # A heap isn't
necessary here
| suggestions = ", ".join( pair[1] for pair in suggestions )
| raise AttributeError, ("method '%s' not found. \nMost similar
named ones: %s" % (name, suggestions))

Note: the general idea of a smart help can be improved a *lot*, this is
the basic version :-]

Bear hugs,
Bearophile

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


Re: checking if program is installing using python

2005-03-30 Thread [EMAIL PROTECTED]
does this help?
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52224

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


Re: AttributeError: ClassA instance has no attribute '__len__'

2005-03-30 Thread Michael Spencer
MackS wrote:
I'm new to Python. In general I manage to understand what is happening
when things go wrong. However, the small program I am writing now fails
with the following message:
In general you are more likely to get helpful responses from this group if you 
post the actual code that has the problem and include the actual traceback. 
However...

AttributeError: ClassA instance has no attribute '__len__'
Following the traceback,I see that the offending line is
self.x = arg1 + len(self.y) + 1
len calls the object's __len__ method.  self.y is bound to something (an 
instance of ClassA) that apparently has no __len__ method

Why should this call to the built-in len() fail? In a small test
program it works with no problems:
class foo:
  def __init__(self):
self.x = 0
self.y = 'y'
  def fun(self, arg1):
  self.x = arg1 + len(self.y) + 1

a = foo()
a.fun(2)

In this case self.y is bound to something different i.e., 'y' :an object of type 
str, which has a __len__ method:
 >>> 'y'.__len__()
 1

Michael

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


Re: list-comprehension and map question (simple)

2005-03-30 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
runsun pan <[EMAIL PROTECTED]> wrote:
.
.
.
>Secondly, [x+y for x,y in itertools.izip(xs, ys)] did go much faster
>than map(lambda x,y: x+y, xs, ys). The latter is not only the slowest
>one, but with an amazingly slow speed of 15 times slowdown.
>

If I understand the story correctly, this reflects Raymond Hettinger's
extraordinary achievement in making all things iter* really, really
quick.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyParsing module or HTMLParser

2005-03-30 Thread Paul McGuire
Lad -

Well, here's what I've got so far.  I'll leave the extraction of the
description to you as an exercise, but as a clue, it looks like it is
delimited by "View Detail " at
the beginning, and "Quantity: 500" at the end, where 500 could be
any number.  This program will print out:

['Title:', 'Sell 2.4GHz Wireless Mini Color Camera With Audio Function
Manufacturers Hong Kong - Exporters, Suppliers, Factories, Seller']
['Contact:', 'Mr. Simon Cheung']
['Company:', 'Lanjin Electronics Co., Ltd.']
['Address:', 'Rm 602, 6/F., Tung Ning Bldg., 2 Hillier Street, Sheung
Wan , Hong Kong\n, HK\n( Hong Kong
)']
['Phone:', '85235763877']
['Fax:', '85231056238']
['Mobile:', '852-96439737']

So I think pyparsing will get you pretty far along the way.  Code
attached below (unfortunately, I am posting thru Google Groups, which
strips leading whitespace, so I have inserted '.'s to preserve code
indentation; just strip the leading '.' characters).

-- Paul

===
from pyparsing import *
import urllib

# get input data
url = "http://www.ourglobalmarket.com/Test.htm";
page = urllib.urlopen( url )
pageHTML = page.read()
page.close()

#~ I would like to extract the tittle ( it is below Lanjin Electronics
#~ Co., Ltd. )
#~ (Sell 2.4GHz Wireless Mini Color Camera With Audio Function )

#~ description - below the tittle next to the picture
#~ Contact person
#~ Company name
#~ Address
#~ fax
#~ phone
#~ Website Address

LANGBRK = Literal("<")
RANGBRK = Literal(">")
SLASH = Literal("/")
tagAttr = Word(alphanums) + "=" + dblQuotedString

# helpers for defining HTML tag expressions
def startTag( tagname ):
return ( LANGBRK + CaselessLiteral(tagname) + \
...ZeroOrMore(tagAttr) + RANGBRK ).suppress()
def endTag( tagname ):
return ( LANGBRK + SLASH + CaselessLiteral(tagname) + RANGBRK
).suppress()
def makeHTMLtags( tagname ):
return startTag(tagname), endTag(tagname)
def strong( expr ):
return strongStartTag + expr + strongEndTag

strongStartTag, strongEndTag = makeHTMLtags("strong")
titleStart, titleEnd = makeHTMLtags("title")
tdStart, tdEnd = makeHTMLtags("td")
h1Start, h1End = makeHTMLtags("h1")

title = titleStart + SkipTo( titleEnd ).setResultsName("title") +
titleEnd
contactPerson = tdStart + h1Start + \
...SkipTo( h1End ).setResultsName("contact")
company   = ( tdStart + strong("Company:") + tdEnd + tdStart ) + \
...SkipTo( tdEnd ).setResultsName("company")
address   = ( tdStart + strong("Address:") + tdEnd + tdStart ) + \
...SkipTo( tdEnd ).setResultsName("address")
phoneNum  = ( tdStart + strong("Phone:") + tdEnd + tdStart ) + \
...SkipTo( tdEnd ).setResultsName("phoneNum")
faxNum= ( tdStart + strong("Fax:";) + tdEnd + tdStart ) + \
...SkipTo( tdEnd ).setResultsName("faxNum")
mobileNum = ( tdStart + strong("Mobile:") + tdEnd + tdStart ) + \
...SkipTo( tdEnd ).setResultsName("mobileNum")
webSite   = ( tdStart + strong("Website Address:") + tdEnd + tdStart )
+ \
...SkipTo( tdEnd ).setResultsName("webSite")
scrapes = title | contactPerson | company | address | phoneNum | faxNum
| mobileNum | webSite

# use parse actions to remove hyperlinks
linkStart, linkEnd = makeHTMLtags("a")
linkExpr = linkStart + SkipTo( linkEnd ) + linkEnd
def stripHyperLink(s,l,t):
return [ t[0], linkExpr.transformString( t[1] ) ]
company.setParseAction( stripHyperLink )

# use parse actions to add labels for data elements that don't
# have labels in the HTML
def prependLabel(pre):
def prependAction(s,l,t):
return [pre] + t[:]
return prependAction
title.setParseAction( prependLabel("Title:") )
contactPerson.setParseAction( prependLabel("Contact:") )

for tokens,start,end in scrapes.scanString( pageHTML ):
print tokens

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


Re: CGI, FieldStorage and Filename

2005-03-30 Thread Neil Benn
Neil Benn wrote:
Hello,
 I'm writing a simple cgi script and want to be able to access 
the filename in a FieldStorage file instance.  I have successfully 
manmaged to access the file as a 'file-like object' by using the 
simple code of :


Sorry, split the filename on path not pathext..
have a nice day if you are in a different time zone than me!
Cheers,
Neil
--
Neil Benn
Senior Automation Engineer
Cenix BioScience
BioInnovations Zentrum
Tatzberg 46
D-01307
Dresden
Germany
Tel : +49 (0)351 4173 154
e-mail : [EMAIL PROTECTED]
Cenix Website : http://www.cenix-bioscience.com
--
http://mail.python.org/mailman/listinfo/python-list


AttributeError: ClassA instance has no attribute '__len__'

2005-03-30 Thread MackS
I'm new to Python. In general I manage to understand what is happening
when things go wrong. However, the small program I am writing now fails
with the following message:

AttributeError: ClassA instance has no attribute '__len__'

Following the traceback,I see that the offending line is

self.x = arg1 + len(self.y) + 1

Why should this call to the built-in len() fail? In a small test
program it works with no problems:

class foo:
  def __init__(self):
self.x = 0
self.y = 'y'

  def fun(self, arg1):
  self.x = arg1 + len(self.y) + 1

>>> a = foo()
>>> a.fun(2)
>>>

No problems; can you help me make some sense of what is happening?

Thanks in advance

Mack

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


CGI, FieldStorage and Filename

2005-03-30 Thread Neil Benn
Hello,
 I'm writing a simple cgi script and want to be able to access 
the filename in a FieldStorage file instance.  I have successfully 
manmaged to access the file as a 'file-like object' by using the simple 
code of :

objInFile = objForm['DataFile'].file
   I can easily read through this data and get all the information out 
as I need - sorted!!  However, when I attempt to access the filename 
attribute of this using :

print 'Content-Disposition: attachment; filename="' + 
os.path.split(objForm['DataFile'].filename)[0] + '_reformatted.txt"'

   I get None back for the filename.  So I dumped the content of the 
objForm['DataFile'] to stdout to see what it contains :

print objForm['DataFile']
I got back this :
FieldStorage('DataFile', 'MOAF_10-12_fin_2.txt', 
'Project\tJob\tBarcode\tPlate set )

   As you can see, when __str__ is called, the FieldStorage is 
displaying the name of the client side file - so it knows what it is, 
however when I call .filename on it, I get None.  I don;t get what is 
happening here - has anyone else seen this and/or knows what I'm doing 
wrong?

   If so then all and any help would be much appreciated.
Cheers,
Neil
--
Neil Benn
Senior Automation Engineer
Cenix BioScience
BioInnovations Zentrum
Tatzberg 46
D-01307
Dresden
Germany
Tel : +49 (0)351 4173 154
e-mail : [EMAIL PROTECTED]
Cenix Website : http://www.cenix-bioscience.com
--
http://mail.python.org/mailman/listinfo/python-list


checking if program is installing using python

2005-03-30 Thread GujuBoy
i want to check to see if a certain program is installed on my windows
box using python. how can i do that...(ie, i want to see if "word" is
installed)

please help

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


Re: Write an hexadecimal file

2005-03-30 Thread rbt
Larry Bates wrote:
There is not such thing as a hexadecimal file.
Right, 300 is 300 whether you choose to represent it in decimal, binary, 
hex, etc... it's still only 300 of something ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: return the last item in a list

2005-03-30 Thread Raymond Hettinger
[David Bear]
> I'm looking for an 'easy' way to have the last item in a list returned.

Try mylist.pop() or mylist[-1].


Raymond Hettinger


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


Re: author index for Python Cookbook 2?

2005-03-30 Thread Raymond Hettinger
[Fuzzyman]
> Three of my recipes are in - but one has been merged with someone elses
> and improved beyond all recognition :-)

Gets my vote for QOTW quote of the week.

The comment captures the spirit of the cookbook and highlights the benefits of
the process (public review, reader comments, competing recipes, and Alex/Anna's
editing).  The cookbook is its own microcosm of open source.


Raymond Hettinger



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


Re: Grouping code by indentation - feature or ******?

2005-03-30 Thread Javier Bezos
"Myles Strous" <[EMAIL PROTECTED]> escribió en el mensaje
news:[EMAIL PROTECTED]
>>> satisfy some handy properties, the first of which being:
>>>   l[:n] + l[n:] = l
>>
>> I don't think l[:5] + l[5:] = l is a handy property
>> and to me is clearly counterintuitive. Further,
>
> It can be quite useful for inserting something into a list (or string),
> after finding the position where you wish to insert it.
> improvedList = l[:n] + [new stuff] + l[n:]

As I answered in another post this is not more
useful than writing l[:n-1]. Of course, I'm aware
of the case where n=0, but this would require only
a bit of extra code (and, after all, I'm just saying
that half-open ranges are not a panacea and that I
don't like their side effects).

> I vaguely remember hearing at one stage that the
> sequence[position:position+length] notation is also potentially useful
> for indexing into large strings or buffers.

Right, to some extent it's useful, but at the cost
of introducing tricky syntaxes for very specific
cases, like this one, and unexpected off-by-one
errors in other cases, which is my point. For
example, recently I had to get a value from a
list preceded by the two previous values:
lst[n-2:n+1] and not the more logical (at last
to my eyes) lst[n-2:n].

Instead of giving further examples I would like
to cite three cases:

1) You have a starting point (s) and a
   length (t): lst[s:s+t].
2) You have an ending point (e) and a
   length: lst[e-t+1:e+1].
3) You have a starting point and an ending
   point: lst[s:e+1].

What's odd is that Python applies the syntax of
case 3 to the logic of case 1. While something
like lst[s:s+t-1] for the first case could be
explained in simple mathematical terms (in other
words, it's an integral part of the algorithms),
I cannot find a way to explain the e+1 in cases
2 and 3 (and the inconsistency with e-t+1 in case
2 vs. s+t in case 1) except the Python syntax.

Javier
___
Javier Bezos | Mem. A multilingual system for LaTeX
jbezos at wanadoo dot es | http://mem-latex.sourceforge.net
.|




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


Re: [DB-SIG] Looking for Stephen Turner, maintainer of informixdb

2005-03-30 Thread Eric Brunson
Read the license.  If he's released it under GPL or BSD, then you could, 
in all good faith, release a fork of the code until he surfaces.

Carsten Haese wrote:
Hello everybody:
I have discovered that the functionality for connecting Python to an
Informix database is currently in a frustrating state of neglect. The
link to Kinfxdb is dead, and informixdb doesn't build on Python 2. I
couldn't find any usable workarounds to the build problem, so I worked
out successfully how to build informixdb using distutils.
Now I'd like to share the result with the community, but the maintainer
appears to have gone missing. My emails to [EMAIL PROTECTED] and
[EMAIL PROTECTED] have bounced back undeliverable, so now I'm
posting to the lists trying to locate Stephen.
If anybody has any pointers for locating Stephen Turner, please let me
know. If Stephen can't be located, I'd be willing to take over the
project, but I'd prefer the torch be given to me rather than me just
taking it.
Thanks,
 

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


Re: Suggesting methods with similar names

2005-03-30 Thread Raymond Hettinger
[Bearophile]
> Working in the interactive window I receive an error like
> this when I write the wrong method name:
>
> >>> table.addGlas()
> Traceback (most recent call last):
>   File "", line 1, in ?
> AttributeError: 'Surface' object has no attribute 'addGlas'
>
> Is it possibile to make the object give a better answer: a short list
> of few method names similar to the one I've misspelled?

[Bearophile]
> Thank you, __getattr__ does what I need :-)
> A smart help can be designed easely...

The idea is a winner.  When you're done, consider posting the result as an ASPN
cookbook recipe.


Raymond Hettinger


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


Re: return the last item in a list

2005-03-30 Thread TZOTZIOY
On 30 Mar 2005 10:48:17 -0700, rumours say that David Bear
<[EMAIL PROTECTED]> might have written:

>I've googled for the above and get way too many hits.. 
>
>I'm looking for an 'easy' way to have the last item in a list returned.
>
>I've thought about
>
>list[len(list)-1]
>
>but thought there would be a more gracefull way.

There is.

alist[-1]

Did you read the tutorial?  This is referenced in "3. An Informal
Introduction to Python".
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


return the last item in a list

2005-03-30 Thread David Bear

I've googled for the above and get way too many hits.. 

I'm looking for an 'easy' way to have the last item in a list returned.

I've thought about

list[len(list)-1]

but thought there would be a more gracefull way.

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


Re: Write an hexadecimal file

2005-03-30 Thread Raymond Hettinger
[Cesar Andres Roldan Garcia]
> I'm trying to write an hexadecimal file... I mean not a text plain...
>I have to convert a float decimal number in float hexadecimal one,
> and that's done.

The struct module provides a portable way to convert a float to and from a
sequence of bytes.

The binascii modules provides tools for converting a sequence of bytes to and
from a representation as a hex string.

>>> import struct, binascii
>>> binascii.hexlify(struct.pack('>f', 3.1415926535))
'40490fdb'
>>> struct.unpack('>f', binascii.unhexlify(_))[0]
3.1415927410125732

Writing to a file is accomplished with the open() function and the file.write()
method:

f = open('mydata.hex', 'w')
f.write('40490fdb')
f.close()



Raymond Hettinger


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


Dr. Dobb's Python-URL! - weekly Python news and links (Mar 30)

2005-03-30 Thread Cameron Laird

QOTW:  "This is a Python newsgroup. Assume that we all have been
brainwashed." -- Peter Otten

"[M]y experience porting Java to Jython is that it mostly involves deleting
stuff :-)" -- Kent Johnson

"[K]eep in mind, however, that not all problems in life can be solved with 
software." -- Roy Smith


The Second Edition (of the *Cookbook*) hits the shelves!
http://www.oreilly.com/catalog/pythoncook2/

Most of the week's news had to do with PyCon2005:
http://python.org/moin/PyConDC2005

http://programming.newsforge.com/programming/05/03/29/0747230.shtml?tid=108&tid=18
http://oreillynet.com/pub/wlg/6767  
http://planetpython.org/
Notice that plenty of other PyEvents, including PyConDayBrasil
in particular, are imminent:
http://python.org/moin/PythonEvents#preview

A Microsoft magazine publishes two favorable profiles of Python:
http://www.devsource.com/article2/0,1759,1778141,00.asp
http://www.devsource.com/article2/0,1759,1778250,00.asp

How does a Linux-hosted Tkinter set its window icon?  Jeff Epler
knows:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/95a5c57c829699d2/

Roy Smith and Larry Bates, among others, cogently counsel
would-be language autodidacts:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/359d8bc917d8dd0a/

Ivan Van Laningham addresses the off-topic matter of /bin/ls's
performance with such precision as to illuminate Python use, 
particularly in its evocation of earlier threads:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9a8586f0ac49c8ca/

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d6524ee021fc946f/

Raymond Hettinger, so wise in the ways of iteration, also knows
his way around the syntax of decimal numerals:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a7b8b5de4c355d56



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Brett Cannon continues the marvelous tradition established by 
Andrew Kuchling and Michael Hudson of intelligently summarizing
action on the python-dev mailing list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/   

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

The Python Business Forum "further[s] the interests of companies
that base their business on ... Python."
http://www.python-in-business.org

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance. 
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch
   
Cetus collects Python hyperlinks.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a 

  1   2   >