Re: Scanning a file

2005-10-31 Thread Lasse Vågsæther Karlsen
David Rasmussen wrote:
snip
 If you must know, the above one-liner actually counts the number of 
 frames in an MPEG2 file. I want to know this number for a number of 
 files for various reasons. I don't want it to take forever.
snip

Don't you risk getting more frames than the file actually have? What 
if the encoded data happens to have the magic byte values for something 
else?

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Expanding Python as a macro language

2005-10-31 Thread qwweeeit
I am further commenting on new replies.

Mike Meyer wrote:
 In general, application scripting facilities are one thing that Unix
 hasn't dealt with well.
 ...so each application is left up to it's own devices.
 Some of them now export APIs that can be hooked up to a variety of
 languages.

Now I understand why I have found so many difficulties!...
An example of APIs is those available for better controlling Google
search engine.

Unfortunately all that leaves the need of specific programming for
each case... I am obliged to learn C++ and Qt (in particular
inter-process communication).

About SPE, he is a little beside the point, but I insisted so much on
web examples...

Alex Martelli wrote:
 General purpose is, I believe, an overbid here --

Perhaps you are right, but for me a macro language
(like for ex. AutoIt) is very general, being only a mean of emulating
the user, running automatically external applications.

 applications are able to detect as being simulated, if they
 want to implement very strong security.
 If you want security, don't complain about the existence of security.

Never complained... I was only favorably impressed by the
sophistication reached for assuring stronger security.

At last a new entry (has) completely off the point (FWIW  FICCL!...).

Bye.

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


Re: Would there be support for a more general cmp/__cmp__

2005-10-31 Thread Antoon Pardon
Op 2005-10-28, Ron Adam schreef [EMAIL PROTECTED]:

 I haven't heard he was removing __cmp__,

I read somewhere he was considering it.

 but I would think the sort or 
 sorted functions would just use the available comparisons methods or 
 equivalent C code for base types.  So I expect it would only matter if 
 you need a custom or modified sort.

 Although It is a thought that these cases could be improved by making 
 the sort value available to the underlying C sort function.  Something 
 on the order of:

  __sortvalue__ == self.value.

I doubt that will be possible in general. You can't even calculate such
a __sortvalue__ for lists.

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


Why the nonsense number appears?

2005-10-31 Thread Johnny Lee
Hi,
   Pls take a look at this code:

--
 t1 = 1130748744
 t2 = 461
 t3 = 1130748744
 t4 = 500
 time1 = t1+.+t2
 time2 = t3+.+t4
 print time1, time2
1130748744.461 1130748744.500
 float(time2) - float(time1)
0.03934332275391


   Why are there so many nonsense tails? thanks for your help.

Regards, 
Johnny

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


meschach + Python

2005-10-31 Thread Cyril Bazin
Hello,

I need to compute eigenvalues and eigenvectors on sparse matrix.
I found a C library meschach which seems to do the work. 
Unfortunatly, this libray doesn't seem to be interfaced in Python.

Has anyone ever used this library and interfaced it in Python or has a solution
to compute eigenvalues and eigenvalues on sparse matrix efficiently in Python?

Thanks in advance,

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

Re: Why the nonsense number appears?

2005-10-31 Thread Sybren Stuvel
Johnny Lee enlightened us with:
 Why are there so many nonsense tails? thanks for your help.

Because if the same reason you can't write 1/3 in decimal:

http://docs.python.org/tut/node16.html

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


Re: Why the nonsense number appears?

2005-10-31 Thread Daniel Dittmar
Johnny Lee wrote:
print time1, time2
 
 1130748744.461 1130748744.500
 
float(time2) - float(time1)
 
 0.03934332275391
 
 
Why are there so many nonsense tails? thanks for your help.

http://en.wikipedia.org/wiki/Floating_point#Problems_with_floating-point, 
especially 'Rounding'. Or google for gloating point precision if you 
need more details.

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


Re: Why the nonsense number appears?

2005-10-31 Thread Ben O'Steen
On Mon, October 31, 2005 9:39, Sybren Stuvel said:
 Johnny Lee enlightened us with:
 Why are there so many nonsense tails? thanks for your help.

 Because if the same reason you can't write 1/3 in decimal:

 http://docs.python.org/tut/node16.html

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



I think that the previous poster was asking something different. I think
he was asking something like this:

If

 t1 = 0.500
 t2 = 0.461
 print t1-t2
0.039

Then why:

 t1 += 12345678910
 t2 += 12345678910
 # Note, both t1 and t2 have been incremented by the same amount.
 print t1-t2
0.0389995574951

It appears Yu-Xi Lim beat me to the punch. Using decimal as opposed to
float sorts out this error as floats are not built to handle the size of
number used here.

Ben

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


tachometer diagram

2005-10-31 Thread Andreas Kaiser
Hello,

I'am searching for a python solution for display a tachometer diagram.
I prefer a solution for wxPython.
The plot libraries I've found do not implement this diagram type.
Any hints welcome!

Thanks
Andreas

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


Re: tachometer diagram

2005-10-31 Thread Jorge Godoy
Andreas Kaiser [EMAIL PROTECTED] writes:

 I'am searching for a python solution for display a tachometer diagram.
 I prefer a solution for wxPython.
 The plot libraries I've found do not implement this diagram type.
 Any hints welcome!

In case you change your mind, I believe there's such a thing in Qt3.  Using
pyQt you could use that.

-- 
Jorge Godoy  [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why the nonsense number appears?

2005-10-31 Thread Yu-Xi Lim
Johnny Lee wrote:
snip
Why are there so many nonsense tails? thanks for your help.

I guess you were expecting 0.039? You first need to understand floating 
point numbers:

http://docs.python.org/tut/node16.html

What you see are the effects of representation errors.

The solution is presented here:
http://www.python.org/peps/pep-0327.html

But briefly, it means your code should read:

from decimal import *
t1 = 1130748744
t2 = 461
t3 = 1130748744
t4 = 500
time1 = t1+.+t2
time2 = t3+.+t4
print time1, time2
Decimal(time2) - Decimal(time1)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tachometer diagram

2005-10-31 Thread Andreas Kaiser
Hello Jorge,

I can change my mind, sorry. The target OS for this app is Win. When
pyQt4 is available, I will check QT.

Andreas

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


Re: Scanning a file

2005-10-31 Thread Steven D'Aprano
David Rasmussen wrote:

 Steven D'Aprano wrote:
 
 On Fri, 28 Oct 2005 06:22:11 -0700, [EMAIL PROTECTED] wrote:

 Which is quite fast. The only problems is that the file might be huge.


 What *you* call huge and what *Python* calls huge may be very different
 indeed. What are you calling huge?

 
 I'm not saying that it is too big for Python. I am saying that it is too 
 big for the systems it is going to run on. These files can be 22 MB or 5 
 GB or ..., depending on the situation. It might not be okay to run a 
 tool that claims that much memory, even if it is available.

If your files can reach multiple gigabytes, you will 
definitely need an algorithm that avoids reading the 
entire file into memory at once.


[snip]

 print file(filename, rb).count(\x00\x00\x01\x00)
 
 (or something like that)
 
 instead of the original
 
 print file(filename, rb).read().count(\x00\x00\x01\x00)
 
 it would be exactly what I am after. 

I think I can say, without risk of contradiction, that 
there is no built-in method to do that.


  What is the conceptual difference?
 The first solution should be at least as fast as the second. I have to 
 read and compare the characters anyway. I just don't need to store them 
 in a string. In essence, I should be able to use the count occurences 
 functionality on more things, such as a file, or even better, a file 
 read through a buffer with a size specified by me.

Of course, if you feel like coding the algorithm and 
submitting it to be included in the next release of 
Python... :-)


I can't help feeling that a generator with a buffer is 
the way to go, but I just can't *quite* deal with the 
case where the pattern overlaps the boundary... it is 
very annoying.

But not half as annoying as it must be to you :-)

However, there may be a simpler solution *fingers 
crossed* -- you are searching for a sub-string 
\x00\x00\x01\x00, which is hex 0x100. Surely you 
don't want any old substring of \x00\x00\x01\x00, but 
only the ones which align on word boundaries?

So ABCD\x00\x00\x01\x00 would match (in hex, it is 
0x41424344 0x100), but AB\x00\x00\x01\x00CD should 
not, because that is 0x4142 0x1004344 in hex.

If that is the case, your problem is simpler: you don't 
have to worry about the pattern crossing a boundary, so 
long as your buffer is a multiple of four bytes.



-- 
Steven.

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


Re: tachometer diagram

2005-10-31 Thread Andreas Kaiser
 I can change my mind, sorry.
Should be: I _can't_ change ...

Andreas

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


Re: Why the nonsense number appears?

2005-10-31 Thread Sybren Stuvel
Ben O'Steen enlightened us with:
 I think that the previous poster was asking something different.

It all boils down to floating point inprecision.

 If

 t1 = 0.500
 t2 = 0.461
 print t1-t2
 0.039

 Then why:

 t1 += 12345678910
 t2 += 12345678910
 # Note, both t1 and t2 have been incremented by the same amount.
 print t1-t2
 0.0389995574951

It's easier to explain in decimals. Just assume you only have memory
to keep three decimals.  12345678910.500 is internally stored as
something like 1.23456789105e10. Strip that to three decimals, and you
have 1.234e10. In that case, t1 - t2 = 1.234e10 - 1.234e10 = 0.

 Using decimal as opposed to float sorts out this error as floats are
 not built to handle the size of number used here.

They can handle the size just fine. What they can't handle is 1/1000th
precision when using numbers in the order of 1e10.

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


Re: Problem With Insert with MySQLdb

2005-10-31 Thread Sibylle Koczian
Gerhard Häring schrieb:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1
 
 David Mitchell wrote:
 
Hello,

I am a complete beginner with Python. I've managed to get mod_python up and
running with Apache2 and I'm trying to a simple insert into a table in a
MySQL database. 

I'm using the MySQLdb library for connectivity. I can read from the database
no problem, but when I do an insert, the value never gets added to the
database, even though there is no error, and the SQL is fine (I print out
the SQL statement in the function). When I copy and paste the sql from my
browser and insert directly into MySQL, it works fine.
[...] Am I doing something obviously incorrect here?
 
 
 It appears you forgot to call .commit() on the connection to commit your
 transaction. From what you tell, it also looks like the MySQL
 commandline tool defaults to autocommit (i. e. each statement is wrapped
 in an implicit BEGIN ... COMMIT.
 
 If you have no idea what a transaction is or what the heck the BEGIN,
 COMMIT or ROLLBACK commands are for (corresponding to .commit() and
 .rollback() methods of the DB-API2 connection object, BEGIN is issued
 implicitly), then the MySQL documentation will probably answer that.
 

What sort of table do you use? MyISAM isn't transaction oriented, and 
that's the standard. So that most probably isn't the problem.

-- 
Dr. Sibylle Koczian
Universitaetsbibliothek, Abt. Naturwiss.
D-86135 Augsburg
e-mail : [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why the nonsense number appears?

2005-10-31 Thread Ben O'Steen
On Mon, October 31, 2005 10:23, Sybren Stuvel said:
 Ben O'Steen enlightened us with:
 Using decimal as opposed to float sorts out this error as floats are
 not built to handle the size of number used here.

 They can handle the size just fine. What they can't handle is 1/1000th
 precision when using numbers in the order of 1e10.


I used the word 'size' here incorrectly, I intended to mean 'length'
rather than numerical value. Sorry for the confusion :)



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



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


data hiding/namespace pollution

2005-10-31 Thread Alex Hunsley
There's no really specific questions in this post, but I'm looking for 
people's thought on the issues within...


The two main versions I've encountered for data pseudo-hiding 
(encapsulation) in python are:

method 1:

_X  - (single underscore) - just cosmetic, a convention to let someone
   know that this data should be private.


method 2:

__X - (double underscore) - mangles the name (in a predictable way).
   Avoids name pollution.


How often does either tend to get used? Personally, I'd be a little 
worried about using method 1, because namespace clashes could happen. Is 
this overly paranoid?

Also, I presume that rather than people writing their own manual getter 
and setter methods, they tend to use either overloading on __getattr__ 
and __setattr__, or the Property class (which itself uses aforementioned 
  methods). Overloading __getattr__ etc. seems more attractive to me, as 
then I can capture access to unknown names, and raise an exception!
(I really don't like the idea of random attribute name typos going 
unnoticed when accessing attributes in a class!)

Note: I do know that the use of the above things is quite dependent on 
what exactly you're coding, the size of the project etc., but what I'm 
trying to find out about is the python communities' recognised good 
practices.

thanks,
alex

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


mixin helper class for unknown attribute access?

2005-10-31 Thread Alex Hunsley
I know that I can catch access to unknown attributes with code something 
like the following:

class example:
  def __getattr__(self, name):
  if name == 'age':
  return __age
  else:
  raise AttributeError


but is there an existing mixin helper class in Python (or one someone 
has written) already that will assist with this? (Just not wanting to 
reinvent the wheel)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tachometer diagram

2005-10-31 Thread Jorge Godoy
Andreas Kaiser [EMAIL PROTECTED] writes:

 I can change my mind, sorry. The target OS for this app is Win. When
 pyQt4 is available, I will check QT.

Dunnon the licensing, but there's a Qt3 GPL available for Win...  It is not
official, but it runs :-)  You'd have to Google for it, though, since I don't
have the URL for it anymore.

-- 
Jorge Godoy  [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: process and spinning slash

2005-10-31 Thread benz
I have rewrited my code as follow, but it still not working.

import os, sys


pid = os.fork()

if pid == 0:
  os.execvp(du,(du,-shc,/usr/share))
else:
  while 1:
try:
  os.kill(pid,0)
  sys.stdout.write('running')
  sys.stdout.flush()
  sys.stdout.write('\b\b\b\b\b\b\b')
except OSError:
  print child ended

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


Re: data hiding/namespace pollution

2005-10-31 Thread bruno at modulix
Alex Hunsley wrote:
 There's no really specific questions in this post, but I'm looking for
 people's thought on the issues within...
 
 
 The two main versions I've encountered for data pseudo-hiding
 (encapsulation) 

OT
Hmmm... Are data-hiding and encapsulation really the same things ?
/OT

 in python are:
 
 method 1:
 
 _X  - (single underscore) - just cosmetic, a convention to let someone
   know that this data should be private.
 
 
 method 2:
 
 __X - (double underscore) - mangles the name (in a predictable way).
   Avoids name pollution.
 
 
 How often does either tend to get used? Personally, I'd be a little
 worried about using method 1, because namespace clashes could happen. Is
 this overly paranoid?

Probably.

Note that prefixing names with a single underscore have a 'protected'
semantic - which means that such names (well, the objects that are bound
to...) can be overriden/extends by child classes.

I personnally only use the double-underscore notation only for things
that are *really* implementation-specific *and* should *really not* be
overriden.

 
 Also, I presume that rather than people writing their own manual getter
 and setter methods, they tend to use either overloading on __getattr__
 and __setattr__, or the Property class (which itself uses aforementioned
  methods). 

Yeps... This is the pythonic way.

 Overloading __getattr__ etc. seems more attractive to me, as
 then I can capture access to unknown names, and raise an exception!
 (I really don't like the idea of random attribute name typos going
 unnoticed when accessing attributes in a class!)

Err... Have you *really* tried to access an inexistant attribute ?  This
is usually not 'unnoticed' (unless you consider the raising of an
AttributeError as being the same as 'unnoticed' !-)

I personnaly use 'magic' accessors only for delegation or like, and
properties (or custom descriptors) for anything else (that requires
it...). This avoid the Big-Switch-Syndrom in __getattr__ and setattr__,
and is much more explicit (API, documentation, introspection etc...).

 Note: I do know that the use of the above things is quite dependent on
 what exactly you're coding, the size of the project etc., but what I'm
 trying to find out about is the python communities' recognised good
 practices.

Then launch your python interactive shell and type import this

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


Re: data hiding/namespace pollution

2005-10-31 Thread Alex Hunsley
bruno at modulix wrote:
 Alex Hunsley wrote:
 
There's no really specific questions in this post, but I'm looking for
people's thought on the issues within...


The two main versions I've encountered for data pseudo-hiding
(encapsulation) 
 
 
 OT
 Hmmm... Are data-hiding and encapsulation really the same things ?
 /OT

No, they're not, I was just being careless there, please disregard any 
apparent implication that they are.

in python are:

method 1:

_X  - (single underscore) - just cosmetic, a convention to let someone
  know that this data should be private.


method 2:

__X - (double underscore) - mangles the name (in a predictable way).
  Avoids name pollution.


How often does either tend to get used? Personally, I'd be a little
worried about using method 1, because namespace clashes could happen. Is
this overly paranoid?
 
 
 Probably.
 
 Note that prefixing names with a single underscore have a 'protected'
 semantic - which means that such names (well, the objects that are bound
 to...) can be overriden/extends by child classes.

Ah, my mistake, not merely cosmetic then! Thanks.

 
 I personnally only use the double-underscore notation only for things
 that are *really* implementation-specific *and* should *really not* be
 overriden.

ok.

Also, I presume that rather than people writing their own manual getter
and setter methods, they tend to use either overloading on __getattr__
and __setattr__, or the Property class (which itself uses aforementioned
 methods). 
 
 
 Yeps... This is the pythonic way.
 
 
Overloading __getattr__ etc. seems more attractive to me, as
then I can capture access to unknown names, and raise an exception!
(I really don't like the idea of random attribute name typos going
unnoticed when accessing attributes in a class!)
 
 
 Err... Have you *really* tried to access an inexistant attribute ?  This
 is usually not 'unnoticed' (unless you consider the raising of an
 AttributeError as being the same as 'unnoticed' !-)

Sorry, I wasn't being clear. What I should have said is that I don't 
like the idea of a typo in an assignment causing the assigning of the 
wrong thing.
e.g. imagine a simple value-holding class:

class Values:
pass

v = Values()

v.conductoin = 10


... I meant to type 'conduction' in the source but spelt it wrong.
My value won't be there when elsewhere I refer to the correct attribute: 
conduction.



 I personnaly use 'magic' accessors only for delegation or like, and
 properties (or custom descriptors) for anything else (that requires
 it...). This avoid the Big-Switch-Syndrom in __getattr__ and setattr__,
 and is much more explicit (API, documentation, introspection etc...).

Right, good point.

Note: I do know that the use of the above things is quite dependent on
what exactly you're coding, the size of the project etc., but what I'm
trying to find out about is the python communities' recognised good
practices.
 
 
 Then launch your python interactive shell and type import this

Thanks for that, I didn't know about that!
alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Automatically creating a HOME environ variable on Windows?

2005-10-31 Thread Maciej Dziardziel
Jorgen Grahn wrote:

 Best solution would be to have portable function that returns
 user home directory and knows about all platfom quirks.
 
 Why is that better than Python creating a HOME in os.environ, if it
 doesn't
 already exist?  I can think of a few reasons it's better, and a few
 reasons it's worse.

First, it is possible that HOME viariable already exists and has different
meaning, (if python is used as embedded scripting language it can be
defined by application), Second, there is a group of path related functions
in os.path (or ntpath), including expanduser, and its better to use
function than relay on some interpreter behaviour that may be different on
jython or ironpython.

-- 
Maciej Fiedzia Dziardziel (fiedzia (at) fiedzia (dot) prv (dot) pl)
www.fiedzia.prv.pl

How come in Scooby Doo Fred and Daphne were always on the same team and   
   Velma, Scooby and Shaggy were always on the same team? Doesn't seem quite 
   right now that you think about it, does it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: data hiding/namespace pollution

2005-10-31 Thread Jorge Godoy
Alex Hunsley [EMAIL PROTECTED] writes:

 Sorry, I wasn't being clear. What I should have said is that I don't like the
 idea of a typo in an assignment causing the assigning of the wrong thing.
 e.g. imagine a simple value-holding class:
 
 class Values:
   pass
 
 v = Values()
 
 v.conductoin = 10
 
 
 ... I meant to type 'conduction' in the source but spelt it wrong.
 My value won't be there when elsewhere I refer to the correct attribute:
 conduction.

Recently there was a big thread where that was raised again (yep, you're not
the first, nor the second, nor the third...).  You should write unittests, use
tools like pychecker, pylint, etc. 

-- 
Jorge Godoy  [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: data hiding/namespace pollution

2005-10-31 Thread Alex Hunsley
Jorge Godoy wrote:
 Alex Hunsley [EMAIL PROTECTED] writes:
 
 
Sorry, I wasn't being clear. What I should have said is that I don't like the
idea of a typo in an assignment causing the assigning of the wrong thing.
e.g. imagine a simple value-holding class:

class Values:
  pass

v = Values()

v.conductoin = 10


... I meant to type 'conduction' in the source but spelt it wrong.
My value won't be there when elsewhere I refer to the correct attribute:
conduction.
 
 
 Recently there was a big thread where that was raised again (yep, you're not
 the first, nor the second, nor the third...).  You should write unittests, use
 tools like pychecker, pylint, etc. 

Yup, I'm plannig on using pyunit. Didn't know about pychecker though, 
thanks for that!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: data hiding/namespace pollution

2005-10-31 Thread Alex Hunsley
Jorge Godoy wrote:
 Alex Hunsley [EMAIL PROTECTED] writes:
 
 
Sorry, I wasn't being clear. What I should have said is that I don't like the
idea of a typo in an assignment causing the assigning of the wrong thing.
e.g. imagine a simple value-holding class:

class Values:
  pass

v = Values()

v.conductoin = 10


... I meant to type 'conduction' in the source but spelt it wrong.
My value won't be there when elsewhere I refer to the correct attribute:
conduction.
 
 
 Recently there was a big thread where that was raised again (yep, you're not
 the first, nor the second, nor the third...).  You should write unittests, use
 tools like pychecker, pylint, etc. 

Btw, can you recall the subject line of the thread? I'd like to google 
groups for it and have a read of that thread...
ta!
alex

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


Re: data hiding/namespace pollution

2005-10-31 Thread Jorge Godoy
Alex Hunsley [EMAIL PROTECTED] writes:

 Btw, can you recall the subject line of the thread? I'd like to google groups
 for it and have a read of that thread...
 ta!

Search for: alex martelli pychecker on comp.lang.python...  I don't have the
thread's name anymore.  You'll probably find more than one thread with
that. :-)

-- 
Jorge Godoy  [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


taking x-window screen shot

2005-10-31 Thread Sinan Nalkaya
hi i have some python practice and want to develop tiny prgramme that 
takes screen shots from command line, im using gnome now but my 
programme should support the others especially pure X - window. also i 
want to learn some more about inside when taking screen shots.
thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter problem

2005-10-31 Thread dale cooper
Hi everybody!
I've recently installed python2.4.2 on Fedora 4 (from downloaded
sources), but it appeared, that I can't use Tkinter module:

 import Tkinter
Traceback (most recent call last):
  File stdin, line 1, in ?
  File /usr/local/lib/python2.4/lib-tk/Tkinter.py, line 38, in ?
import _tkinter # If this fails your Python may not be configured
for Tk
ImportError: libBLT24.so: cannot open shared object file: No such file
or directory

I tried the solution given in README file for RH9 (./configure
--enable-unicode=ucs4) despite they wrote the newer wersion didn't need
this hack. This is what I had after make instruction:

INFO: Can't locate Tcl/Tk libs and/or headers
*** WARNING: renaming array since importing it failed:
build/lib.linux-i686-2.4/array.so: undefined symbol:
PyUnicodeUCS2_FromUnicode
*** WARNING: renaming _testcapi since importing it failed:
build/lib.linux-i686-2.4/_testcapi.so: undefined symbol:
PyUnicodeUCS2_Decode
*** WARNING: renaming unicodedata since importing it failed:
build/lib.linux-i686-2.4/unicodedata.so: undefined symbol:
PyUnicodeUCS2_FromUnicode
*** WARNING: renaming _locale since importing it failed:
build/lib.linux-i686-2.4/_locale.so: undefined symbol:
PyUnicodeUCS2_AsWideChar
*** WARNING: renaming cPickle since importing it failed:
build/lib.linux-i686-2.4/cPickle.so: undefined symbol:
PyUnicodeUCS2_AsUTF8String
*** WARNING: renaming pyexpat since importing it failed:
build/lib.linux-i686-2.4/pyexpat.so: undefined symbol:
PyUnicodeUCS2_DecodeUTF8
*** WARNING: renaming _multibytecodec since importing it failed:
build/lib.linux-i686-2.4/_multibytecodec.so: undefined symbol:
PyUnicodeUCS2_FromUnicode
running build_scripts

It seems that --enable-unicode=ucs4 wasn't the right way. I tried
another hack: ./configure --enable-shared, but it still couldn't locate
Tcl/Tk libs and/or headers. Then I installed RPMs:

[EMAIL PROTECTED] Python-2.4.2]# rpm -q tk
tk-8.4.9-3
[EMAIL PROTECTED] Python-2.4.2]# rpm -q tcl
tcl-8.4.9-3
[EMAIL PROTECTED] Python-2.4.2]# rpm -q tkinter
tkinter-2.4.1-2

and tried to do the hacks above, but it still could'nt find these libs.
What can I do?

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


Re: Need Python Pro for Help!! Plzz

2005-10-31 Thread Ruben Charles
A stranger from the land of Woot came to Master Foo as he was eating
the morning meal with his students.

I hear y00 are very l33t, he said. Pl33z teach m3 all y00 know.

Master Foo's students looked at each other, confused by the stranger's
barbarous language. Master Foo just smiled and replied: You wish to
learn the Way of Unix?

I want to b3 a wizard hax0r, the stranger replied, and 0wn ever3one's b0xen.

I do not teach that Way, replied Master Foo.



http://www.catb.org/~esr//writings/unix-koans/script-kiddie.html


On 10/30/05, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Need python Pro at [EMAIL PROTECTED] , if u wanna help, plz
 reply to that address. We are python beginners. need a real good
 Python Programmer for Help. TIA!!
 --
  * Posted with NewsLeecher v3.0 Beta 7
  * http://www.newsleecher.com/?usenet
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: data hiding/namespace pollution

2005-10-31 Thread Steven D'Aprano
On Mon, 31 Oct 2005 10:35:19 +, Alex Hunsley wrote:

 There's no really specific questions in this post, but I'm looking for 
 people's thought on the issues within...
 
 
 The two main versions I've encountered for data pseudo-hiding 
 (encapsulation) in python are:
 
 method 1:
 
 _X  - (single underscore) - just cosmetic, a convention to let someone
know that this data should be private.

Not quite.

In modules, names starting with one or more underscore (_X, __X, etc.) are
not copied over when you import the module using from module import *.

In classes, instance._X is just a convention this is private, don't touch
unless you really have to.

 method 2:
 
 __X - (double underscore) - mangles the name (in a predictable way).
Avoids name pollution.

Again, not quite: this only occurs for attributes, not names in modules.

 How often does either tend to get used? Personally, I'd be a little 
 worried about using method 1, because namespace clashes could happen. Is 
 this overly paranoid?

You are no more likely to have instance._attribute clash as you are to
have instance.attribute clash.

In fact, since each class is its own namespace, it is only an issue if you
are subclassing. And that is an argument for better documentation: if you
tell people your class uses semi-private attribute _X, and they still
accidentally over-write it, that is their fault exactly as if they
accidentally over-wrote public methods like .append().


 Also, I presume that rather than people writing their own manual getter 
 and setter methods, they tend to use either overloading on __getattr__ 
 and __setattr__, or the Property class (which itself uses aforementioned 
   methods). Overloading __getattr__ etc. seems more attractive to me, as 
 then I can capture access to unknown names, and raise an exception!

You don't need to overload __getattr__ to raise an exception when you
access unknown names:

py class Parrot:
... canSpeak = True  # note mixed case
...
py p = Parrot()
 p.canspeak
Traceback (most recent call last):
  File stdin, line 1, in ?
AttributeError: Parrot instance has no attribute 'canspeak'


In any case, that sounds like you are just making work for yourself.
What are you doing, manually keeping a list of allowed attributes which
you check before hand?

# warning: untested
class Spanish_Inquisition():
ALLOWED = ['comfy_chair', 'shrubbery']
def __getattr__(self, name):
if name in self.ALLOWED:
return self.__dict__[name]
raise ValueError(No such attribute)

Yuck yuck yuck. Slow, unnecessary, and of course you might think you know
what attributes your class needs, but you can never predict when your
class's users will want to add attributes you never thought of.

There is, at least, an argument in favour of using that technique for
enforcing something like attribute declarations:

def __setattr__(self, name, value):
if name in self.ALLOWED:
self.__dict__[name] = value
else:
raise ValueError(That attribute hasn't been declared.)

although that just leads into the whole bondage and domination language
can of worms.

In any case, you already have a perfectly good list of attributes.
Actually, two lists, one for class attributes and one for instance
attributes:

instance.__class__.__dict__.keys() 
instance.__dict__.keys() 

Keeping two lots of the same data around is usually a recipe for trouble.
Just wait until you delete an attribute, and then forget to remove it from
your ALLOWED list, and watch the fun and games when you start getting
unexpected errors.


 (I really don't like the idea of random attribute name typos going 
 unnoticed when accessing attributes in a class!)

This is no more a problem than getting random name typos when accessing
any objects in Python. In many people's experience, it is mostly -- but
not always -- those who don't use Python very much who worry about the
lack of declarations. In practice, if you are testing your code
sufficiently, you won't miss the lack of declarations. Declarations are
only good for picking up a tiny subset of bugs, and proper testing will
pick those same bugs -- and many more -- without the need for declaring
variables and/or attributes.

No doubt there will be some who disagree. Let me postscript my comments
with YMMV, and remind folks that even if declarations are the best thing
since the transistor, Python currently doesn't have them and all the
arguing in the world won't change that.


-- 
Steven.

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


Re: mixin helper class for unknown attribute access?

2005-10-31 Thread Alex Hunsley
Steven D'Aprano wrote:
 On Mon, 31 Oct 2005 10:39:40 +, Alex Hunsley wrote:
 
 
I know that I can catch access to unknown attributes with code something 
like the following:

class example:
  def __getattr__(self, name):
  if name == 'age':
  return __age
  else:
  raise AttributeError


but is there an existing mixin helper class in Python (or one someone 
has written) already that will assist with this? (Just not wanting to 
reinvent the wheel)
 
 
 Too late.
 
 py class Example:
 ... age = 0
 ...
 py Example.age
 0
 py Example.aeg
 Traceback (most recent call last):
   File stdin, line 1, in ?
 AttributeError: class Example has no attribute 'aeg'
 
 It works for instances too:
 
 py Example().aeg
 Traceback (most recent call last):
   File stdin, line 1, in ?
 AttributeError: Example instance has no attribute 'aeg'
 
 
 Your __getattr__ code is completely unnecessary.

Sorry, as I noted in another reply not long ago, I was having a 'braino' 
and not saying what I actually meant!
What I was talking about was the accidental _setting_ of the wrong 
attribute.
And the mixin class I'm looking for is one that could be told what were 
valid attributes for the class, and would then catch the situation where 
you mis-spelt an attribute name when setting an attrib.

thanks!
alex






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


Re: taking x-window screen shot

2005-10-31 Thread jepler
I recommend using 'xwd' to actually get the screenshot, because xwd is
installed nearly everwhere X is.  xwd-format images are documented by the
header file X11/XWDFile.h.  This program works in a pipeline to convert certain
xwd-format images to postscript.  You can use it something like this:
$ xwd | python xwdtops.py | lpr
.. it should print a greyscale rendition of the clicked window to the default
printer, if it accepts postscript.

It's been quite awhile since I wrote this program (and later re-wrote it
in C because it's a bit slow), so I'm not really familiar with this code
anymore.  However, I do believe that it works on common 16 and 32-bit X
displays.

One more thing --- if you have imagemagick installed, you may want to consider
using its command import instead.  Instead of the xwd format, it can write
the image in many formats, instead of just xwd.

Jeff

#---
import struct, sys

print %!PS-Adobe-1.0
def get_shift(n):
for i in range(32):
if n  (1i):
return i

def struct_read(f, fmt):
sz = struct.calcsize(fmt)
return struct.unpack(fmt, f.read(sz))

header_format = !25I
color_format = !IHHHBB

header_size = struct.calcsize(header_format)

header = struct_read(sys.stdin, header_format)

(header_size1, file_version, pixmap_format, pixmap_depth, pixmap_width, 
 pixmap_height, xoffset, byte_order, bitmap_unit, bitmap_bit_order,
 bitmap_pad, bits_per_pixel, bytes_per_line, visual_class, red_mask,
 green_mask, blue_mask, bits_per_rgb, colormap_entries, ncolors,
 window_width, window_height, window_x, window_y, window_bdrwidth) = header

if file_version != 7:
raise ValueError, Cannot parse file version %d (only 7) % file_version
if pixmap_format != 2:
raise ValueError, Cannot parse pixel format %d (only ZPixmap, 2) % 
pixel_format

window_name = sys.stdin.read(header[0]-100)[:-1] # discard terminating NUL

print % Undumping, window_name


colors = {}
for i in range(colormap_entries):
color = struct_read(sys.stdin, color_format)
colors[color[0]] = color

rest = sys.stdin.read()

rs = get_shift(red_mask)
gs = get_shift(green_mask)
bs = get_shift(blue_mask)

rsc = .299*256/(red_mask  rs)
gsc = .587*256/(green_mask  gs)
bsc = .114*256/(blue_mask  bs)

print %, red_mask, green_mask, blue_mask
print %, rs, gs, bs
print %, rsc, gsc, bsc
print %, bits_per_pixel
wscale = 558./window_width
hscale = 720./window_height
scale = min(1, wscale, hscale)

rwscale = 558./window_height
rhscale = 720./window_width
rscale = min(1, rwscale, rhscale)
print % scale -, scale, rscale

print /Helvetica findfont 16 scalefont setfont
print 18 756 moveto
print (%s) show %  .join(sys.argv[1:]) or window_name

if scale  rscale:
scale = rscale
#print %d %d translate % (window_height*scale+18, 36)
print %d %d translate % (8.5*72, 0)
print 90 rotate
print 18 %d translate % (594-window_height*scale) # 8.25
sz = 8.5*72
else:
print 18 %d translate % (750-window_height*scale) # 10.5
sz = 11*72

print %d %d scale % (window_width*scale, window_height*scale)

print /picstr %d string def % window_width

bytes_per_pixel = (bits_per_pixel+7)/8
row_format = %c%d%c % ([byte_order],
window_width,
HI[bits_per_pixel  16])
print %, row_format, bytes_per_line, bytes_per_pixel*window_width
print %, len(rest)

print %d %d 8 [%d 0 0 %d 0 0] {currentfile picstr readhexstring pop } image % 
(window_width, window_height, window_width, window_height)

if 0:
print 00* window_width
for row in range(window_height-2):
print 00 + c0 * (window_width-2) + 00
print 00* window_width
else:
for row in range(window_height-1, -1, -1):
a = row * bytes_per_line
b = a + bytes_per_pixel*window_width
for pixel in struct.unpack(row_format, rest[a:b]):
r = (pixel  red_mask)  rs
g = (pixel  green_mask)  gs
b = (pixel  blue_mask)  bs
gray = int(rsc*r+gsc*g+bsc*b)
sys.stdout.write(%02x % gray)
sys.stdout.write(\n)
print
print showpage
#---


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

Re: data hiding/namespace pollution

2005-10-31 Thread Alex Hunsley
Jorge Godoy wrote:
 Alex Hunsley [EMAIL PROTECTED] writes:
 
 
Btw, can you recall the subject line of the thread? I'd like to google groups
for it and have a read of that thread...
ta!
 
 
 Search for: alex martelli pychecker on comp.lang.python...  I don't have the
 thread's name anymore.  You'll probably find more than one thread with
 that. :-)

thanks! :]
lex

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


PyCon: proposal deadline is today

2005-10-31 Thread A.M. Kuchling
Today is your last chance to get in your PyCon 2006 submissions.  (If
you can't finish an outline today, you can still submit a summary and
provide the outline in a few days.)

Conference site:http://www.python.org/pycon/2006/
Call for Proposals: http://www.python.org/pycon/2006/cfp
Submission site:http://submit.python.org


A.M. Kuchling
Chair, PyCon 2006
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mixin helper class for unknown attribute access?

2005-10-31 Thread Steven D'Aprano
On Mon, 31 Oct 2005 12:47:16 +, Alex Hunsley wrote:

 Sorry, as I noted in another reply not long ago, I was having a 'braino' 
 and not saying what I actually meant!
 What I was talking about was the accidental _setting_ of the wrong 
 attribute.
 And the mixin class I'm looking for is one that could be told what were 
 valid attributes for the class, 

Who decides what are valid attributes for a class? The class writer, or
the class user who may want to use it in ways the writer never imagined?


 and would then catch the situation where 
 you mis-spelt an attribute name when setting an attrib.

If all you care about is preventing developers from adding any new
attributes at run time, you can do something like this:

# warning: untested
class Example:
def __init__(self, data):
self.__dict__['data'] = data
def __setattr__(self, name, value):
if self.__dict__.has_key(name):
self.__dict__[name] = value
else:
raise AttributeError

except that the developers will then simply bypass your code:

p = Example(None)
p.__dict__['surprise'] = 1
p.surprise

Trying to prevent setting new attributes is a pretty heavy-handed act just
to prevent a tiny subset of errors. Many people argue strongly that even
if you could do it, it would be pointless -- or at least, the cost is far
greater than whatever small benefit there is.

But, if you insist, something like this:

# Warning: untested.
class Declare:
def __init__(self, names):
names is a list of attribute names which are allowed.
Attributes are NOT initialised.

self.__dict__['__ALLOWED'] = names
def __setattr__(self, name, value):
if name in self.__ALLOWED:
self.__dict__[name] = value
else:
raise AttributeError(No such attribute.)

If you want to initialise your attributes at the same time you declare
them, use:

# Warning: untested.
class DeclareInit:
def __init__(self, names):
names is a dictionary of attribute names/values which are
allowed.

self.__dict__ = names
def __setattr__(self, name, value):
if self.__dict__.has_key(name):
self.__dict__[name] = value
else:
raise AttributeError(No such attribute.)

Of the two approaches, I would say the second is marginally less of a bad
idea.

-- 
Steven.

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


Re: Need Python Pro for Help!! Plzz

2005-10-31 Thread Alex Hunsley
[EMAIL PROTECTED] wrote:
 Need python Pro at [EMAIL PROTECTED] , if u wanna help, 

1) Why would anyone want to help you when you're not even willing to 
spend the (small) time and effort to spell simple words like you 
correctly or make sure your post actually makes sense? Start by helping 
yourself and writing english. Then you'd look less like a script kiddie.

2) Why should someone willing to help you enter into a private email 
discussion? Newsgroups like this exist to help people, and by it being a 
public forum, many more people can benefit from knowledge available 
here. If you asked your questions here, you'd be more likely to get 
answers, and many more people than yourself could benefit from the help 
that might result.




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


Re: mixin helper class for unknown attribute access?

2005-10-31 Thread Steven D'Aprano
On Mon, 31 Oct 2005 05:12:11 -0800, Sam Pointon wrote:

 One alrady exists, __slots__.
 
 class Foo(object):
   __slots__ = ['bar', 'baz', 'qig']
 
 
 f = Foo()
 f.foo = 'bar'
 
 Traceback (most recent call last):
   File pyshell#5, line 1, in -toplevel-
 f.foo = 'bar'
 AttributeError: 'Foo' object has no attribute 'foo'
 f.bar = 'foo'


__slots__ are NOT intended to be used to limit Python's dynamic nature.
Whether you call this usage a misuse or a serendipitous side-effect is a
matter of opinion.


 However, __slots__ only works for class instances, so if you're messing
 around with uninitialised classes (not a good idea outside the
 singleton pattern or very functional-style code) it won't work.


__slots__ only work with new-style classes, not classic classes.

Before using __slots__, read this:

http://www.python.org/doc/current/ref/slots.html

Then read this recipe:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158


-- 
Steven.

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


Re: learning emacs lisp

2005-10-31 Thread Jaime Wyant
I really appreciate the fact that while Xah is an inflammatory nut, he
hasn't been `censored' by the folks that run the mailing list.  Free
speech is awesome, no?

jw

On 10/30/05, Steve Holden [EMAIL PROTECTED] wrote:
 [To new readers:

 please ignore the rantings of this unbalanced person, who is well known
 for posing inappropriate and inflammatory material on news groups and
 mailing lists of all kinds.]

 Xah Lee wrote:
  well, in the past couple of days i started my own:
  http://xahlee.org/emacs/notes.html
 
  but i'm sure something like it exists.
 
  Btw, the elisp intro by
  Robert J Chassell. At:
  http://www.gnu.org/software/emacs/emacs-lisp-intro/
  is extremely well written.
  (and so is the elisp reference)
 
  Bravo to GNU  Freesoftware Foundation once again. Thank you.
 
  PS Fuck unix and unix fuckheads. Fuck asshole Larry Wall. Fuck Python
  documenation community and their fucking ass lying thru their teeth
  ignorance fucking shit. (See:
   http://xahlee.org/UnixResource_dir/writ/gubni_papri.html)
 
  Disclaimer: all mention of real person are opinion only.
 
   Xah
   [EMAIL PROTECTED]
  ∑ http://xahlee.org/
 
  rgb wrote:
 
 i'm looking for something example based... for senior professional
 programers who may want to pickup some elisp for practical macro.
 
 Unfortunately the path from any given language to Elisp varies vastly.
 For example a Prolog programmer would need far fewer tips than a Cobol
 or even a C programmer.  It's unlikely you will find something
 tailored to your specific experience.
 
 I'd already written programs in well over 100 languages in the 20
 years before learning Elisp yet I didn't find the intro terribly
 tedious until around section 13 (Counting).  At that point it switches
 focus toward examples of creating functions rather than introducing
 syntax and available features.  Perhaps starting at section 12 would
 suit your learning style better.
 
 As you probably realize, the language itself is just syntax and the
 hard part is learning about all the facilities at your disposal once
 you decide to write something.  There are a lot of features available
 and, although daunting, I think the reference is the best resource
 for discovering them.
 
 This group has also been indispensable to me.
 
 


 --
 Steve Holden   +44 150 684 7255  +1 800 494 3119
 Holden Web LLC www.holdenweb.com
 PyCon TX 2006  www.python.org/pycon/

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


--
Government does not solve problems; it subsidizes them.
Ronald Reagan
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Scanning a file

2005-10-31 Thread Paul Watson
Alex Martelli wrote:
...
gc.garbage
 
 [__main__.a object at 0x64cf0, __main__.b object at 0x58510]
 
 So, no big deal -- run a gc.collect() and parse through gc.garbage for
 any instances of your wrapper of file class, and you'll find ones that
 were forgotten as part of a cyclic garbage loop and you can check
 whether they were explicitly closed or not.
 
 
 Alex

Since everyone needs this, how about building it in such that files 
which are closed by the runtime, and not user code, are reported or 
queryable?  Perhaps a command line switch to either invoke or suppress 
reporting them on exit.

Is there any facility for another program to peer into the state of a 
Python program?  Would this be a security problem?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: data hiding/namespace pollution

2005-10-31 Thread bruno at modulix
Alex Hunsley wrote:
 bruno at modulix wrote:
 
 Alex Hunsley wrote:

(snip)

 method 1:

 _X  - (single underscore) - just cosmetic, a convention to let someone
  know that this data should be private.


 method 2:

 __X - (double underscore) - mangles the name (in a predictable way).
  Avoids name pollution.


 How often does either tend to get used? Personally, I'd be a little
 worried about using method 1, because namespace clashes could happen. Is
 this overly paranoid?

 Probably.

 Note that prefixing names with a single underscore have a 'protected'
 semantic - which means that such names (well, the objects that are bound
 to...) can be overriden/extends by child classes.
 
 
 Ah, my mistake, not merely cosmetic then! Thanks.

Well, to be more exact, the point is not that _names can be overriden,
but that, due to name mangling, the following won't work, or, at least,
not as expected:

class Base(object):
def __dothis(self):
print Base dothis

def dothat(self):
print Base dothat

def run(self):
self.__dothis()
self.dothat()

class Child(Base):
def __dothis(self):
print __%s_dothis % self.__class__.__name__

def dothat(self):
print %s dothat % self.__class__.__name__

c = Child()
c.run()

(snip)

 Sorry, I wasn't being clear. What I should have said is that I don't
 like the idea of a typo in an assignment causing the assigning of the
 wrong thing.
 e.g. imagine a simple value-holding class:
 
 class Values:
 pass
 
 v = Values()
 
 v.conductoin = 10
 
 
 ... I meant to type 'conduction' in the source but spelt it wrong.
 My value won't be there when elsewhere I refer to the correct attribute:
 conduction.
 

This kind of mistakes are usually not too hard to spot and not too hard
to correct. You'd have the same problem with a dict (and your Values
class is not much more than a dotted_syntax dict in disguise). BTW,
Pylint or Pychecker would catch this, and most unittests too.

Now if you have a case where this could really matter (like a user's
script), you can then define a more bondage_and_the_whip class with slots.

My overall experience with programming and Python is that keeping it
stupid simple where you can is usually the best approach. Your
__setattr__as_a_typo_catcher solution looks to me like a case of
arbitrary complexification. Better to go with the language than to fight
against it.

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


Arguments for button command via Tkinter?

2005-10-31 Thread [EMAIL PROTECTED]
Recently, I have been needing to do this alot and I can never find a
way around it, the main reason I want to do this is because for example
in the application I am making right now, it creates a grid of buttons
in a loop and they all have the same purpose so they need to call the
same method, within this method they need to change the background
color of the button clicked, I've tried stuff like...

button['command'] = lambda: self.fill(button)

def fill(self, wid):
button['bg'] = '#ff'

But that's no good, everytime it I do click a button the lambda method
I have setup keeps getting recreated so all of the button commands
point to the same lambda method, I have also tried appending them to an
array, and calling them from that.

Anyone have any clue as of what to do? Thanks.

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


Re: Need Python Pro for Help!! Plzz

2005-10-31 Thread Gerhard Häring
Alex Hunsley wrote:
 [EMAIL PROTECTED] wrote:
 
Need python Pro at [EMAIL PROTECTED] , if u wanna help, 
 [...]
 2) Why should someone willing to help you enter into a private email 
 discussion? [...]

Actually, it's a Google Group mailing list (formerly eGroups):

http://groups.google.de/group/newtopython?lnk=sghl=de

Maybe the people who set it up didn't know that there is perfectly good 
mailing list for the same topic already:

http://www.python.org/mailman/listinfo/tutor

-- Gerhard

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


Re: Automatically creating a HOME environ variable on Windows?

2005-10-31 Thread Jorgen Grahn
On Mon, 31 Oct 2005 12:26:30 +0100, Maciej Dziardziel [EMAIL PROTECTED] wrote:
 Jorgen Grahn wrote:

 Best solution would be to have portable function that returns
 user home directory and knows about all platfom quirks.
 
 Why is that better than Python creating a HOME in os.environ, if it
 doesn't
 already exist?  I can think of a few reasons it's better, and a few
 reasons it's worse.

 First, it is possible that HOME viariable already exists and has different
 meaning, (if python is used as embedded scripting language it can be
 defined by application),

And on systems where $HOME exists, that's what this new abstraction would
have to use internally anyway, so us Unix users won't lose anything. OK, I
accept the reasoning.

/Jorgen

-- 
  // Jorgen Grahn jgrahn@   Ph'nglui mglw'nafh Cthulhu
\X/algonet.se   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 'super' to only be used for diamond inheritance problems?

2005-10-31 Thread bruno at modulix
Alex Hunsley wrote:
 I've seen a few discussion about the use of 'super' in Python, including
 the opinion that 'super' should only be used to solve inheritance
 diamond problem. (And that a constructor that wants to call the
 superclass methods should just call them by name and forget about super.)
 What is people's opinion on this? Does it make any sense?

imho
Since you'll never know how your class will be used, better to stick
with super... super(MyClass, self).dothis() is no more difficult to use
than MySuperClass.dothis(self), and does not require much more typing,
so I don't see any reason not to use it.
/imho


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


Re: Arguments for button command via Tkinter?

2005-10-31 Thread [EMAIL PROTECTED]
And yet the stupidity continues, right after I post this I finnally
find an answer in a google search, It appears the way I seen it is to
create a class for each button and have it call the method within that.
If anyone else has any other ideas please tell.

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


Re: need start point for getting html info from web

2005-10-31 Thread alex_f_il
You can easily do it with SW Explorer Automation
(http://home.comcast.net/~furmana/SWIEAutomation.htm).
The program creates an automation API for any Web application which
uses HTML and DHTML and works with Microsoft Internet Explorer. The Web
application becomes programmatically accessible from any .NET language.


The tool has Visual Table Data Extractor. It allows visually define the
table structure. The table becomes accessible from the code as
DataTable class. You can develop the extraction script in hours with
the tool.

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


Re: Need Python Pro for Help!! Plzz

2005-10-31 Thread Fredrik Lundh
Alex Hunsley wrote:

 2) Why should someone willing to help you enter into a private email
 discussion? Newsgroups like this exist to help people

looks like Fan wants to run his own group:

http://groups.google.com/group/newtopython/about

There are no experts or PHD's, all are simple users, even i also am
new to python. So. forget com.lang.python if ur new to python.

if someone feels that the huge number of PhD experts on comp.lang.python
can be a bit overwhelming, my recommendation is to check out this list:

http://mail.python.org/mailman/listinfo/tutor

/F 



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


Re: Tkinter problem

2005-10-31 Thread Fredrik Lundh
dale cooper wrote:

 I've recently installed python2.4.2 on Fedora 4 (from downloaded
 sources), but it appeared, that I can't use Tkinter module:

 import Tkinter
 Traceback (most recent call last):
  File stdin, line 1, in ?
  File /usr/local/lib/python2.4/lib-tk/Tkinter.py, line 38, in ?
import _tkinter # If this fails your Python may not be configured
 for Tk
 ImportError: libBLT24.so: cannot open shared object file: No such file
 or directory

this seems to indicate that the build process picked up the Tk BLT extension 
[1],
but that you haven't installed that extension properly.

/F

1) http://sourceforge.net/projects/blt/



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


Re: process and spinning slash

2005-10-31 Thread Fredrik Lundh
benz [EMAIL PROTECTED] wrote

I have rewrited my code as follow, but it still not working.

 import os, sys


 pid = os.fork()

 if pid == 0:
  os.execvp(du,(du,-shc,/usr/share))
 else:
  while 1:
try:
  os.kill(pid,0)
  sys.stdout.write('running')
  sys.stdout.flush()
  sys.stdout.write('\b\b\b\b\b\b\b')
except OSError:
  print child ended

thomas has already explained why that doesn't work:

http://article.gmane.org/gmane.comp.python.general/428821

/F 



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


Re: Expanding Python as a macro language

2005-10-31 Thread Jorgen Grahn
On 29 Oct 2005 17:25:58 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
...
 Michel wrote:
...
  Linux can run perfectly happily without any form of windowing
  environment.

 I know, but nowadays almost any relevant application has a GUI.

Side note: lots of people would disagree with that. For example, from my
perspective, almost all relevant applications /lack/ a GUI. (And some that
has one would be better off without it.)

/Jorgen

-- 
  // Jorgen Grahn jgrahn@   Ph'nglui mglw'nafh Cthulhu
\X/algonet.se   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning a file

2005-10-31 Thread Steve Holden
Paul Watson wrote:
 Alex Martelli wrote:
 ...
 
gc.garbage

[__main__.a object at 0x64cf0, __main__.b object at 0x58510]

So, no big deal -- run a gc.collect() and parse through gc.garbage for
any instances of your wrapper of file class, and you'll find ones that
were forgotten as part of a cyclic garbage loop and you can check
whether they were explicitly closed or not.


Alex
 
 
 Since everyone needs this, how about building it in such that files 
 which are closed by the runtime, and not user code, are reported or 
 queryable?  Perhaps a command line switch to either invoke or suppress 
 reporting them on exit.
 
This is a rather poor substitute from correct program design and 
implementation. It also begs the question of exactly what constitutes a 
file. What about a network socket that the user has run makefile() on? 
What about a pipe to another process? This suggestion is rather ill-defined.

 Is there any facility for another program to peer into the state of a 
 Python program?  Would this be a security problem?

It would indeed be a security problem, and there are enough of those 
already without adding more.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Windows - Need to process quotes in string...

2005-10-31 Thread Ernesto
I'm trying to use a $ delimeter, but it doesn't seem to work.  Here is
the code:


launchWithoutConsole(devcon.exe,d'$enable
@USB\VID_0403PID_6010MI_00\715E4F681$)

I want to send the string parameter:

enable @USB\VID_0403PID_6010MI_00\715E4F681

to the program devcon.

The argument itself is a string, but has quotes inside too.  I've tried
it many different ways and I keep getting syntax errors.

Thanks,

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


Re: Arguments for button command via Tkinter?

2005-10-31 Thread Steve Holden
[EMAIL PROTECTED] wrote:
 And yet the stupidity continues, right after I post this I finnally
 find an answer in a google search, It appears the way I seen it is to
 create a class for each button and have it call the method within that.
 If anyone else has any other ideas please tell.
 
I'm hoping you have simply mis-stated your correct understanding of the 
problem, and that what you really propose to do is create a button class 
of which each button in your interface is an instance.

Let's suppose you want each button to toggle between two colors, but 
that the colors for each button are different. The thing to do is create 
a button class that subclasses the button class of your GUI package 
(whatever that may be), storing the required color values as instance 
attributes.

In wxPython, for example, I would write something like (warning: untested):

import wx

class myButton(wx.Button):

 def __init__(self, color1, color2, *args, **kw):
 wx.Button.__init__(self, *args, **kw)
 self.c1 = color1
 self.c2 = color2
 self.state = False

 def onClick(self, event):
 if self.state:
 self.SetBackgroundColor(self.c1)
 else:
 self.SetBaclgroundColor(self.c2)
 self.state = not self.state

Then when you create a button with, say,

 but1 = myButton(wx.RED, wx.BLUE, ...)

you can associate a click on that button with a bound instance method, 
which you'd do in wxPython like:

 wx.EVT_BUTTON(parent, but1, but2.onClick)

but similar considerations apply to Tkinter, and you appear to have the 
wit to be able to extend the argument to that toolkit.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Windows - Need to process quotes in string...

2005-10-31 Thread Sybren Stuvel
Ernesto enlightened us with:
 I'm trying to use a $ delimeter

Why?

 I want to send the string parameter:

 enable @USB\VID_0403PID_6010MI_00\715E4F681

launchWithoutConsole(devcon.exe
'enable @USB\VID_0403PID_6010MI_00\715E4F681')

Or, if you should also be able to send single quotes:

launchWithoutConsole(devcon.exe
'''enable @USB\VID_0403PID_6010MI_00\715E4F681''')

 The argument itself is a string, but has quotes inside too.

Then use other quotes as string delimiters. Why would you use
something else?

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


Re: handling ExpatError exception raised from ElementTree.XML() method

2005-10-31 Thread Paul Boddie
[EMAIL PROTECTED] wrote:

 It's not clear how a grep of the site-packages directory revealed the
 most likely location of the ExpatError class is xml.parsers.expat.

Here's what I did:

grep -e ExpatError -r /usr/lib/python2.4/site-packages/

What is interesting is that most of the hits belonged to packages
which you may not have on your system: pyxdg and smartpm, for example,
which mention the ExpatError class. I did get the following message,
though:

Binary file
/usr/lib/python2.4/site-packages/_xmlplus/parsers/pyexpat.so matches

 ...it located the file Mr. Boddie mentioned...\lib\xml\parsers\expat.py.  
 That file has
 only a few lines of code...it appears to import all the objects from what I'm 
 guessing
 is the pyexpat extension module.  I'm guessing that ExpatError is
 embedded within that extension module...is that a correct guess?

I believe so.

Paul

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


Re: Expanding Python as a macro language

2005-10-31 Thread Sybren Stuvel
[EMAIL PROTECTED] enlightened us with:
 I know, but nowadays almost any relevant application has a GUI.

I can't think of any relevant server application running on Linux that
has a GUI. My text processor, email client, Usenet client, IRC client,
address book and agenda are all without GUI too.

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


Re: data hiding/namespace pollution

2005-10-31 Thread Alex Hunsley
Steven D'Aprano wrote:
 On Mon, 31 Oct 2005 10:35:19 +, Alex Hunsley wrote:
 
 
There's no really specific questions in this post, but I'm looking for 
people's thought on the issues within...


The two main versions I've encountered for data pseudo-hiding 
(encapsulation) in python are:

method 1:

_X  - (single underscore) - just cosmetic, a convention to let someone
   know that this data should be private.
 
 
 Not quite.
 
 In modules, names starting with one or more underscore (_X, __X, etc.) are
 not copied over when you import the module using from module import *.

And you can also control what gets exported by defining __all__ I 
believe

 
 In classes, instance._X is just a convention this is private, don't touch
 unless you really have to.

ah, ok.

 [snip some more details]

Thanks for your helpful response, it's clarifying a few things for me!

 What are you doing, manually keeping a list of allowed attributes which
 you check before hand?
 


Heheh. No, I'm not actually 'doing' anything yet, I'm  findout out what 
is good practise in python land.


 There is, at least, an argument in favour of using that technique for
 enforcing something like attribute declarations:
 
 def __setattr__(self, name, value):
 if name in self.ALLOWED:
 self.__dict__[name] = value
 else:
 raise ValueError(That attribute hasn't been declared.)
 
 although that just leads into the whole bondage and domination language
 can of worms.
 
 In any case, you already have a perfectly good list of attributes.
 Actually, two lists, one for class attributes and one for instance
 attributes:
 
 instance.__class__.__dict__.keys() 
 instance.__dict__.keys() 
[snip]

okeydoke.
thanks for the advice!
alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arguments for button command via Tkinter?

2005-10-31 Thread Francesco Bochicchio
Il Mon, 31 Oct 2005 06:23:12 -0800, [EMAIL PROTECTED] ha scritto:

 And yet the stupidity continues, right after I post this I finnally
 find an answer in a google search, It appears the way I seen it is to
 create a class for each button and have it call the method within that.
 If anyone else has any other ideas please tell.

This is  how I do it: Supposing I have three buttons b1, b2 and b3, and I
want for each button to call the same callback with, as argument, the
button itself:


def common_callback(button):
# callback code here


class CallIt(objetc):
def __init__(function, *args ):
self.function, self.args = function, args
def __call__(self, *ignore):
self.function(button, *self.args)

b1['command']= CallIt(common_callback, b1)
b2['command']= CallIt(common_callback, b2)
b3['command']= CallIt(common_callback, b3)

This way you need only one class (a sort of custom callable) and
its instances gets called by Tkinter and in turn calls your
callback with the proper arguments.

Ciao
-
FB





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


Re: mixin helper class for unknown attribute access?

2005-10-31 Thread Alex Martelli
Steven D'Aprano [EMAIL PROTECTED] wrote:
   ...
 Trying to prevent setting new attributes is a pretty heavy-handed act just
 to prevent a tiny subset of errors. Many people argue strongly that even
 if you could do it, it would be pointless -- or at least, the cost is far
 greater than whatever small benefit there is.

I entirely agree with you (also about the use of __slots__ being a
particularly WRONG way to achieve this).  When I have to suggest a mixin
to avoid accidental setting of misspelled attributes (which does appear
to be a clinically certifiable phobia of programmers coming to Python
from certain other languages) I suggest something like:

class Rats(object):
  def __setattr__(self, name, value):
if hasattr(self, name):
  super(Rats, self).__setattr__(name, value)
else:
  raise AttributeError, can't set attribute %r % (name,)

The key idea is to exploit hasattr's semantics -- it checks the class as
well as the specific instance.

Example use case:

class Bah(Rats):
  foo = bar = baz = 23

now, given b=Bah(), you can set b.foo, b.bar and b.baz, but no other
attribute of b (of course you can bypass the restriction easily -- such
restrictions are always intended against *accidental* cases, not against
deliberate attacks).

Differently from __slots__, Rats gives no problems with pickling,
inheritance, etc, etc.


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


Re: data hiding/namespace pollution

2005-10-31 Thread Alex Martelli
Alex Hunsley [EMAIL PROTECTED] wrote:

 There's no really specific questions in this post, but I'm looking for
 people's thought on the issues within...
 
 
 The two main versions I've encountered for data pseudo-hiding 
 (encapsulation) in python are:
 
 method 1:
 
 _X  - (single underscore) - just cosmetic, a convention to let someone
know that this data should be private.
 
 
 method 2:
 
 __X - (double underscore) - mangles the name (in a predictable way).
Avoids name pollution.
 
 
 How often does either tend to get used? Personally, I'd be a little 
 worried about using method 1, because namespace clashes could happen. Is
 this overly paranoid?

Experienced programmers who know little Python tend to start with (2),
and mostly migrate to (1) with time (once they've had to hand-mangle
names a few times to work around (2)'s limitations for testing or
overrides they had not foreseen).  Accidental name clashes between
superclasses and subclasses tend to be caught very rapidly by unit tests
that are at all decent, anyway.


 Also, I presume that rather than people writing their own manual getter
 and setter methods, they tend to use either overloading on __getattr__
 and __setattr__, or the Property class (which itself uses aforementioned
   methods). Overloading __getattr__ etc. seems more attractive to me, as
 then I can capture access to unknown names, and raise an exception!

If you AVOID overriding __getattr__, THEN you'll automatically get
exceptions; __getattr__ is called only when, were it absent, the
exception would get raised.  property does NOT use __getattr__ at all,
but rather each instance thereof is a descriptor and thus uses its own
__get__.  __setattr__ has very different semantics and is appropriate
only in very peculiar circumstances.


 (I really don't like the idea of random attribute name typos going 
 unnoticed when accessing attributes in a class!)

A common but unjustified paranoia.  I've been coding almost exclusively
(say over 90% of my work) in Python for over 5 years, and also teaching,
consulting, mentoring c based on Python, and all the possible
typo-level bugs that so terrify so many new-to-Python programmers are
simply irrelevant -- they're not common in the first place, pychecker
and the likes make short work of them, and unit tests (which ARE
indispensable in any language anyway) catch them easily just as they
catch the really nasty typos possible in any language such as typing -=
where one meant +=,  where one should have coded = (the one most
likely tiny-bug in any language, since it can be a thinko ever more
easily than a typo -- it once took me three days debugging a Fortran
program for extremely subtle corner-case errors that boiled down to a
miscoding of .LT. where .LE. should have been), and the like.


If you manage to do a significant poll of the community, don't forget to
correlate respondents' opinions with each respondent depth and length of
experience with real-world Python use...


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


Re: Windows - Need to process quotes in string...

2005-10-31 Thread Francesco Bochicchio
Il Mon, 31 Oct 2005 07:18:31 -0800, Ernesto ha scritto:

 I'm trying to use a $ delimeter, but it doesn't seem to work.  Here is
 the code:
 
 
 launchWithoutConsole(devcon.exe,d'$enable
 @USB\VID_0403PID_6010MI_00\715E4F681$)
 
 I want to send the string parameter:
 
 enable @USB\VID_0403PID_6010MI_00\715E4F681
 
 to the program devcon.
 
 The argument itself is a string, but has quotes inside too.  I've tried
 it many different ways and I keep getting syntax errors.
 
 Thanks,

Use the single quote to delimit the string, so you can use the double
quote inside it. Like this:

'enable @USB\VID_0403PID_6010MI_00\715E4F681' 

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


Re: 'super' to only be used for diamond inheritance problems?

2005-10-31 Thread Alex Martelli
Alex Hunsley [EMAIL PROTECTED] wrote:

 I've seen a few discussion about the use of 'super' in Python, including
 the opinion that 'super' should only be used to solve inheritance 
 diamond problem. (And that a constructor that wants to call the 
 superclass methods should just call them by name and forget about super.)
 What is people's opinion on this? Does it make any sense?

No, it makes no sense whatsoever.  Any situation where multiple
inheritance is possible, diamonds or no diamonds, can benefit from
cooperative superclass calling where needed (e.g., __init__).  Consider:

class A(B, C): ...

should A know or care at all whether B and C share common bases?  Of
course not -- why should A have to be burdened with that knowledge?!  To
ensure __init__ is called on each base once and only once,
systematically using super(A, self) is the best and simplest way.

Another way to put it: there's ALWAYS meshes (diamonds or more
complicated forms), whenever multiple inheritance occurs, because (in
the newstyle object model, and the other one only exists for legacy
reasons and shouldn't be used in new code) object is always among the
ancestors of EVERY class.  So, again: use super.


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


Rename files with numbers

2005-10-31 Thread dudufigueiredo
I have one folder containing mp3 files, the folder is:
C:\My Shared Folder\Rubber Soul

And the files are:
01 drive my car.mp3
02 norwegian wood.mp3
03 you won't see me.mp3
04 nowhere man.mp3
.
.
.

I'm trying to rename files to:
The Beatles - Drive My Car.mp3
The Beatles - Norwegian Wood.mp3
The Beatles - You Won't See Me.mp3
The Beatles - Nowhere Man.mp3
.
.
.

So I need to change the file number to The Beatles - and Capitalize
the name.
I was trying to create a function and using glob and rename, but i had
no sucsses...
Could somebody help me please,
Since now, thanks...

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


Python -- CGI -- Take SQL database, make it download in CSV

2005-10-31 Thread [EMAIL PROTECTED]
I currently have a cgi-bin which I use to authenticate users against a
SQL database, which holds info about them, and their login info.

I would like to have the 'admin' section take part of the table and put
it in CSV and allow them to download it, somehow making it so that the
'members' cannot download it.

How it authenticates an admin --
Check User/pass
if correct:
check if-member:
print html-for-members
check if-admin:
print html-for-admins
if incorrect:
print enter correct creds


So I would like to have a link in the html-for-admins, that could
re-auth them, and if it's correct allow a download of a csv file of
most of the sql table (I'd like to exclude the md5's  ;)  )

Does anyone have any ideas on how to do this?

Alex

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


Re: Arguments for button command via Tkinter?

2005-10-31 Thread Mike Meyer
[EMAIL PROTECTED] [EMAIL PROTECTED] writes:
 Recently, I have been needing to do this alot and I can never find a
 way around it, the main reason I want to do this is because for example
 in the application I am making right now, it creates a grid of buttons
 in a loop and they all have the same purpose so they need to call the
 same method, within this method they need to change the background
 color of the button clicked, I've tried stuff like...

 button['command'] = lambda: self.fill(button)

 def fill(self, wid):
 button['bg'] = '#ff'

 But that's no good, everytime it I do click a button the lambda method
 I have setup keeps getting recreated so all of the button commands
 point to the same lambda method, I have also tried appending them to an
 array, and calling them from that.

 Anyone have any clue as of what to do? Thanks.

People have pointed out how to do this with a class, but you can do it
with lambdas as well. I suspect the problem you're having is that
python is binding values at call time instead of at definition time,
but it's hard to tell without more of your source code.

If I'm right, one solution is to make the values you want bound at
definition time optional arguments to the lambda, bound to the correct
value then. So you'd do:

  button['command'] = lambda b = button: self.fill(b)

The version you used will look up the name button when the lambda is
invoked. My version will look it up when the lambda is defined.

 mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Instantiating Classes in python (newbie)

2005-10-31 Thread DaBeef
Hello, I am learning python for work from knowing java,c#,c.  I had a
couple questions.
1)  IntegerClass - to instantiate this class how come I use i =
IntegerClass.IntegerClass() and then this works while i =
IntegerClass() i.method.  I receive an error.

2)  Also using self in the method (self, dataVal).  What does this do
differently from using (dataval).  I am a little confused about the
bound and unbound methods.  What does passing self do different?
Thank-you for all your help

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


Asyncore Loop Question

2005-10-31 Thread John W
Hello,

I have a gui application where I am trying to use the asyncore module
to gather data from other computers. I am able to connect, but I
am getting constant handle_write_event method calls into my
application. It is obviously slowing down the gui processing
significantly.

My understanding is that the handle_write_event and handle_read_event
are both edge notifications and I should just get the method call
essentially just once.

I think the problem is how I have my loop() call configured. All
I am trying to do with the code below is to open the socket (that
works) and then receive a single handle_write_event method call.
Instead, I am getting constantly barraged with them.

I have tried several different types of the loop() call (using poll,
timeout...) but with no luck. If anyone can explain what I should
be doing to get a single handle_write_event call until I actually write
something to the socket (which my code is not presently doing yet), I
would appreciate 

Below is some code showing what I am doing:

--
class Connection(asyncore.dispatcher):
 def __init__ (self, server_name, port_num ):
 self.message_queue = []

 asyncore.dispatcher.__init__(self)
 self.create_socket( socket.AF_INET, socket.SOCK_STREAM )
 self.connect(( server_name, port_num ))


 def handle_read_event( self ):
 print handle_read_event received


 def handle_write_event( self ):
 print Asking for a write

 if len( self.message_queue )  0:
 # Pop the first message off the queue
 self.send_next_message()


class TestApp:
 def __init__( self, server_name, port_number ):

 self.nomad = Connection( server_name, port_number )
 asyncore.loop()


Output ends up being a constant stream of:
Asking for a write
Asking for a write
Asking for a write
Asking for a write
Asking for a write

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

Re: Scanning a file

2005-10-31 Thread Bengt Richter
On Mon, 31 Oct 2005 09:41:02 +0100, 
=?ISO-8859-1?Q?Lasse_V=E5gs=E6ther_Karlsen?= [EMAIL PROTECTED] wrote:

David Rasmussen wrote:
snip
 If you must know, the above one-liner actually counts the number of 
 frames in an MPEG2 file. I want to know this number for a number of 
 files for various reasons. I don't want it to take forever.
snip

Don't you risk getting more frames than the file actually have? What 
if the encoded data happens to have the magic byte values for something 
else?

Good point, but perhaps the bit pattern the OP is looking for is guaranteed
(e.g. by some kind of HDLC-like bit or byte stuffing or escaping) not to occur
except as frame marker (which might make sense re the problem of re-synching
to frames in a glitched video stream).

The OP probably knows. I imagine this thread would have gone differently if the
title had been How to count frames in an MPEG2 file? and the OP had supplied
the info about what marks a frame and whether it is guaranteed not to occur
in the data ;-)

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


Re: Using graphviz to visualize trace.py output, anybody?

2005-10-31 Thread David E. Konerding DSD staff
In article [EMAIL PROTECTED], [EMAIL PROTECTED] wrote:
 Hi,
 
 has anybody thought of / already used graphviz to convert the output of
 trace.py into a graph? I looked at PyUMLGraph, but 1. PyUMLGraph does
 not successfully create a dot file, and 2. I don't really want a UML
 representation but a compact representation of program execution.
 
 Maybe there is some other tool that I am not aware of which can create
 this kind of trace. I use eclipse with pydev plugin on MacOS 10.3.9
 
 Regards,
 Svenn
 

Take a look at:
http://dkbza.org/pydot.html

It's a python interface which can produce dot format files (based on its 
internal
graph API) and run graphviz for you.

I'm not sure which trace.py you're referring to, but I assume it dumps some 
output file.
You have a couple of obvious ways to get what you want:

1) modify trace.py to create a pydot graph structure then write to file
2) make a script that parses the trace.py output to create a pydot graph 
structure then write to file

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


Re: Scanning a file

2005-10-31 Thread Bengt Richter
On Mon, 31 Oct 2005 09:19:10 +0100, Peter Otten [EMAIL PROTECTED] wrote:

Bengt Richter wrote:

 I still smelled a bug in the counting of substring in the overlap region,
 and you motivated me to find it (obvious in hindsight, but aren't most ;-)
 
 A substring can get over-counted if the overlap region joins
 infelicitously with the next input. E.g., try counting 'xx' in 10*'xx'
 with a read chunk of 4 instead of 1024*1024:
 
 Assuming corrections so far posted as I understand them:
 
   def byblocks(f, blocksize, overlap):
  ... block = f.read(blocksize)
  ... yield block
  ... if overlap0:
  ... while True:
  ... next = f.read(blocksize-overlap)
  ... if not next: break
  ... block = block[-overlap:] + next
  ... yield block
  ... else:
  ... while True:
  ... next = f.read(blocksize)
  ... if not next: break
  ... yield next
  ...
   def countsubst(f, subst, blksize=1024*1024):
  ... count = 0
  ... for block in byblocks(f, blksize, len(subst)-1):
  ... count += block.count(subst)
  ... f.close()
  ... return count
  ...
 
   from StringIO import StringIO as S
   countsubst(S('xx'*10), 'xx',  4)
  13
   ('xx'*10).count('xx')
  10
   list(byblocks(S('xx'*10), 4, len('xx')-1))
  ['', '', '', '', '', '', 'xx']
 
 Of course, a large read chunk will make the problem either
 go away
 
   countsubst(S('xx'*10), 'xx',  1024)
  10
 
 or might make it low probability depending on the data.

[David Rasmussen]

 First of all, this isn't a text file, it is a binary file. Secondly,
 substrings can overlap. In the sequence 0010010 the substring 0010
 occurs twice.
The OP didn't reply to my post re the above for some reason
   http://groups.google.com/group/comp.lang.python/msg/dd4125bf38a54b7c?hl=en;


Coincidentally the always overlap case seems the easiest to fix. It
suffices to replace the count() method with

def count_overlap(s, token):
pos = -1
n = 0
while 1:
try:
pos = s.index(token, pos+1)
except ValueError:
break
n += 1
return n

Or so I hope, without the thorough tests that are indispensable as we should
have learned by now...

Unfortunately, there is such a thing as a correct implementation of an 
incorrect spec ;-)
I have some doubts about the OP's really wanting to count overlapping patterns 
as above,
which is what I asked about in the above referenced post. Elsewhere he later 
reveals:

[David Rasmussen]
 If you must know, the above one-liner actually counts the number of 
 frames in an MPEG2 file. I want to know this number for a number of 
 files for various reasons. I don't want it to take forever.

In which case I doubt whether he wants to count as above. Scanning for the
particular 4 bytes would assume that non-frame-marker data is escaped
one way or another so it can't contain the marker byte sequence.
(If it did, you'd want to skip it, not count it, I presume). Robust streaming 
video
format would presumably be designed for unambigous re-synching, meaning
the data stream can't contain the sync mark. But I don't know if that
is guaranteed in conversion from file to stream a la HDLC or some link packet 
protocol
or whether it is actually encoded with escaping in the file. If framing in the 
file is with
length-specifying packet headers and no data escaping, then the 
filebytes.count(pattern)
approach is not going to do the job reliably, as Lasse was pointing out.

Requirements, requirements ;-)

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


Re: Rename files with numbers

2005-10-31 Thread Micah Elliott
On Oct 31, [EMAIL PROTECTED] wrote:
 I have one folder containing mp3 files, the folder is:
 C:\My Shared Folder\Rubber Soul
 
 And the files are:
 03 you won't see me.mp3
 .
 
 I'm trying to rename files to:
 The Beatles - You Won't See Me.mp3
 .

My first suggestion is that you make better changes while you're
taking the effort to rename.  I.e., don't use spaces or apostrophes
(or other shell-unfriendly characters) in file names (though some
might disagree with me on this religious issue).  So for your case a
more parse-able/useful translation might be:

The_Beatles_-_You_Wont_See_Me.mp3

 So I need to change the file number to The Beatles -

You'll probably want to use re for this.  In a loop over
your glob'd files, something like:

re.sub(r'^\d\d\s', r'The Beatles - ', ...)

 and Capitalize the name.

If you avoid the apostrophe, then 'you wont see me'.title() will do
the Right Thing.

 I was trying to create a function and using glob and rename, but i
 had no sucsses... Could somebody help me please,

You should post the solution you've attempted to write if you want help
fixing it.

-- 
_ _ ___
|V|icah |- lliott  http://micah.elliott.name  [EMAIL PROTECTED]
  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: textwidget.tag_bind(name, Any-KeyPress, self.donothing) not working

2005-10-31 Thread shannonl
Thanks for your help and the link.  From the link it sounds like no one
is sure how this is supposed to act.  I will dig around in the tcl
forum and see what I can find.

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


Re: Print to printer

2005-10-31 Thread avnit
I just want to print text. I'll try macpython. Thanks for the help.

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


Python Linked list?

2005-10-31 Thread Simon Roses Femerling



Hi there!

I'm looking for a linked list class or lib ? Any 
suggestions ?

Is for a project I'm working on.

Sincerely,

Simon Roses Femerling
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Rename files with numbers

2005-10-31 Thread dudufigueiredo
Ok, so the function simplifyed without loops:

def renamer(folder, band):
archive = #file to transform
rest = archive[3:]
print band +  -,rest.capitalize()


obs: the file names came this way(with spaces or apostrophes) from the
cd i imported.

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


Re: Instantiating Classes in python (newbie)

2005-10-31 Thread infidel
 Hello, I am learning python for work from knowing java,c#,c.  I had a
 couple questions.
 1)  IntegerClass - to instantiate this class how come I use i =
 IntegerClass.IntegerClass() and then this works while i =
 IntegerClass() i.method.  I receive an error.

It depends on what IntegerClass is.  If you have a module named
IntegerClass with a class named IntegerClass within it, then you must
use IntegerClass.IntegerClass to refer to the class, because
IntegerClass is the module.  You could also change the import statement
to:

from IntegerClass import IntegerClass

... in which case, IntegerClass in your current namespace will be the
class and not the module.

This is all an educated guess because you didn't specify what the error
was.

 2)  Also using self in the method (self, dataVal).  What does this do
 differently from using (dataval).  I am a little confused about the
 bound and unbound methods.  What does passing self do different?
 Thank-you for all your help

A bound method is kind of like an instance method in java, it's bound
to a particular instance object.  Python automatically inserts a
reference to the object itself as the first argument to a bound call.
self is just like this in Java, but you have to explicitly account
for it in the method signature.

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


Re: MacOS Extension Carbon.File.FSCatalogInfo file sizes should be UInt64?

2005-10-31 Thread Kevin Walzer
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

donbro wrote:
| If my read of the extension source (Mac/Modules/file/_Filemodule.c) is
| correct, the parameter sizes specified for data and resource file sizes
| are UInt32 where they should be UInt64.
|
| In both OS9 and OSX Carbon, the MacOS File Manager (Files.h) uses
| UInt64 values for data and resource filesizes.
|
| Testing Python 2.3 and 2.4.2 on MacOS 10.3 returns 0L for the file size
| values and correct values for other elements such as parentDirID:
|
|
|fsRef = FSRef('LICENSE')
|catinfo, d1, d2, d3  = fsRef.FSGetCatalogInfo(-1L)
|catinfo.dataPhysicalSize
|
| 0
|
|catinfo.parentDirID
|
| 2026177
|
|
| in Files.h, both OS9 and OSX Carbon, the elements are UInt64:
|
| struct FSCatalogInfo {
| [...]
| UInt64  dataLogicalSize;
| UInt64  dataPhysicalSize;
| UInt64  rsrcLogicalSize;
| UInt64  rsrcPhysicalSize;
| [...]
| }
|
| in _Filemodule.c the spec looks to be 32 bit:
|
| static PyObject *FSCatalogInfo_get_dataLogicalSize(FSCatalogInfoObject
| *self, void *closure)
| {
|   return Py_BuildValue(l, self-ob_itself.dataLogicalSize);
| }
|
| I have, perhaps naively, just changed my local copy to use a BuildValue
| parameter of L instead of l for each of these get and set methods
| and this has survived my initial testing:
|
| static PyObject *FSCatalogInfo_get_dataLogicalSize(FSCatalogInfoObject
| *self, void *closure)
| {
|   return Py_BuildValue(L, self-ob_itself.dataLogicalSize);
| }
|
| But my questions are:
|
| Has anyone else seen this?
|
| Does this seem like the right fix?
|
| There is another routine in _Filemodule.c: FSCatalogInfo_tp_init() that
| also seems to hold information relevant to parameter size.  Should this
| be changed as well?
|
| If this is a bug, what's the best procedure to report this?
| Sourceforge?  This mailing list?
|
| I'm porting a MacOS9 application from C++ to python and I expect to be
| seeing a lot of these python macintosh filesystem extensions in the
| near future!
|
| Thanks for any help
|
| Don
|
You're most likely to get a good answer to this question on the
MacPython mailing list--give that a try if you don't get a response here.


- --
Cheers,

Kevin Walzer, PhD
WordTech Software - Tame the Terminal
http://www.wordtech-software.com
sw at wordtech-software.com
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.1 (Darwin)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFDZmj8JmdQs+6YVcoRAtkTAJ9CEYbIRy6VLY7qp304JPmcl+iXUQCdHTMT
KmJljW7loFJNKFsjFkB2aNA=
=vEVV
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Print to printer

2005-10-31 Thread avnit
I just want to print text. I'll try macpython. Thanks for the help.

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


Re: Arguments for button command via Tkinter?

2005-10-31 Thread [EMAIL PROTECTED]
Yah, thats how i learned how to do it, thanks.

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


Re: Expanding Python as a macro language

2005-10-31 Thread Mike Meyer
Jorgen Grahn [EMAIL PROTECTED] writes:

 On 29 Oct 2005 17:25:58 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 ...
 Michel wrote:
 ...
  Linux can run perfectly happily without any form of windowing
  environment.

 I know, but nowadays almost any relevant application has a GUI.

 Side note: lots of people would disagree with that. For example, from my
 perspective, almost all relevant applications /lack/ a GUI. (And some that
 has one would be better off without it.)

This brings up an interesting point for scripting unix
applications. One common approach is to provide the application
functionaliity in a library, then wrap that in various ways, of which
a GUI is only one. You script the application by wrapping the
library for your favorite scripting language, and the script will never
open a GUI. In fact, it'll work fine in an environment where the GUI
couldn't open at all.

 mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Function returns none

2005-10-31 Thread noahlt
I'm trying to write a website updating script, but when I run the
script, my function to search the DOM tree returns None instead of what
it should.

I have this program:

import sys
from xml.dom.minidom import parse


# search the tree for an element with a particular class

def findelement(current, classtofind, topnode = None):
if topnode == None: topnode = current



# if it's an xml element...
if current.nodeType == 1:
print current.nodeName, ':', current.getAttribute('class')
if current.getAttribute('class') == classtofind:
print 'Returning node:', current
return current
elif current.hasChildNodes():
findelement(current.firstChild, classtofind, topnode)
elif current.nextSibling:
findelement(current.nextSibling, classtofind, topnode)

elif (current.parentNode != topnode) \

 and (current.parentNode.nextSibling != None):

findelement(current.parentNode.nextSibling, classtofind,
topnode)
else:

print 'Returning None...'

return None

# others (text, comment, etc)

else:

if current.nextSibling:

findelement(current.nextSibling, classtofind, topnode)

elif (current.parentNode != topnode) \

 and (current.parentNode.nextSibling != None):

findelement(current.parentNode.nextSibling, classtofind,
topnode)
else:

print 'Returning None...'

return None



# parse the document

blog = parse('/home/noah/dev/blog/template.html')



# find a post

postexample = findelement(blog.documentElement, 'post')



print 'Got node:   ', postexample

-

My output is this:

-
html :
head :
title :
body :
h1 :
ul :
li :
h2 :
ol :
li : post
Returning node: DOM Element: li at -0x48599c74
Got node:None
-

The function finds the right element fine, and says it will return DOM
Element: li at -0x48599c74, but the program gets None instead.  What's
happening here?  Any suggestions?

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


Re: Arguments for button command via Tkinter?

2005-10-31 Thread Steve Holden
Francesco Bochicchio wrote:
 Il Mon, 31 Oct 2005 06:23:12 -0800, [EMAIL PROTECTED] ha scritto:
 
 
And yet the stupidity continues, right after I post this I finnally
find an answer in a google search, It appears the way I seen it is to
create a class for each button and have it call the method within that.
If anyone else has any other ideas please tell.
 
 
 This is  how I do it: Supposing I have three buttons b1, b2 and b3, and I
 want for each button to call the same callback with, as argument, the
 button itself:
 
 
 def common_callback(button):
   # callback code here
 
 
 class CallIt(objetc):
   def __init__(function, *args ):
   self.function, self.args = function, args
   def __call__(self, *ignore):
   self.function(button, *self.args)
 
 b1['command']= CallIt(common_callback, b1)
 b2['command']= CallIt(common_callback, b2)
 b3['command']= CallIt(common_callback, b3)
 
 This way you need only one class (a sort of custom callable) and
 its instances gets called by Tkinter and in turn calls your
 callback with the proper arguments.
 
I don't see why this is preferable to having the callback as a bound 
method of the button instances. What's the advantage here? It looks 
opaque and clunky to me ...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Function returns none

2005-10-31 Thread Carsten Haese
On Mon, 2005-10-31 at 14:12, [EMAIL PROTECTED] wrote:
 I'm trying to write a website updating script, but when I run the
 script, my function to search the DOM tree returns None instead of what
 it should.
 
 I have this program:
 
 import sys
 from xml.dom.minidom import parse
 
 
 # search the tree for an element with a particular class
 
 def findelement(current, classtofind, topnode = None):
 if topnode == None: topnode = current
 
 
 
 # if it's an xml element...
 if current.nodeType == 1:
 print current.nodeName, ':', current.getAttribute('class')
 if current.getAttribute('class') == classtofind:
 print 'Returning node:', current
 return current
 elif current.hasChildNodes():
 findelement(current.firstChild, classtofind, topnode)
 elif current.nextSibling:
 findelement(current.nextSibling, classtofind, topnode)
 
 elif (current.parentNode != topnode) \
 
  and (current.parentNode.nextSibling != None):
 
 findelement(current.parentNode.nextSibling, classtofind,
 topnode)
 else:
 
 print 'Returning None...'
 
 return None
 
 # others (text, comment, etc)
 
 else:
 
 if current.nextSibling:
 
 findelement(current.nextSibling, classtofind, topnode)
 
 elif (current.parentNode != topnode) \
 
  and (current.parentNode.nextSibling != None):
 
 findelement(current.parentNode.nextSibling, classtofind,
 topnode)
 else:
 
 print 'Returning None...'
 
 return None
 
 
 
 # parse the document
 
 blog = parse('/home/noah/dev/blog/template.html')
 
 
 
 # find a post
 
 postexample = findelement(blog.documentElement, 'post')
 
 
 
 print 'Got node:   ', postexample
 
 -
 
 My output is this:
 
 -
 html :
 head :
 title :
 body :
 h1 :
 ul :
 li :
 h2 :
 ol :
 li : post
 Returning node: DOM Element: li at -0x48599c74
 Got node:None
 -
 
 The function finds the right element fine, and says it will return DOM
 Element: li at -0x48599c74, but the program gets None instead.  What's
 happening here?  Any suggestions?

You have a lot of cases where findelement is called recursively and then
its return value is discarded instead of being turned into a return
value to the caller. In those cases, execution simply falls off the end
of the function and None is returned implicitly (and silently, since you
don't have a print Returning None at the end of the function).

HTH,

Carsten.


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


Re: Microsoft Hatred FAQ

2005-10-31 Thread David Schwartz

Mike Meyer [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 Microsoft's behavior consisted of arguments, that is, did not
 involve force, the threat of force, fraud, or the threat of
 fraud. This is perhaps the most vital distinction that there is.

 Wrong. Either your definition of force is to narrow, or you're wrong
 that it's the distinction is even vaguely vital. If I convince
 everyone who might make food available to you not to do so - for
 example, by paying them more than their interaction with you is worth
 to them, I can starve you to death. I'd say I've used force against
 you - an economic force.

Right, you would say that, because you don't see the difference between 
guns and arguments.

 This is the kind of force that MS wields
 illegally. I'm willing to admit this isn't a usual definition of
 force, and won't argue if you want to say that it isn't force. But in
 that case, the fact that I didn't use force against you is
 irrelevant to you - you're just as dead.

No, it is completely relevant. You are trying to say the means don't 
matter if the same end is achieved. But if you're going to say that, you 
might as well say there's no difference between shooting someone and letting 
them die of natural causes.

But you are completely and utterly wrong. Civilized interactions between 
men consist of prohibiting certain *means*, not prohibiting certain ends.

DS


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


Re: Oh what a twisted thread we weave....

2005-10-31 Thread GregM
Tom,

Thanks for the reply and sorry for the delay in getting back to you.
Thanks for pointing out my logic problem. I had added the 2nd part of
the if statement at the last minute...

Yes I have a single threaded version its several hundred lines and uses
COM to write the results out to and Excel spreadsheet.. I was trying to
better understand threading and queues before I started hacking on my
current code... maybe that was a mistake... hey I'm still learning and
I learn a lot just by reading stuff posted to this group. I hope at
some point I can help others in the same way.

Here are the relevent parts of the code (no COM stuff)

here is a summary:
# see if url exists
# if exists then
#   hit page
#   get text of page
#   see if text of page contains search terms
#   if it does then
#   update appropiate counters and lists
#   else update static line and do the next one
# when done with Links list
#   - calculate totals and times
#   - write info to xls file
# end.

# utils are functions and classes that I wrote
# from utils import PrintStatic, HttpExists2
#
# My version of 'easyExcel' with extentions and improvements.
# import excelled
import urllib2
import time
import socket
import os
#import msvcrt # for printstatic
from datetime import datetime
import pythoncom
from sys import exc_info, stdout, argv, exit

# search terms to use for matching.
#primarySearchTerm = 'Narrow your'
ST_lookingFor = 'Looking for Something'
ST_errorConnecting = 'there has been an error connecting'
ST_zeroMatch = 'You found 0 products'
ST_zeroMatch2 = 'There are no products matching your selection'

#initialize Globals
timeout = 90# sets timeout for urllib2.urlopen()
failedlinks = []# list for failed urls
zeromatch = []  # list for 0 result searches
pseudo404 = []  # list for shop.com 404 pages
t = 0   # used to store starting time for 
getting a page.
count = 0   # number of tests so far
pagetime = 0# time it took to load page
slowestpage = 0 # slowest page time
fastestpage = 10# fastest page time
cumulative = 0  # total time to load all pages (used to calc. 
avg)

#version number of the program
version = 'B2.9'

def ShopCom404(testUrl):
 checks url for shop.com 404 url
shop.com 404 url -- returns status 200
http://www.shop.com/amos/cc/main/404/ccsyn/260

if '404' in testUrl:
return True
else:
return False

# main program #

try:
links = open(testfile).readlines()
except:
exc, err, tb = exc_info()
print 'There is a problem with the file you specified. Check the file
and re-run the program.\n'
#print str(exc)
print str(err)
print
exit()

# timeout in seconds
socket.setdefaulttimeout(timeout)
totalNumberTests = len(links)
print 'URLCheck ' + version + ' by Greg Moore (c) 2005 Shop.com\n\n'
# asctime() returns a human readable time stamp whereas time() doesn't
startTimeStr = time.asctime()
start = datetime.today()
for url in links:
count = count + 1
#HttpExists2 - checks to see if URL exists and detects redirection.
# handles 404's and exceptions better. Returns tuple depending on
results:
# if found: true and final url. if not found: false and attempted url
pgChk = HttpExists2(url)
if pgChk[0] == False:
#failed url Exists
failedlinks.append(pgChk[1])
elif ShopCom404(pgChk[1]):
#Our version of a 404
pseudo404.append(url)
if pgChk[0] and not ShopCom404(url):
#if valid page not a 404 then get the page and check it.
try:
t = time.time()
urlObj = urllib2.urlopen(url)
pagetime = time.time() - t
webpg = urlObj.read()
if (ST_zeroMatch in self.webpg) or (ST_zeroMatch2 in 
self.webpg):
zeromatch.append(url)
elif ST_errorConnecting in webpg:
# for some reason we got the error page
# so add it to the failed urls
failmsg = 'Error Connecting Page with: ' + url
failedlinks.append(failmsg)
except:
print 'exception with: ' + url
#figure page times
cumulative += pagetime
if pagetime  slowestpage:
slowestpage = pagetime, url.strip()
elif pagetime  fastestpage:
fastestpage = pagetime, url.strip()
msg = 'testing ' + str(count) + ' of ' + str(totalNumberTests) + \
'. Currnet runtime: ' 

Re: Rename files with numbers

2005-10-31 Thread Micah Elliott
On Oct 31, [EMAIL PROTECTED] wrote:
 ...
 obs: the file names came this way(with spaces or apostrophes) from
 the cd i imported.

So remove them first.  Here's a possible solution::

#! /usr/bin/env python

import glob, os.path

uglies = glob.glob(*.mp3)
print 'uglies:', uglies
pretties = []

for ugly in uglies:
song, ext = os.path.splitext(ugly)
song = song.replace(', )
song = song.replace( , _)
song = song.title()
song = The_Beatles_-_ + song[3:]
song_ext = song + ext
pretties.append(song_ext)

print 'pretties:', pretties 

# rename uglies to pretties...

-- 
_ _ ___
|V|icah |- lliott  http://micah.elliott.name  [EMAIL PROTECTED]
  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Asyncore Loop Question

2005-10-31 Thread Steve Holden
John W wrote:
 Hello,
 
 I have a gui application where I am trying to use the asyncore module to
 gather data from other computers. I am able to connect, but I am getting
 constant handle_write_event method calls into my application. It is
 obviously slowing down the gui processing significantly.
 
 My understanding is that the handle_write_event and handle_read_event are
 both edge notifications and I should just get the method call essentially
 just once.
 
 I think the problem is how I have my loop() call configured. All I am trying
 to do with the code below is to open the socket (that works) and then
 receive a single handle_write_event method call. Instead, I am getting
 constantly barraged with them.
 
 I have tried several different types of the loop() call (using poll,
 timeout...) but with no luck. If anyone can explain what I should be doing
 to get a single handle_write_event call until I actually write something to
 the socket (which my code is not presently doing yet), I would appreciate
 
 Below is some code showing what I am doing:
 
 --
 class Connection(asyncore.dispatcher):
 def __init__ (self, server_name, port_num ):
 self.message_queue = []
 
 asyncore.dispatcher.__init__(self)
 self.create_socket( socket.AF_INET, socket.SOCK_STREAM )
 self.connect(( server_name, port_num ))
 
 
 def handle_read_event( self ):
 print handle_read_event received
 
 
 def handle_write_event( self ):
 print Asking for a write
 
 if len( self.message_queue )  0:
 # Pop the first message off the queue
 self.send_next_message()
 
 
 class TestApp:
 def __init__( self, server_name, port_number ):
 
 self.nomad = Connection( server_name, port_number )
 asyncore.loop()
 
 
 Output ends up being a constant stream of:
 Asking for a write
 Asking for a write
 Asking for a write
 Asking for a write
 Asking for a write
 
 ...
 ...
 
 
Normally if a socket channel asks for a write and you have no data you 
should respond by removing it from the list of write-enabled channels 
for the asyncore loop until you *do* have some data for it. Otherwise 
every time the loop scans the channels expecting notification it will 
tell you again that you can write to that channel.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


frozenset/subclassing/keyword args

2005-10-31 Thread Mark E. Fenner
Hello all,

I was migrating some code from sets.ImmutableSet to frozenset and noticed
the following:

**code
#!/usr/bin/env python

from sets import ImmutableSet


class MSet1(ImmutableSet):
def __init__(self, iterArg, myName=foo):
ImmutableSet.__init__(self, iterArg)
self.name = myName


class MSet2(frozenset):
def __init__(self, iterArg, myName=foo):
frozenset.__init__(self, iterArg)
self.name = myName


m1 = MSet1([1,2,3], myName = donkey)
print m1
print m1.name

m2 = MSet2([1,2,3], myName = kong)
print m2
print m2.name
*end code**

*run**
MSet1([1, 2, 3])
donkey
Traceback (most recent call last):
  File ./setTest.py, line 22, in ?
m2 = MSet2([1,2,3], myName = kong)
TypeError: frozenset() does not take keyword arguments
*end run

I'm missing something and couldn't find it in the docs.

Speaking of which, in the docs at the bottom of the description of the
builtin set/frozenset, there is a link to a page describing differences
between the builtin sets and the sets module sets.  This link is broken
locally and on the python.org docs.
Locally, it reads:
file:///usr/share/doc/python-docs-2.4.2/html/lib/module-comparison-to-builtin-set.html

While it should read:
file:///usr/share/doc/python-docs-2.4.2/html/lib/comparison-to-builtin-set.html

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


Re: Function returns none

2005-10-31 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 I'm trying to write a website updating script, but when I run the
 script, my function to search the DOM tree returns None instead of what
 it should.

When you call findelement() recursively you have to return the value from the 
recursive call to the next caller up. See example below.

Kent

 
 I have this program:
 
 import sys
 from xml.dom.minidom import parse
 
 
 # search the tree for an element with a particular class
 
 def findelement(current, classtofind, topnode = None):
 if topnode == None: topnode = current
 
 
 
 # if it's an xml element...
 if current.nodeType == 1:
 print current.nodeName, ':', current.getAttribute('class')
 if current.getAttribute('class') == classtofind:
 print 'Returning node:', current
 return current
 elif current.hasChildNodes():
 findelement(current.firstChild, classtofind, topnode)

Should be
  return findelement(current.firstChild, classtofind, topnode)
and similarly wherever you call findelement().

 elif current.nextSibling:
 findelement(current.nextSibling, classtofind, topnode)
 
 elif (current.parentNode != topnode) \
 
  and (current.parentNode.nextSibling != None):
 
 findelement(current.parentNode.nextSibling, classtofind,
 topnode)
 else:
 
 print 'Returning None...'
 
 return None
 
 # others (text, comment, etc)
 
 else:
 
 if current.nextSibling:
 
 findelement(current.nextSibling, classtofind, topnode)
 
 elif (current.parentNode != topnode) \
 
  and (current.parentNode.nextSibling != None):
 
 findelement(current.parentNode.nextSibling, classtofind,
 topnode)
 else:
 
 print 'Returning None...'
 
 return None
 
 
 
 # parse the document
 
 blog = parse('/home/noah/dev/blog/template.html')
 
 
 
 # find a post
 
 postexample = findelement(blog.documentElement, 'post')
 
 
 
 print 'Got node:   ', postexample
 
 -
 
 My output is this:
 
 -
 html :
 head :
 title :
 body :
 h1 :
 ul :
 li :
 h2 :
 ol :
 li : post
 Returning node: DOM Element: li at -0x48599c74
 Got node:None
 -
 
 The function finds the right element fine, and says it will return DOM
 Element: li at -0x48599c74, but the program gets None instead.  What's
 happening here?  Any suggestions?
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: frozenset/subclassing/keyword args

2005-10-31 Thread Kent Johnson
Mark E. Fenner wrote:
 Speaking of which, in the docs at the bottom of the description of the
 builtin set/frozenset, there is a link to a page describing differences
 between the builtin sets and the sets module sets.  This link is broken
 locally and on the python.org docs.
 Locally, it reads:
 file:///usr/share/doc/python-docs-2.4.2/html/lib/module-comparison-to-builtin-set.html
 
 While it should read:
 file:///usr/share/doc/python-docs-2.4.2/html/lib/comparison-to-builtin-set.html

A little further down the page it says See About this document... for 
information on suggesting changes. If you click the link there it will tell 
you how to submit a doc bug which is the best way to get this fixed.

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


Re: Function returns none

2005-10-31 Thread noahlt
Thanks, that worked!

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


Re: Asyncore Loop Question

2005-10-31 Thread John W
Steve,

Ar you saying that I should close the connection until I have data to
write? Or should I be using the readable and writable methods to
turn it off?

Thanks for your help, unfortunatly, I have struggled with the
documentation and getting a clear understanding of everything.
This is my first socket program as well.

Thanks,

JohnOn 10/31/05, Steve Holden [EMAIL PROTECTED] wrote:
John W wrote: Hello, I have a gui application where I am trying to use the asyncore module to gather data from other computers. I am able to connect, but I am getting constant handle_write_event method calls into my application. It is
 obviously slowing down the gui processing significantly. My understanding is that the handle_write_event and handle_read_event are both edge notifications and I should just get the method call essentially
 just once. I think the problem is how I have my loop() call configured. All I am trying to do with the code below is to open the socket (that works) and then receive a single handle_write_event method call. Instead, I am getting
 constantly barraged with them. I have tried several different types of the loop() call (using poll, timeout...) but with no luck. If anyone can explain what I should be doing to get a single handle_write_event call until I actually write something to
 the socket (which my code is not presently doing yet), I would appreciate Below is some code showing what I am doing: --
 class Connection(asyncore.dispatcher): def __init__ (self, server_name, port_num ): self.message_queue = [] asyncore.dispatcher.__init__(self) self.create_socket( socket.AF_INET
, socket.SOCK_STREAM ) self.connect(( server_name, port_num )) def handle_read_event( self ): print handle_read_event received def handle_write_event( self ):
 print Asking for a write if len( self.message_queue )  0: # Pop the first message off the queue self.send_next_message() class TestApp: def __init__( self, server_name, port_number ):
 self.nomad = Connection( server_name, port_number ) asyncore.loop() Output ends up being a constant stream of: Asking for a write Asking for a write Asking for a write
 Asking for a write Asking for a write  ... ...Normally if a socket channel asks for a write and you have no data youshould respond by removing it from the list of write-enabled channels
for the asyncore loop until you *do* have some data for it. Otherwiseevery time the loop scans the channels expecting notification it willtell you again that you can write to that channel.regardsSteve
--Steve Holden +44 150 684 7255+1 800 494 3119Holden
Web
LLC
www.holdenweb.comPyCon TX
2006www.python.org/pycon/--http://mail.python.org/mailman/listinfo/python-list

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

Re: Scanning a file

2005-10-31 Thread Paul Watson
Steve Holden wrote:
 Since everyone needs this, how about building it in such that files 
 which are closed by the runtime, and not user code, are reported or 
 queryable?  Perhaps a command line switch to either invoke or suppress 
 reporting them on exit.

 This is a rather poor substitute from correct program design and 
 implementation. It also begs the question of exactly what constitutes a 
 file. What about a network socket that the user has run makefile() on? 
 What about a pipe to another process? This suggestion is rather 
 ill-defined.
 
 Is there any facility for another program to peer into the state of a 
 Python program?  Would this be a security problem?
 
 It would indeed be a security problem, and there are enough of those 
 already without adding more.
 
 regards
  Steve

All I am looking for is the runtime to tell me when it is doing things 
that are outside the language specification and that the developer 
should have coded.

How ill will things be when large bodies of code cannot run 
successfully on a future version of Python or a non-CPython 
implementation which does not close files.  Might as well put file 
closing on exit into the specification.

The runtime knows it is doing it.  Please allow the runtime to tell me 
what it knows it is doing.  Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rename files with numbers

2005-10-31 Thread dudufigueiredo
Micah, thanks a lot,
but my focus is to learn how to acess a folder and rename all files in
this folder.

Somyhing like this:
def renamer(folder, band):
folder = #place to act
archive = #file to transform
rest = archive[3:]
print band +  -, rest.capitalize()

And than just do this:

renamer('C:\My Shared Folder\Rubber Soul', 'The Beatles')

And than pyhton alter all files in my folder. Is it possible?

I'm a beginer, for now, i just want to let the spaces and apostrophes
as they are...

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


Re: Microsoft Hatred FAQ

2005-10-31 Thread Mike Meyer
David Schwartz [EMAIL PROTECTED] writes:
 Mike Meyer [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 Microsoft's behavior consisted of arguments, that is, did not
 involve force, the threat of force, fraud, or the threat of
 fraud. This is perhaps the most vital distinction that there is.
 Wrong. Either your definition of force is to narrow, or you're wrong
 that it's the distinction is even vaguely vital. If I convince
 everyone who might make food available to you not to do so - for
 example, by paying them more than their interaction with you is worth
 to them, I can starve you to death. I'd say I've used force against
 you - an economic force.
 Right, you would say that, because you don't see the difference between 
 guns and arguments.

Except I'm willing to allow your definition. All it takes is reading
the next paragraph for you to see that.

Of course, you've dropped the real point, which is your own inabillity
to distinguish between, as you put it, guns and arguments. You
always act as if every mention of a crime committed by someone other
than microsoft involved guns, even when most of them don't. You have
as yet to offer any explanation for that other than that you're
following MS's orders.

 This is the kind of force that MS wields
 illegally. I'm willing to admit this isn't a usual definition of
 force, and won't argue if you want to say that it isn't force. But in
 that case, the fact that I didn't use force against you is
 irrelevant to you - you're just as dead.
 No, it is completely relevant. You are trying to say the means don't 
 matter if the same end is achieved. But if you're going to say that, you 
 might as well say there's no difference between shooting someone and letting 
 them die of natural causes.

Another straw man argument. I'm not trying to say anything of the
sort.

mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


yapsnmp - on windows

2005-10-31 Thread py
I have installed net-snmp and of course python on windows xp.  I
downloaded yapsnmp (http://yapsnmp.sourceforge.net/) and I can't seem
to use it.  It has a swig interface...but I get errors when trying to
swig it..

C:\yapsnmp-0.7.8\srcc:\Program Files\swigwin-1.3.25\swig.exe -python
net-snmp.i
net-snmp.i(29): Error: Unable to find 'asn1.h'
net-snmp.i(30): Error: Unable to find 'snmp_api.h'
net-snmp.i(31): Error: Unable to find 'snmp.h'
net-snmp.i(32): Error: Unable to find 'snmp_client.h'
net-snmp.i(33): Error: Unable to find 'mib.h'
net-snmp.i(34): Error: Unable to find 'default_store.h'

C:\yapsnmp-0.7.8\src

...Any ideas?  Anyone have this working on windows?

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


Re: Recursive generators and backtracking search

2005-10-31 Thread Tim Peters
[Talin]
 I've been using generators to implement backtracking search for a while
 now. Unfortunately, my code is large and complex enough (doing
 unification on math expressions) that its hard to post a simple
 example. So I decided to look for a simpler problem that could be used
 to demonstrate the technique that I am talking about.

 I noticed that PEP 255 (Simple Generators) refers to an implementation
 of the 8 Queens problem in the lib/test directory. Looking at the
 code, I see that while it does use generators, it doesn't use them
 recursively.

In context, the N-Queens and MxN Knight's Tour solvers in
test_generators.py are exercising the conjoin() generators in that
file.  That's a different approach to backtracking search, with some
nice features too:  (1) it uses heap space instead of stack space;
and, (2) it's easy to run entirely different code at different levels
of the search.  #2 isn't well-illustrated by the N-Queens solver
because the problem is so symmetric, although it is used to give the
code for each row its own local table of the board lines used by the
squares in that row.  That in turn is a major efficiency win.  The
Knight's Tour solver makes more obvious use of #2, by, e.g., running
different code for the first square than for the second square
than for the last square than for all the other squares.  That
doesn't require any runtime test-and-branch'ing in the search code,
it's set up once at the start in the list of M*N generators passed to
conjoin() (each square gets its own generator, which can be customized
in arbitrary ways, in advance, for that square).

 As an alternative, I'd like to present the following implementation. If
 you compare this one with the one in lib/test/test_generator.py you
 will agree (I hope) that by using recursive generators to implement
 backtracking, the resulting code is a little more straightforward and
 intuitive:

Since straightfoward and intuitive weren't the goals of the
test_generators.py implementations, that's not too surprising ;-)

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


Re: Microsoft Hatred FAQ

2005-10-31 Thread David Schwartz

Mike Meyer [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 Of course, you've dropped the real point, which is your own inabillity
 to distinguish between, as you put it, guns and arguments. You
 always act as if every mention of a crime committed by someone other
 than microsoft involved guns, even when most of them don't. You have
 as yet to offer any explanation for that other than that you're
 following MS's orders.

Your sole evidence for this claim is that I once equated theft with 
force. Yes, you are correct that it's possible to steal something without 
using force. Even in this case, from context, it was quite clear that 
forceful theft was intended.

There is a fundamental category difference between the fundamental 
inter-personal wrongs of force and fraud and every other invented wrong. 
People are making a concerted attempt in this thread to obliterate that 
distinction, and I include you in those making that attempt.

The *only* motive I have ever seen to obliterate that distinction is to 
justify responding to arguments with bullets. And that is precisely what you 
advocate. Quoting you:

 If I convince
 everyone who might make food available to you not to do so - for
 example, by paying them more than their interaction with you is worth
 to them, I can starve you to death. I'd say I've used force against
 you - an economic force.

Your convincing and paying is an argument. It's in no way analogous to, 
for example, hiring someone to kill me (wherein force is actually used). 
Certainly if I did starve you by force, you would be justified in responding 
with force, that is, with bullets if needed, to defend your life.

What possible motive is there for making an argument like this other 
than to justify the use of guns in response to arguments? That's why you 
need to equate metaphorical market force with *real* force. But there is 
no more important distinction in the world.

Again, I utterly reject your argument. The use of actual force is 
justified only in response to force, fraud, or things that *really* are 
force.

 I'm willing to admit this isn't a usual definition of
 force, and won't argue if you want to say that it isn't force.

The point is not whether you call it force or not. The point is whether 
you believe it justifies the use of force in retaliation. There is no 
difference between someone who says while arguments aren't force, it's okay 
to respond to them with force and someone who says arguments are force so 
it's okay to respond to them with force.

The premise I utterly and totally reject is that good arguments, shrewd 
negotiations, and anything else that is not actual force, not fraud, not 
inducing others to use force, or anything like that are somehow the same as 
real force. You have an obligation not to use actual force against other 
people, you have an obligation in a negotiation not to misrepresent your 
product to induce a payment, and failing in these obligations are serious 
wrongs. But they are in no way comparable to trying to get what something is 
worth. They are in no way comparable to persuasive negotiations.

This point transcends the issue of Microsoft. I would make this same 
argument regardless of whose non-force were claimed to justify a forceful 
retaliation. (And have done so consistently.)

DS


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


  1   2   >