Re: adding a new line of text in Tk

2006-03-26 Thread Ben Cartwright
nigel wrote:
 w =Label(root, text=Congratulations you have made it this far,just a few more
 questions then i will be asking you some)

 The problem i have is where i have started to write some textCongratulations
 you have made it this far,just a few more questions then i will be asking you
 some)
 I would actually like to add some text but it puts it all on one line.I would
 like to be able to tell it to start a new line.


Just use \n in your string, e.g.:

w = Label(root, text=Line 1\nLine 2\nLine 3)

Or a triple-quoted string will do the trick:

w = Label(root, text=Line 1
Line 2
Line 3)

--Ben

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


Re: SSH, remote login, and command output

2006-03-26 Thread Spire 01

Greetings!

I'm working on a Python program for a small LAN of Linux systems running 
Gentoo, and I need a little help figuring out what I need to do it.  So what 
I'd like to do is, from any given computer, log on to every other computer, 
run a certain command (which normally outputs text to the terminal), and 
store the output so I can use the aggregate statistics later in the program. 
 I would normally something along the lines of SSH to do it, but I don't 
know what I would need to pull that off in Python.  There's also one 
complication: the systems could be Gentoo systems, or they could be logged 
into Windows since they're dual booted.  Considering all of this, can anyone 
give me some recommendation as to what library I should learn how to use to 
pull this off? I admit, I haven't done too much in the way of networks, but 
if someone can tell me what I need to do remote logins in this way, I'll do 
what I can to make it work.


Thanks a million!
Spire

_
Is your PC infected? Get a FREE online computer virus scan from McAfee® 
Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963


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

Re: detecting drives for windows and linux

2006-03-26 Thread Fulvio

Alle 03:17, domenica 26 marzo 2006, BWill ha scritto:
 Hi, I'm writing a file browser, but I'm not sure how I could go about
 detecting the drives available

I was just asking a similar question some days back. I'm planning to try a file catalogger.
I just remember something about Win32API, but I didn't find anything on the linux side.
Frankly I got some curious info that concerns 'Bacula', disk backup. And a part of it is use to browse and catalog file.

I think we should read some line of code on that program.

F

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

Re: Comparisons and singletons

2006-03-26 Thread David Isaac
Alan asked:
  2. If I really want a value True will I ever go astray with the test:
  if a is True:
   a = True
   b = 1.
   c = 1
   a is True, b is True, c is True
  (True, False, False)

Ziga Seilnacht [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 I think that True and False, although they were added in version
 2.3, were not true singeltons until version 2.4.

OK, but Python 2.3 yields the same result as above.

Ziga  wrote:
 You should finish
 reading the PEP, see especially this part:
 - Don't compare boolean values to True or False using ==
 Yes:   if greeting:
 No:if greeting == True:
 Worse: if greeting is True:


I do not think this is relevant to the question I asked,
which was how to test for a value of True, if that's
what I really want.  I think the outcome of this
discussion has been: use 'is'.

Thanks,
Alan


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


Re: Extending Methods Vs Delegates

2006-03-26 Thread vbgunz
I am sorry I couldn't reply sooner! Alex, Python in a nutshell is my
bible and I take it virtually everywhere! Seriously, I would highly
recommend it to anyone with a little to a lot of Python experience.

I apologize for misinterpreting your passage on page 80. I will look
much closer at your examples, links and ideas and I hope to straighten
my knowledge on the subject of delegates!

Thank you for hinting on the Template Method design pattern! Sorry
for any misunderstanding!

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


Re: Extending Methods Vs Delegates

2006-03-26 Thread Sybren Stuvel
vbgunz enlightened us with:
 I hope I've made some sense with this question. I ultimately wish to
 know just one real thing. Regardless of the name of the second
 example above, what is the purpose of calling a sub class method
 from a super class instance? What is the application to such a
 design?

I've seen this style of programming before, in wxWidgets. The
constructor of a class does various things. This is roughly what
happens:

class wxSomeClass(wxParent):
def __init__(self, *args, **kwargs):
# Do various things

if not self.OnInit():
raise RuntimeError(Initialization failed)

# Do other things that need to be done after custom
# initialization

def OnInit(self):
return True

This makes it easier to simply provide custom initialization, without
having to redo everything in __init__. Calling the superclass'
function is fine if you want to add behaviour before and/or after
calling it. This example however lets you customize behaviour that's
put in the middle of the __init__ function.

 Maybe an example will help?

I hope so :)

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: SSH, remote login, and command output

2006-03-26 Thread Sybren Stuvel
Spire 01 enlightened us with:
 So what I'd like to do is, from any given computer, log on to every
 other computer, run a certain command (which normally outputs text
 to the terminal), and store the output so I can use the aggregate
 statistics later in the program. 

I'd go for SSH indeed.

 I would normally something along the lines of SSH to do it, but I
 don't know what I would need to pull that off in Python.

Easiest way would be the popen2 module.

 There's also one complication: the systems could be Gentoo systems,
 or they could be logged into Windows since they're dual booted.

Then install Cygwin on the windows systems, and run the OpenSSH daemon
there 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: SSH, remote login, and command output

2006-03-26 Thread Rob Williscroft
Spire 01 wrote in
news:[EMAIL PROTECTED] in
comp.lang.python: 

 Greetings!
 
 I'm working on a Python program for a small LAN of Linux systems
 running Gentoo, and I need a little help figuring out what I need to
 do it.  So what I'd like to do is, from any given computer, log on to
 every other computer, run a certain command (which normally outputs
 text to the terminal), and store the output so I can use the aggregate
 statistics later in the program. 
   I would normally something along the lines of SSH to do it, but I
   don't 
 know what I would need to pull that off in Python.  There's also one 
 complication: the systems could be Gentoo systems, or they could be
 logged into Windows since they're dual booted.  Considering all of
 this, can anyone give me some recommendation as to what library I
 should learn how to use to pull this off? I admit, I haven't done too
 much in the way of networks, but if someone can tell me what I need to
 do remote logins in this way, I'll do what I can to make it work.
 

I found this:

http://pyssh.sourceforge.net/

which may be able to help you script ssh, alternativly use the
subprocess module:

http://docs.python.org/dev/lib/module-subprocess.html

and translate however you would normaly script ssh.

To connect to windows, you could install:

http://sshwindows.sourceforge.net/

on your windows clients, but IIRC its win2K, XP only, or you 
could use cygwin (which the above is taken from).

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pondering about the essence of types in python

2006-03-26 Thread gangesmaster
i dont think it's possible, to create proxy classes, but even if i did,
calling remote methods with a `self` that is not an instance of the
remote class would blow up.


-tomer

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


Slogan

2006-03-26 Thread Paddy
In the style of the Pepsi 'Lip smakin' add of the 70's...

  In-dentin
  easy-readin
  object-orientin
  motivatin
  good buzzin
  literate programmin'
  abstractin
  fast runnin
  ever givin
  dynamic
  PYTHON!

- I know, too much free time can be harmful ;-)

- Pad.

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


Re: detecting drives for windows and linux

2006-03-26 Thread Max
BWill wrote:

 oh, I wasn't expecting a single solution for both platforms, just some 
 good solutions
 
 thanks

Are you aware that this idea is somewhat foreign to Linux? (Maybe you 
are and want to do it anyway?) Linux puts the whole file system 
(including mounted iPods, ISOs and NTFS drives) in one hierarchy.

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


Re:using else: interactive programme

2006-03-26 Thread nigel
Hello i will show you a short  example of my programme.
s = raw_input (ok lets see about doing some mathematics would you like to try 
some?)
if s=='no':
print Well you aint no fun sling your hook
print END OF PROGRAMME
print Go on sling your hook
print Now let some one else have a go
if s=='yes':
print brilliant lets get cracking
print We will start with some easy sums progressing to professor 
standard
s = raw_input()
s = raw_input (5 + 5 =)
if s=='10':
print Correct
 else:
print you are not very smart it would seem 
print Or maybe you are just taking the piss if so behave
print Are you ready to continue
if s=='no':
print Then go away
if s=='yes':
s = raw_input (5 + 5 =)
if s=='10':
print Well done
else:
print tut tut lets try some thing else

The problem being my programme will not run,I believe it is because i have 
missused else: can some one please give me an example of how to correct 
this.Just to recap the programme runs fine until i get to.
  print well done I was under the impression that by using else: if the 
wrong answer was typed it would print tut tut lets try some thing else
Any thought on this please.
Thanks nige.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using else: interactive programme

2006-03-26 Thread nikie
I guess the indention got mixed up in your post, if I try to run it, I
get error messages at each of the else: lines, because they're
mis-indented.
else should be indented like the if it belongs to, e.g (using
underscores for spaces):
if s=='10':
print well done
else:
print something else
Make sure you're using tabs/spaces consistently across the whole file,
too.
If I indent the else clauses correctly, I can run your script and it
behaves the way you expeced.

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


Re: image reduction script

2006-03-26 Thread Philippe Martin
Thanks, 

I'll give it a shot.

Philippe



Kamilche wrote:

 
 To reduce the color depth of an image in PIL:
 im = im.convert(mode=P, palette=Image.ADAPTIVE)

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


Re: What's The Best Editor for python

2006-03-26 Thread [EMAIL PROTECTED]
For myself, I use kdevelop, KDE's development environment, it handles a
multitude of languages very well, and python is one of them.  It has
solid project management, and a slew of other features.  If you are
looking for something solid, I would go with kdevelop.

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


Re: pondering about the essence of types in python

2006-03-26 Thread Alan Franzoni
gangesmaster on comp.lang.python said: 

 TypeError: unbound method __init__() must be called with z instance as
 first argument (got x instance instead)
 ==
 
 and the question is -- WHY?

I think the answer would be: because it's an instance method. Its
'contract' it's to be bound to an object of a certain class. Would you like
a different behaviour, you could decorate whatever method you need. I.e.,
turn your example into:

class z(object):
@staticmethod
def __init__(self):
self.blah=5

class x(object):
def __init__(self):
z.__init__(self)


y = x()


And this will work as you wish. You could have used classmethod as well
with a properly tuned init, of course.
 
 but __mro__ is a readonly attribute, and deriving from instances is
 impossible (conn.modules.wx.Frame is a PROXY to the class)...
 
 and again -- WHY? these all look like INTENTIONAL limitations. someone
 went around and added type checks (which are NOT pythonic) into the
 cPython implementation. argh. why do that?

I really think this happens because Python was designed to be
casualerror-safe. This approach would probably lead to many programming
errors. 

By the way, Python was designed to *discourage* such behaviours, not to
prevent them. By the way, I didn't grasp what you would really like to do.
You're saying you want to derive from instances, but then I see in your
sample code you're creating a *class* derived from an object (I would
expect you would like to derive an instance from an instance, and to
'twist' such new instance methods to your needs, which I think can be done
as well). What's the difference between that and the use of __class__ ?

class z(object):
@staticmethod
def __init__(self):
self.blah=5

@staticmethod
def met_stat(self):
pass

@classmethod
def met_cls(self):
pass

def met_inst(self):
pass



class x(object):
def __init__(self):
z.__init__(self)


y = x()


class q(y.__class__):
pass


r = q()


This work OK to me. Unless you want to do something like making y instance
attributes become q class attributes, or you would like to set y instance
attributes on all q instances, which could require a bit more of code but
surely can be done. This would mix up a bit the class vs instance
behaviour, though, e.g. changing a derived class instance attribute which
is inherited from a parent instance would lead to a global attribute
change, or would 'spawn' a new instance attribute for that particular
instance?

 def derive_from(obj):
 class cls(object):
 def __getattr(self, name):
 return getattr(obj, name)
 return cls

This seems to work for deriving read-only data from instances (no way to
write back data).
 
 check types. DONT. the whole point of duck-typing is you DONT CHECK THE
 TYPES. you just work with objects, and instead of TypeError you'd get
 AttribiuteError, which is much better.  AAARRGGGHH.

You don't HAVE TO check types if you don't want. Just use @staticmethod
everywhere in your classes. I mean, a METHOD is supposed to be
class-related, and it's often useful to have it as such, (unexpected errors
and behaviours might rise everywhere if not so), but you're never forced to
use that.


-- 
Alan Franzoni [EMAIL PROTECTED]
-
Togli .xyz dalla mia email per contattarmi.
Rremove .xyz from my address in order to contact me.
-
GPG Key Fingerprint:
5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E
-- 
http://mail.python.org/mailman/listinfo/python-list


wired md5 hashing problem

2006-03-26 Thread Matthias Güntert
Hello list-members

i am in the process of writing a python script to backup my data. Now I
would like to implement md5/sha1 hashes.  

# do md5 fingerprinting 
if config.get(global, crc) == md5:
m = md5.new()
# open the file 
f = open(fname, rb)
while 1:
block = f.read(1024*1024)
if not block:
break
# generate the hash
m.update(block)
f.close()
  
# write the results properly formated to a file
fd = file(fname + .md5, w)
fd.write(m.hexdigest())
fd.write(   + fname + \n)
fd.close()


[EMAIL PROTECTED]  md5sum -c backup.tar.bz2.md5   
/fileservice/temp/backup.tar.bz2: FAILED
md5sum: WARNING: 1 of 1 computed checksum did NOT match

[EMAIL PROTECTED]  cat backup.tar.bz2.md5 
d41d8cd98f00b204e9800998ecf8427e  /fileservice/temp/backup.tar.bz2

so the format should be okay, but whats wrong with my piece of code?!

Greetings

-- 
Mit freundlichen Grüßen

Matthias Güntert


signature.asc
Description: This is a digitally signed message part
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: wired md5 hashing problem

2006-03-26 Thread Felipe Almeida Lessa
Em Dom, 2006-03-26 às 16:56 +0200, Matthias Güntert escreveu:
 so the format should be okay, but whats wrong with my piece of code?!

It looks ok for me. What does md5sum gives as the sum?

-- 
Felipe.

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

Module documentation

2006-03-26 Thread Tony Burrows
Just getting to grips with Python, a great language BUT
With something like Java I can find the syntax of a method call with no
problems, how do I do the same with Python?

For example, using MySQLdb or SGMLParser I can see what the available
methods are with dir, but how do I find out what parameters are needed and
what they represent?

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


Re: Module documentation

2006-03-26 Thread Rene Pijlman
Tony Burrows:
With something like Java I can find the syntax of a method call with no
problems, how do I do the same with Python?

The basic syntax is just the name, with parameters in brakcets:

   object.method(par1, par2, ...)

This is explained in the documentation, of course.

how do I find out what parameters are needed and what they represent?

This is documented in the library reference:
http://docs.python.org/modindex.html

You can also query the module for its docstrings:

import os
help(os)
...
help(os.utime)
Help on built-in function utime in module nt:
...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Extending Methods Vs Delegates

2006-03-26 Thread Alex Martelli
vbgunz [EMAIL PROTECTED] wrote:

 I am sorry I couldn't reply sooner! Alex, Python in a nutshell is my
 bible and I take it virtually everywhere! Seriously, I would highly
 recommend it to anyone with a little to a lot of Python experience.
 
 I apologize for misinterpreting your passage on page 80. I will look
 much closer at your examples, links and ideas and I hope to straighten
 my knowledge on the subject of delegates!
 
 Thank you for hinting on the Template Method design pattern! Sorry
 for any misunderstanding!

Hey, no problem -- such a misunderstanding is always a shared
responsibility, and as an author I need to take my part of the blame.

Unfortunately, the root issue is that more and more common, ordinary,
useful English words get expropriated by specialized technical meanings,
making it almost impossible to discuss technical matters in ordinary
English without *some* risk of misunderstanding (by the reader
mistakenly seeing a specialized, technical meaning where the NORMAL
English use of the word, possibly in a slightly metaphorical vein, is
what the author meant).  From function and procedure, to delegate
and built-in, a growing number of words become risky!-)

Funny enough, the problem is worst in English - because in many other
languages, the specialized technical terms often use borrowed English
words, so the other language's native terms remain available.  Latin had
similar luck wrt Greek a couple millennia ago -- all technical terms of
philosophy were borrowed Greek words, so the risk of confusion was in
fact much lower than it was in Greek;-).


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


Re: detecting drives for windows and linux

2006-03-26 Thread Alex Martelli
Max [EMAIL PROTECTED] wrote:

 BWill wrote:
 
  oh, I wasn't expecting a single solution for both platforms, just some
  good solutions
  
  thanks
 
 Are you aware that this idea is somewhat foreign to Linux? (Maybe you
 are and want to do it anyway?) Linux puts the whole file system 
 (including mounted iPods, ISOs and NTFS drives) in one hierarchy.

Yes, but you may still want to distinguish (because, for example, hard
linking doesn't work across filesystems, and mv is not atomic then).

Running a df command is a good simple way to find out what drives are
mounted to what mountpoints -- the mount command is an alternative, but
its output may be slightly harder to parse than df's.


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


Re: Module documentation

2006-03-26 Thread Paul Boddie
Tony Burrows wrote:
 Just getting to grips with Python, a great language BUT
 With something like Java I can find the syntax of a method call with no
 problems, how do I do the same with Python?

 For example, using MySQLdb or SGMLParser I can see what the available
 methods are with dir, but how do I find out what parameters are needed and
 what they represent?

You can use the help function to get documentation on modules,
functions, classes and objects. For example:

import sgmllib
help(sgmllib) # gives lots of information on the entire module
help(sgmllib.SGMLParser) # gives information on the class
help(sgmllib.SGMLParser.__init__) # gives initialisation information

Unfortunately, because of the discrepancies between old-style and
new-style classes, you can't always get decent help on objects.
Consider this contrived example:

parser = sgmllib.SGMLParser() # you'd usually be using a subclass
help(parser) # gives information about class instance(object)

Compare this to what happens when you get help on a file object:

f = open(/etc/hosts)
help(f) # gives information about class file(object)

Personally, I feel that the whole new-style thing - making a class
which inherits from something called object (of all the names that
could have been chosen) - introduces a fair number of
implementation-level issues that should have been hidden at the level
of the language. I know that various other object-oriented languages
have object or Object as a root class, but it's a dubious
convention, unnecessary for the first seven or more years of Python's
public life, and perhaps a prime candidate for elimination in the
much-discussed-of-late Python 3000.

Paul

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


Re: Module documentation

2006-03-26 Thread Tony Burrows
On Sun, 26 Mar 2006 17:19:35 +0200, Rene Pijlman wrote:

 Tony Burrows:
With something like Java I can find the syntax of a method call with no
problems, how do I do the same with Python?
 
 The basic syntax is just the name, with parameters in brakcets:
 
object.method(par1, par2, ...)
 
 This is explained in the documentation, of course.
 
how do I find out what parameters are needed and what they represent?
 
 This is documented in the library reference:
 http://docs.python.org/modindex.html
 
 You can also query the module for its docstrings:
 
import os
help(os)
 ...
help(os.utime)
 Help on built-in function utime in module nt:
 ...
Wow!  Thanks for that, I didn't know about the help command.  The problem
was that things like MySQLdb wasn't in the link you give (or at least, I
couldn't find it - though poking around did take me to the database
section and there it was).

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


Cookbook for beginners?

2006-03-26 Thread Aahz
If you were going to name three or five essential recipes from the
Python Cookbook suitable for beginners, what would you pick?

Yes, this is for _Python for Dummies_, so idioms that aren't in the
Cookbook are also fine.
-- 
Aahz ([EMAIL PROTECTED])   * http://www.pythoncraft.com/

Look, it's your affair if you want to play with five people, but don't
go calling it doubles.  --John Cleese anticipates Usenet
-- 
http://mail.python.org/mailman/listinfo/python-list


access mbx files?

2006-03-26 Thread David Isaac
Should I be able to access mail messages in Mahogany mail's mbx

format using the Python mailbox module? If so, can someone

please post a working example? If not, can you please

point me to documentation of the file format or better yet

Python code to parse it?

Thanks,

Alan Isaac


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


Re: Extending Methods Vs Delegates

2006-03-26 Thread Adam DePrince
On Sun, 2006-03-26 at 07:21 -0800, Alex Martelli wrote:
 vbgunz [EMAIL PROTECTED] wrote:
 
  I am sorry I couldn't reply sooner! Alex, Python in a nutshell is my
  bible and I take it virtually everywhere! Seriously, I would highly
  recommend it to anyone with a little to a lot of Python experience.
  
  I apologize for misinterpreting your passage on page 80. I will look
  much closer at your examples, links and ideas and I hope to straighten
  my knowledge on the subject of delegates!
  
  Thank you for hinting on the Template Method design pattern! Sorry
  for any misunderstanding!
 
 Hey, no problem -- such a misunderstanding is always a shared
 responsibility, and as an author I need to take my part of the blame.
 
 Unfortunately, the root issue is that more and more common, ordinary,
 useful English words get expropriated by specialized technical meanings,
 making it almost impossible to discuss technical matters in ordinary
 English without *some* risk of misunderstanding (by the reader
 mistakenly seeing a specialized, technical meaning where the NORMAL
 English use of the word, possibly in a slightly metaphorical vein, is
 what the author meant).  From function and procedure, to delegate
 and built-in, a growing number of words become risky!-)
 
 Funny enough, the problem is worst in English - because in many other
 languages, the specialized technical terms often use borrowed English
 words, so the other language's native terms remain available.  Latin had
 similar luck wrt Greek a couple millennia ago -- all technical terms of
 philosophy were borrowed Greek words, so the risk of confusion was in
 fact much lower than it was in Greek;-).

Of course, any language suffers that problem when the rise of a new
field is associated with it.  

Medicine draws from Latin.  For English speakers that is wonderful, a
whole language from which to assign specific meanings.  But consider Mr.
DaVinci at one of his past-times, the dissection of rapidly decomposing
corpses for the secrets hidden within.  That he might choose to spell
his description of the inside of an eye as vitreous humor, instead of
say, eye slime, didn't make it sound as impressive to him as the term
does to me today.   I almost feel that a true appreciation for the
complexity of any endeavor must wait until its native language passed a
bit from the spot light.

While I can't speak for other fields, I believe that our linguistic
address space does limit our progress.   Take list interpolations for
instance ... interpolation has other, specific meanings in other not so
far removed fields.  When I first read about it, I had to backup and
think for a moment, if only to resolve the fact that yet another term is
overloaded. 

And even our keyboards limit our space.  I can create a tuple (), or a
list [], or a dict{}, but why can't I create another structure .. oh
wait, we are out of parenthesis like characters, and nobody has the
courage to recycle the of HTML fame  pair.  

Now, as I work on my mutable sequences PEP and implementation, I find
myself annoyed without a good, non-overloaded, way of naming an iter
friendly variant of a data store's normal __delitem__.   Actually, this
wasn't more than a minute long problem, but the rate of collisions
within the English word space is a problem.   At least English is pretty
friendly about adopted and synthetic words.  

Cheers - Adam

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


Re: wired md5 hashing problem

2006-03-26 Thread Adam DePrince
What do you get when you type 

md5sum backup.tar.bz2? 

- Adam

On Sun, 2006-03-26 at 16:56 +0200, Matthias Güntert wrote:
 Hello list-members
 
 i am in the process of writing a python script to backup my data. Now I
 would like to implement md5/sha1 hashes.  
 
 # do md5 fingerprinting 
 if config.get(global, crc) == md5:
 m = md5.new()
 # open the file 
 f = open(fname, rb)
 while 1:
 block = f.read(1024*1024)
 if not block:
 break
 # generate the hash
 m.update(block)
 f.close()
   
 # write the results properly formated to a file
 fd = file(fname + .md5, w)
 fd.write(m.hexdigest())
 fd.write(   + fname + \n)
 fd.close()
 
 
 [EMAIL PROTECTED]  md5sum -c backup.tar.bz2.md5   
 /fileservice/temp/backup.tar.bz2: FAILED
 md5sum: WARNING: 1 of 1 computed checksum did NOT match
 
 [EMAIL PROTECTED]  cat backup.tar.bz2.md5 
 d41d8cd98f00b204e9800998ecf8427e  /fileservice/temp/backup.tar.bz2
 
 so the format should be okay, but whats wrong with my piece of code?!
 
 Greetings
 
 -- 
 http://mail.python.org/mailman/listinfo/python-list

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

Re: wired md5 hashing problem

2006-03-26 Thread Adam DePrince
On Sun, 2006-03-26 at 16:56 +0200, Matthias Güntert wrote:
 Hello list-members
 
 i am in the process of writing a python script to backup my data. Now I
 would like to implement md5/sha1 hashes.  
 
 # do md5 fingerprinting 
 if config.get(global, crc) == md5:
 m = md5.new()
 # open the file 
 f = open(fname, rb)
 while 1:
 block = f.read(1024*1024)
 if not block:
 break
 # generate the hash
 m.update(block)
 f.close()
   
 # write the results properly formated to a file
 fd = file(fname + .md5, w)
 fd.write(m.hexdigest())
 fd.write(   + fname + \n)
 fd.close()
 
 
 [EMAIL PROTECTED]  md5sum -c backup.tar.bz2.md5   
 /fileservice/temp/backup.tar.bz2: FAILED
 md5sum: WARNING: 1 of 1 computed checksum did NOT match
 
 [EMAIL PROTECTED]  cat backup.tar.bz2.md5 
 d41d8cd98f00b204e9800998ecf8427e  /fileservice/temp/backup.tar.bz2


Hey, I found an md5 collision for your file! 

 import md5
 md5.new().hexdigest()
'd41d8cd98f00b204e9800998ecf8427e'

[EMAIL PROTECTED] Include]$ md5sum # hit ^d at start
d41d8cd98f00b204e9800998ecf8427e  -

Your file was empty when scanned. 

Without more information, I'd say that your file was empty when you ran
your python code.

But your code does work ... 

import md5
m = md5.new()
# open the file
fname=Python-2.4.2.tar.bz2
f = open(fname, rb )
while 1:
block = f.read(1024*1024)
if not block:
break
# generate the hash
m.update(block)
f.close()
fd = file(fname + .md5, w)
fd.write(m.hexdigest())
fd.write(   + fname + \n)
fd.close()

[EMAIL PROTECTED] ~]$ python test2.py
[EMAIL PROTECTED] ~]$ md5sum -c Python-2.4.2.tar.bz2.md5
Python-2.4.2.tar.bz2: OK

- Adam

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

maximum() efficency

2006-03-26 Thread Steve R. Hastings
I was looking at a Python function to find the maximum from a list. 
The original was more complicated; I simplified it.  The built-in max()
function can replace the simplified example, but not the original.


def maximum(lst):
  maxval = lst[0]

  for i in xrange(1, len(lst)):
v = lst[i]
if maxval  v:
  maxval = v

  return maxval



Immediately I started thinking about ways to make this more efficient.  My
first thought was to use iterators:


def maximum(lst):
  itr = iter(lst)
  maxval = itr.next()

  for v in itr:
if maxval  v:
  maxval = v

  return maxval



Then I thought, I wonder if there is a faster solution that *doesn't* use
iterators, for use with older versions of Python.  I came up with:


def maximum(lst):
  a = []
  for v in lst:
try:
  if a[0]  v:
a[0] = v
except IndexError:
  a.append(v)
  return a[0]



Of course, it's a little ugly to use a[0] instead of maxval.  And I'm
trying not to index a list, and here I am indexing another list.  So:


def maximum(lst):
  for v in lst:
try:
  if maxval  v:
maxval = v
except NameError:
  maxval = v
  return maxval



And we come at last to my actual question:  Is this guaranteed to work on
all versions of Python?

In my testing on my computer, the above function works perfectly.  Even
if you do this:

 maxval = 100
 print maximum(cmp, [2, 0, 3, 1])
3

In other words, you get a NameError in the function even if there is a
global variable with that name.  That's with Python 2.4, however... is
this function guaranteed to work in all Python versions?  I am very
comfortable with the a[0] version, since I explicitly set a to an empty
list, I know a[0] will always raise that IndexError.


P.S. I went ahead and benchmarked the above functions, plus one more
that is similar to the a[0] solution but used an empty dictionary instead
of a zero-length list.  I created a list of a million zeroes, and then
stored a 1 at the beginning of the list.  Thus the maximum functions would
spend all their time iterating through values and comparing them, and very
little time updating maxval or its equivalent.  Times to run each function
100 times on the large list:

36.8 seconds  xrange
22.3 seconds  iterator
39.2 seconds  IndexError on a[0]
31.5 seconds  NameError with maxval
43.4 seconds  KeyError on empty dictionary


The conclusions I draw from these numbers:

The sneaky tricks with exceptions don't bring enough speed to be worth
using; two of them were actually slower than the xrange solution.  Even
the NameError one was only a little bit faster, and simple is better than
complex, so I don't think I'd ever actually use it.

The clear winner was the iterator version. It was much faster than the
others, and in my opinion it is simpler and easier to understand than any
of the others.
-- 
Steve R. HastingsVita est
[EMAIL PROTECTED]http://www.blarg.net/~steveha

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


String To Dict Problem

2006-03-26 Thread Kamilche
Hi everyone. I'm trying to convert a string that looks like this:

gid = 'FPS', type = 'Label', pos = [0, 20], text = 'FPS', text2 = 'more
text without quotes', fmtline = @VALUE @SIGNAL, signals = [('FPS',
None), ('FPS2', 'something')]

to a dict that looks like this:

{'signals': [('FPS', None), ('FPS2', 'something')], 'text': 'FPS',
'pos': [0, 20], 'text2': 'more text without quotes', 'gid': 'FPS',
'type': 'Label', 'fmtline': '@VALUE @SIGNAL'}

I've got a home-rolled routine that was 'good enough', until I added
the list of tuples in there. Now it's failing. I have a hack to
'special case' it, but you know that will come up to bite me in the
future.

Does anyone have a thought on how I can turn what are basically
function keyword arguments in string form, to a dict, without using
exec or eval?

--Kamilche

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


Re: pondering about the essence of types in python

2006-03-26 Thread Steven Bethard
gangesmaster wrote:
 i dont think it's possible, to create proxy classes, but even if i did,
 calling remote methods with a `self` that is not an instance of the
 remote class would blow up.

I don't understand you here.  Why can't you just do something like:

  class RemoteClass(object):
... def __init__(self, name):
... self.name = name
... def __repr__(self):
... return '%s(name=%s)' % (type(self).__name__, self.name)
...
  rc = RemoteClass('foo')
  rc
RemoteClass(name=foo)
  class ProxyClass(object):
... def __init__(self, name):
... self.remote = RemoteClass(name)
... def __repr__(self):
... return repr(self.remote)
...
  pc = ProxyClass('foo')
  pc
RemoteClass(name=foo)

Note that when I call methods on the remote class, I don't pass them an 
instance of the proxy class -- I pass them an instance of the 
appropriate, RemoteClass type.  Of course my code is simplified because 
I'm not actually doing something remote, but assuming things get, say, 
pickled and unpickled appropriately, I'm not sure I understand why the 
above won't work.

Could you give some more details?

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


Re: wired md5 hashing problem

2006-03-26 Thread Matthias Güntert
On Sun, 2006-03-26 at 11:48 -0500, Adam DePrince wrote:
 
 What do you get when you type 
 
 md5sum backup.tar.bz2?  

it is working. Don't know what went wrong. But now I have another
question: How am I able to execute an external program, like mysqldump?
I had a look into the mysql module it didn't fit my needs. 

-- 
Mit freundlichen Grüßen

Matthias Güntert

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


Re: maximum() efficency

2006-03-26 Thread Steven Bethard
Steve R. Hastings wrote:
 I was looking at a Python function to find the maximum from a list. 
 The original was more complicated; I simplified it.  The built-in max()
 function can replace the simplified example, but not the original.

What's the original?  Are you sure max can't solve it with an 
appropriate decorate-sort-undecorate (DSU) or the key= argument coming 
in Python 2.5?

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


Re: Cookbook for beginners?

2006-03-26 Thread Rene Pijlman
Aahz:
If you were going to name three or five essential recipes from the
Python Cookbook suitable for beginners, what would you pick?
Yes, this is for _Python for Dummies_, so idioms that aren't in the
Cookbook are also fine.

Constants

Static methods / Class methods

Bunch

TaskQueue (Queue for easy and safe multithreading)

A decorator for type checking of function arguments, and/or for
require/ensure, and/or for similar features of other languages that people
find missing in Python.

Properties and in particular lazy properties. Why and how to avoid
getters/setters.

Dynamically import a module (name known at runtime, may or may not be
present).

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


Re: is mysqlsb compatible with MySQL 5.0?

2006-03-26 Thread John Salerno
Dennis Lee Bieber wrote:

   Check the Windows services control for MySQL and try from it...

How do I do that?

 
   You might (since it sounds like this is a first attempt) need to
 uninstall everything -- and make sure you delete the mysql database (in
 case you have a garbaged root login)

Ugh, if this is the case, is there more to uninstall than just using the 
Add/Remove programs? Where do I delete the database?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String To Dict Problem

2006-03-26 Thread Michael Spencer
Kamilche wrote:
 Hi everyone. I'm trying to convert a string that looks like this:
 
 gid = 'FPS', type = 'Label', pos = [0, 20], text = 'FPS', text2 = 'more
 text without quotes', fmtline = @VALUE @SIGNAL, signals = [('FPS',
 None), ('FPS2', 'something')]
 
 to a dict that looks like this:
 
 {'signals': [('FPS', None), ('FPS2', 'something')], 'text': 'FPS',
 'pos': [0, 20], 'text2': 'more text without quotes', 'gid': 'FPS',
 'type': 'Label', 'fmtline': '@VALUE @SIGNAL'}
 
 I've got a home-rolled routine that was 'good enough', until I added
 the list of tuples in there. Now it's failing. I have a hack to
 'special case' it, but you know that will come up to bite me in the
 future.
 
 Does anyone have a thought on how I can turn what are basically
 function keyword arguments in string form, to a dict, without using
 exec or eval?
 
 --Kamilche
 

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

HTH

Michael

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


Re: image reduction script

2006-03-26 Thread Philippe Martin
Kamilche,

I am posting the code in another thread but am not certain that convert does
anything to the picture color depth ... still searching in the doc.

Philippe




Kamilche wrote:

 
 To reduce the color depth of an image in PIL:
 im = im.convert(mode=P, palette=Image.ADAPTIVE)

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


PIL image size reduction script

2006-03-26 Thread Philippe Martin
Hi,

Thanks to the NG, I got the script hereunder working.

1) I am not certain that the call to convert does much (checking the doc)
2) Can this be improved as far as the final image size in (X,Y) ?


For instance, passing a large .jpg with a target byte size of 7000, I get
final (X,Y) results around (213, 174) ... but might want to strech it a bit
while keeping the byte size.

Thanks,

Philippe




 
#***
  def Image_Reduce(self, p_filename, p_size):
BASE_SIZE = 400.0
l_im = Image.open(p_filename)

l_size = l_im.size

if l_size[0]  l_size[1]:
  l_ratio = BASE_SIZE / l_size[0] 
  l_x_size = l_ratio * l_size[0]
  l_y_size = l_ratio * l_size[1]
else:
  l_ratio = BASE_SIZE / l_size[1] 
  l_x_size = l_ratio * l_size[0]
  l_y_size = l_ratio * l_size[1]
  

#l_im.show()
l_image = l_im.resize( (l_x_size, l_y_size))
l_image = l_image.convert(mode=RGB, palette=Image.ADAPTIVE)

l_done = False

l_tmp_file_name = 'sc_tmp_file.jpg'

while False == l_done:
  l_image.save(l_tmp_file_name)
  l_st = os.stat(l_tmp_file_name)
  print 'HERE ', l_st
  if p_size  l_st[6]:

l_ratio -= 0.005
print 'NEW RATIO = ', l_ratio
l_x_size = l_ratio * l_size[0]
l_y_size = l_ratio * l_size[1]
l_image = l_im.resize( (l_x_size, l_y_size))



  else:
l_done = True


l_image.show()
print l_image.size


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


For loop and list comprehension similarity

2006-03-26 Thread s . lipnevich
Hi All,

I apologize if this was brought up before, I couldn't find any prior
art :-).
On more than one occasion, I found myself wanting to use a conditional
loop like this (with Invalid syntax error, of course):

for i in c if test:
print i*2

...because it's similar to the list comprehension construct:

[i*2 for i in c if test]
-

Is this the intended difference in constructs? The available equivalent
feels a bit awkward:

for i in c:
if test:
print i*2

Just curious. Thanks!

Sergey.

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


Re: SSH, remote login, and command output

2006-03-26 Thread Tim Parkin
Spire 01 wrote:
 Greetings!
 
 I'm working on a Python program for a small LAN of Linux systems running
 Gentoo, and I need a little help figuring out what I need to do it.  So
 what I'd like to do is, from any given computer, log on to every other
 computer, run a certain command (which normally outputs text to the
 terminal), and store the output so I can use the aggregate statistics
 later in the program.  I would normally something along the lines of SSH
 to do it, but I don't know what I would need to pull that off in
 Python.  There's also one complication: the systems could be Gentoo
 systems, or they could be logged into Windows since they're dual
 booted.  Considering all of this, can anyone give me some recommendation
 as to what library I should learn how to use to pull this off? I admit,
 I haven't done too much in the way of networks, but if someone can tell
 me what I need to do remote logins in this way, I'll do what I can to
 make it work.
 
 Thanks a million!
 Spire


I wrote a small tool to implement cron like functionality over ssh using
 twisted (with public/private keys). This was written to scratch a small
itch but also to learn how twisted works with conch, it's ssh module.

http://crontorted-project.pollenation.net/cgi-bin/trac.cgi

Feel free to use, I haven't put a license on it but it would be MIT/BSD
.. contact me if you want an explicit confirmation.

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


Re: String To Dict Problem

2006-03-26 Thread Kamilche
Thanks! It's interesting, and nearly what I want, but not quite there.

When I run my sample code through it, I get a syntax error because it's
not a valid expression. If I were to put a 'dict(' in front and a ')'
at the end, THEN it nearly works - but it gives me an
'Unsafe_Source_Error: Line 1.  Unsupported source construct:
compiler.ast.CallFunc' error.

How do I let one measly function in (dict), without letting them all in?

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


Re: Cookbook for beginners?

2006-03-26 Thread Bruno Desthuilliers
Aahz a écrit :
 If you were going to name three or five essential recipes from the
 Python Cookbook suitable for beginners, what would you pick?
 
 Yes, this is for _Python for Dummies_, so idioms that aren't in the
 Cookbook are also fine.


1/ tuple- and dict-based dispatch, ie:
x = (result_if_false, result_if_true)[boolexpr]
y = {key1: result1, key2:result2, ...}[keyexpr]

2/ functions (and methods etc) as first-class objects (two main obvious 
uses : callbacks and decorators)

+ (bonus) the combination of 1/ and 2/ !-)

3/ name-based lookups and affectations (getattr() / setattr()) and their 
implementation ( __getattr__ / __setattr__)



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


Re: maximum() efficency

2006-03-26 Thread Mitja Trampus
Steve R. Hastings wrote:
 I was looking at a Python function to find the maximum from a list. 
 The original was more complicated; I simplified it.  The built-in max()
 function can replace the simplified example, but not the original.

But you forgot to shuw us the original...

[snip several implementations]

 Of course, it's a little ugly to use a[0] instead of maxval.  And I'm
 trying not to index a list, and here I am indexing another list.  So:
 
 def maximum(lst):
   for v in lst:
 try:
   if maxval  v:
 maxval = v
 except NameError:
   maxval = v
   return maxval
 
 In my testing on my computer, the above function works perfectly.  Even
 if you do this:
 
 maxval = 100
 print maximum(cmp, [2, 0, 3, 1])
 3
 
 In other words, you get a NameError in the function even if there is a
 global variable with that name.  That's with Python 2.4, however... is
 this function guaranteed to work in all Python versions?  

Not 100% sure, but I think yes. People with longer experience in python can 
answer 
definitely. Or you can try it out yourself.
The reason it works is that this:
def f():
print a
a=7; f()
works and prints 7 (global a is used), while this
def f():
print a
a = 12
a=7; f()
does NOT work. Python notices that a is going to get assigned to inside f and 
treats it as 
a local variable. This is also the case with your code. Try out the above 
examples without 
a=7 and notice the different error messages...

 The clear winner was the iterator version. It was much faster than the
 others, and in my opinion it is simpler and easier to understand than any
 of the others.

I would have done it in the same way, but probably without the iterators. I.e., 
like this:

def maximum(lst):
try: m = lst[0]
except (TypeError, IndexError): raise Exception Non-sequence or empty 
sequence given to 
maximum)

# (you forgot the above sanity checks in your code.
# not strictly necessary, but nice to have.)

for x in lst:
if xm: m=x
return m
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Module documentation

2006-03-26 Thread Bruno Desthuilliers
Tony Burrows a écrit :
 Just getting to grips with Python, a great language BUT
 With something like Java I can find the syntax of a method call with no
 problems, how do I do the same with Python?
 
 For example, using MySQLdb or SGMLParser I can see what the available
 methods are with dir, but how do I find out what parameters are needed and
 what they represent?

In the python shell, typing 'help(symbol)' should get you started most 
of the time.

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


Re: For loop and list comprehension similarity

2006-03-26 Thread Mitja Trampus
[EMAIL PROTECTED] wrote:

 On more than one occasion, I found myself wanting to use a conditional
 loop like this (with Invalid syntax error, of course):
 
   for i in c if test:
   print i*2

Maybe there's been a PEP, don't really know...
Currently, the only sensible alternative is what you've written below:

 The available equivalent
 feels a bit awkward:
 
   for i in c:
   if test:
   print i*2


This indeed doesn't look nice, especially if you've got lots of code instead of 
just 
print. An alternative which avoids double indentation is

for i in c:
if not test: continue
print i*2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String To Dict Problem

2006-03-26 Thread Michael Spencer
Kamilche wrote:
 Thanks! It's interesting, and nearly what I want, but not quite there.
 
 When I run my sample code through it, I get a syntax error because it's
 not a valid expression. If I were to put a 'dict(' in front and a ')'
 at the end, THEN it nearly works - but it gives me an
 'Unsafe_Source_Error: Line 1.  Unsupported source construct:
 compiler.ast.CallFunc' error.
 
 How do I let one measly function in (dict), without letting them all in?
 
You could add a Keyword node, and use it something like this:

import compiler

class SafeEval(object):

 def visit(self, node,**kw):
 cls = node.__class__
 meth = getattr(self,'visit'+cls.__name__,self.default)
 return meth(node, **kw)

 def default(self, node, **kw):
 for child in node.getChildNodes():
 return self.visit(child, **kw)

 visitExpression = default

 def visitConst(self, node, **kw):
 return node.value

 def visitDict(self,node,**kw):
 return dict([(self.visit(k),self.visit(v)) for k,v in node.items])

 def visitTuple(self,node, **kw):
 return tuple(self.visit(i) for i in node.nodes)

 def visitList(self,node, **kw):
 return [self.visit(i) for i in node.nodes]

 def visitKeyword(self,node,**kw):
 return node.name, self.visit(node.expr)

def safe_dict(source):
 source = dict(%s) % source # funcname is actually ignored
 walker = SafeEval()

 ast = compiler.parse(source,eval)

 kwargs = {}
 args = ast.node.args
 for arg in args:
 if isinstance(arg, compiler.ast.Keyword):
 keyword, value = walker.visit(arg)
 kwargs[keyword] = value
 else:
 raise Exception, only keywords
 return dict(**kwargs)

  source=  gid = 'FPS', type = 'Label', pos = [0, 20], text = 'FPS', 
  text2 
= 'more text without quotes', fmtline = @VALUE @SIGNAL, signals = 
[('FPS',None), ('FPS2', 'something')]
  safe_dict(source)
{'signals': [('FPS', None), ('FPS2', 'something')], 'text2': 'more text without 
quotes', 'gid': 'FPS', 'fmtline': '@VALUE @SIGNAL', 'text': 'FPS', 'type': 
'Label', 'pos': [0, 20]}
 

Michael

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


Re: object references

2006-03-26 Thread Mitja Trampus
DrConti wrote:
 class ObjectClass:
Test primary Key assignment 
 
 if __name__ == __main__:
   ObjectClassInstantiated=ObjectClass()
   ObjectClassInstantiated.AnAttribute='First PK Elem'
   ObjectClassInstantiated.AnotherOne='Second PK Elem'
   ObjectClassInstantiated.Identifier=[]
   
 ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnAttribute)
   
 ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnotherOne)
   print ObjectClassInstantiated.Identifier
   ObjectClassInstantiated.AnAttribute='First PK Elem Changed'
   print ObjectClassInstantiated.Identifier
 
 leads a wrong result
 ./test.py
 ['First PK Elem', 'Second PK Elem']
 ['First PK Elem', 'Second PK Elem']
 -- wrong! It should write  ['First PK Elem Changed', 'Second PK Elem']
 
 i.e. the assgnment
 ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnAttribute)
 assigns only the attribute value, not the reference.

Nono, it assigns the reference alright. In python, EVERYTHING gets assigned 
only a 
reference, .AnAttribute as well. So when you do .AnAttribute = 'Changed', you 
make it a 
reference to a NEW string 'Changed', while .Identifier[0] keeps referencing the 
'First PK' 
string object.
Strings are an unfortunate example, since they're immutable - once you create a 
string 
object, you cant't modify it any more. But if you had a more complex object, 
you could do 
.AnAttribute.changeYourself(), and .Identifier[0] would change accordingly as 
well, 
because .AnAttribute would keep pointing to the same object (albeit changed).

In your case, try .AnAttribute = ['First']; .Identifier[0] = .AnAttribute; 
.AnAttribute[0] 
= 'First changed'; - this will work the way you want it to, because 
.AnAttribute doesn't 
get rebound (only the content of the object (list) it's pointing to change, but 
it's still 
the same object).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cookbook for beginners?

2006-03-26 Thread Rune Strand

Aahz wrote:
 If you were going to name three or five essential recipes from the
 Python Cookbook suitable for beginners, what would you pick?

 Yes, this is for _Python for Dummies_, so idioms that aren't in the
 Cookbook are also fine.

If it's for _beginners_ / _dummies_, I would expect things like

1.6
names = ['George', 'Saddam', 'Osama']
name_string = ', '.join(names)

4.10
dict.setdefault(k, v)

?.?
dict = dict(zip(list_a, list_b))

- listcomps

2.1 / 2.2
reading/writing from/to files

?.?
string-methods like .split(), .upper(), endswith(), startswith(),
isalpha() ...

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


Re: SSH, remote login, and command output

2006-03-26 Thread Tim Parkin
Tim Parkin wrote:
 Spire 01 wrote:
 
Greetings!

...
Thanks a million!
Spire
 
 
 
 I wrote a small tool to implement cron like functionality over ssh using
  twisted (with public/private keys). This was written to scratch a small
 itch but also to learn how twisted works with conch, it's ssh module.
 
 http://crontorted-project.pollenation.net/cgi-bin/trac.cgi
 
 Feel free to use, I haven't put a license on it but it would be MIT/BSD
 .. contact me if you want an explicit confirmation.
Actually, unless you are happy to implement a BSD/MIT (or your own)
license crontab parser (crontorted/crontab.py) the whole will have to be
GPL? The current crontab.py is from Bothan (Thomas Herve therve
doesntlike spam AT free DOT fr) if you're interested, I'll write my own
crontab parser and release it.

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


Re: object references

2006-03-26 Thread Bruno Desthuilliers
DrConti a écrit :
 Dear Python developer community,
 I'm quite new to Python, so perhaps my question is well known and the
 answer too.
 
 I need a variable alias ( what in other languages you would call  a
 pointer (c) or a reference (perl))

Well, that's the only kind of variable[1] in Python.

[1] the correct name in Python is 'binding', since it's about 'binding' 
a reference to a name, not labelling an in-memory address and storing 
data there.

 I read some older mail articles and I found that the offcial position
 about that was that variable referencing wasn't implemented because
 it's considered bad style.
 There was also a suggestion to write a real problem where referencing
 is really needed.
 I have one...:

You *think* you have one.

 I'm trying to  generate dynamically class methods which works on
 predefined sets of object attributes.
 one of these is the set of attributes identfying uniquely the object
 (primary key).
 A naïve attempt to do the job:
 
 class ObjectClass:
Test primary Key assignment 
 
 if __name__ == __main__:
 
   ObjectClassInstantiated=ObjectClass()
   ObjectClassInstantiated.AnAttribute='First PK Elem'
   ObjectClassInstantiated.AnotherOne='Second PK Elem'
   ObjectClassInstantiated.Identifier=[]
   
 ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnAttribute)
   
 ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnotherOne)
   print ObjectClassInstantiated.Identifier
   ObjectClassInstantiated.AnAttribute='First PK Elem Changed'
   print ObjectClassInstantiated.Identifier
 
 leads a wrong result
 
./test.py
 
 ['First PK Elem', 'Second PK Elem']
 ['First PK Elem', 'Second PK Elem']
 -- wrong! It should write  ['First PK Elem Changed', 'Second PK Elem']

Nope, it's exactly what you asked for !-)

 
 i.e. the assgnment
 
 ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnAttribute)
 
 assigns only the attribute value, not the reference.

1/ it's not an assignement
2/ it does not store the attribute value, it stores the reference to 
the object the attribute is bound to. When you later rebind the 
attribute, it only impact this binding - there's no reason it should 
impact other bindings.


 so my question is:
 is it still true that there is no possibilty to get directly object
 references?

But object references *are* what you have.

 Is there a solution for the problem above ?

Yes : keep a reference to the attribute name, not to the value bound to 
that name. There are many ways to do it, here's one:

ObjectClass.Identifier = property(
   fget=lambda self: [self.AnAttribute, self.AnotherOne]
   )

and here's another one:

ObjectClassInstantiated._identifier_parts = []
# note the use of strings, not symbols
ObjectClassInstantiated._identifier_parts.append(AnAttribute)
ObjectClassInstantiated._identifier_parts.append(AnotherOne)

ObjectClass.Identifier = property(
   fget=lambda self: [getattr(self, name) \
for name in self._identifier_parts]
   )


 Thank you for any feedback 

May I add some ? Your naming conventions are highly unpythonic. We 
usually use CamelCase for classes names, and (in order of preference) 
all_lower_with_underscores or mixedCaps for 
variables/attributes/functions etc.

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


Re: String To Dict Problem

2006-03-26 Thread Kamilche
Ah, finally, that's exactly what I need! Thanks bunches. I was
attempting to modify your first code to fit my needs, but mine was much
longer, and not yet working, a sure clue that yours is a better
solution. :-D

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


Re: Accessing func_name from inside a function

2006-03-26 Thread Ron Adam
Alex Martelli wrote:

 Personally, I'd rather have a 3.0 keyword referring to the current
 object (module for module toplevel code, class for classbody toplevel
 code, function for code within a function) -- say for the sake of
 argument the keyword is 'current'; this would allow current.__name__ to
 have the obvious meaning, and would also allow a few more neat things
 (such as natural access to current.__doc__).

That was my thought too, that what is really desired is a *obvious* way 
to get a dependable reference to the current function as you describe here.

A quick experiment...  with an obvious result:

 def foo(): print foo.__name__
 ...
 foo()
 foo
 boo = foo
 boo()
 foo
 boo.__name__
 'foo'
 foo = None
 boo()
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File stdin, line 1, in foo
 AttributeError: 'NoneType' object has no attribute '__name__'

A Current key word would fix this.  Or possibly This which would be 
short for This object.

This may also relate to suggestions to reduce the need for having self 
in the argument list of methods.  So if a keyword This could mean this 
method or function, then Self could mean this class.  Hmmm, methods 
that use Self in this way might run into problems, but I havn't had 
enough coffee to think it though. ;-)

Cheers,
Ron

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


Re: MVC in Python for web app dev

2006-03-26 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
 Thanks Rune. I've already checked out Django and TG and have found both
 the projects to be a little misguided. I think the one great thing they
 have over Rails is the use of SQLObject 

Then you haven't really checked Django - it doesn't use SQLObject.

 Having said that, neither TG or Django seem to have the learning
 material available on an equivilent standard to Rails.

I found Django's doc to be mostly good, even if a bit terse on some 
points (but then there's the mailing-list).

 Maybe it's just
 because they're more immature and thus Rails has got the head start
 here.

Django has been 'extracted' from existing software (3+ years of use in 
production), so I wouldn't call it 'immature'. It certainly has warts 
(the most obvious one - the ORM - will be fixed in 0.92, that is in few 
weeks), but I found it mostly usable, and (this ORM issue apart, but 
transition should not be a big issue) stable enough to start using it on 
real-life projects.

 I guess more than pointing out a few URLs I was looking for some
 peoples honest opinion on why they would chose one over the other
 (besides the basis of language alone).

Well, the 'language' criteria is already enough for me. Ruby is fine 
too, but I've already been programming in Python for 5+ years - talking 
about 'head start' !-)

 I'm just trying to source the
 most viable option at the moment, trying to find something to offer
 quickly without resorting to *shudders* Spring or the like.
 

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


Re: New development windows, IronPython or PythonWin

2006-03-26 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
 Dan wrote:
 
 I realise its in beta. But long term, do you think that the win32com,
win32gui etc... will have no support because everyone jumps on the
Microsoft bandwagon? Aren't the windows support extensions supported
primarily by one guy, Mark Hammond? As a developer, this seams to leave
me with a vulnerability long term. Thanks for the advise.
 
 
 Bruno Desthuilliers wrote:
 
Well, from what we've seen so far, I'd rather rely on open source
software than on proprietary one. An oss project lives as long as
someone is willing to maintain it, and anyone can pick it up. And I
wouldn't count on every one jumping on MS wagon neither.
 
 
 I find this comment curious, as IronPython *is* an open source
 software.

based on a proprietary runtime (yes, I know, Mono... but there again, 
there are legal issues to consider). And what will happen when MS 
discontinue dotnet ???
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANN] Firedrop 0.2.0 - The Python Blog Client

2006-03-26 Thread Fuzzyman
It has finally happened, the release of `Firedrop 0.2.0
http://www.voidspace.org.uk/python/firedrop2/`_.

The impatient can download the new release here :

`Firedrop 0.2.0 (1.3mb)
http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=firedrop2-0.2.0.zip`_

.. note::

The first time you run version 0.2.0 it will convert your weblog
config file to the new format.

**Firedrop2** is the Python blog client with a host of features. These
include :

* RSS feed generation
* Categories
* Automatic archive generation
* A powerful set of plugins, including spell checker and emailer
* Entries can be made in text, HTML, ReST, textile, sextile or markdown
markup
* HTML templating system and macros for all sorts of tricks
* Built in FTP capability for uploading your blog to a server
* Because it's written in Python, it is easy to extend Firedrop or
create new plugins for it

This new release has been made possible by the hard work of `Stewart
Midwinter http://www.midtoad.org`_.

The changes and new features include :

* Firedrop will now start up by opening a default site.
* You can set the default site using the GUI.
* Main file name changed to ``firedrop.pyw``
* `ConfigObj http://www.voidspace.org.uk/python/configobj.html`_ is
now used to edit all the config files.
* Full support for all style elements (e.g. underline, bold) in four
  major markup formats: ReST, Sextile, Textile, Markdown (plus HTML).
* New entries are created in a separate dialog that takes care of the
markup.
* Links are available to websites for the markup styles.
* You can reset the app to a null site, and/or delete all entries.
* You can force a full build of your site, or just update your site.
* You can now create sites serving Article Collections or Items Lists
(e.g. FAQs)
  in addition to Weblogs.
* Firedrop2 now runs on Mac OS X and Linux in addition to Windows.
* You can view logfile contents using the GUI.
* Documentation has been updated to reflect these changes.

There is a roadmap for future releases on the `Firedrop2 Trac Site
http://firedrop2.python-hosting.com`_.

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


Re: For loop and list comprehension similarity

2006-03-26 Thread s . lipnevich
Thank you for replying, Mitja! That *is* a nice alternative.

Do you think it's a good idea to ask on comp.python.devel if they would
be interested in a PEP about this (provided there is none)?

Cheers,
Sergey.

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


Re: image reduction script

2006-03-26 Thread Kamilche
Be sure and use mode = P instead of RGB, like you have in your other
code. P is for palettized images. Don't palettize if you're storing as
JPG, only if you're storing as PNG or some other format that can handle
256 color images.

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


Advice for Python and Web Server/Services?

2006-03-26 Thread Ron Davis

I have recently discovered Python and like it quite a bit. I would like to
use it on a new project I am starting. 

The project will gather data from several web services and present the
collected data to browser users through a web server.

So basically I need a full-time web server and a separate way to poll web
services for their data. There is no database involved.

The problem is that I have tried several Python web servers (CherryPy,
Karrigell, etc) and they all have problems getting out through my Comcast
cable modem. There is a 3 second pause every 10th file. Never the 9th or
11th, but always the 10th file. 

I thought maybe Comcast was limiting incomming HTTP but Apache does not do
this so I'm stumped as to why it is happening with the Python servers. All
servers work fine over the LAN.

Anyway, I wanted to get some advice on what type of setup would be best
for this using Apache. The web service polling needs to be going all the
time so a straight CGI-type thing is not an option. 

I've looked in to fastcgi and mod_python but I'm not sure either is what I
need. What I want is for my Python program to be polling the web
services 24/7 and Apache to serve static pages by itself but call
a function in my already running Python program for files with a certain
extension (.xml for example).

Have any of you done something like this before?

Ideally, I'd like to figure out why the Python servers are having
problems. This is a very low volume system so straight Python would be
great if I can get it working.

Thanks for any advice you can give.

--
Ron Davis






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


wildcard exclusion in cartesian products

2006-03-26 Thread [EMAIL PROTECTED]
The python code below is adapted from a Haskell program written by
Tomasz
Wielonka on the comp.lang.functional group. It's more verbose than his
since I wanted to make sure I got it right.

http://groups.google.com/group/comp.lang.functional/browse_frm/thread...

Does anyone know how to turn it into a module (or whatever it's called)
so that I can put it in a
loop and not have to generate the whole list? I've already tried
without success.

The program solves the following problem: generate the subset X of the
cartesian product S^n that excludes n-tuples defined by wildcards. For
example, if I want to exclude from [1,2,3]^3 the wc's [1,*,2] and
[*,3,*,3,*], where * stands for a sequence of zero or more
elements of [1,2,3], then I just type

for x in generateNotMatching([1,2,3,4],4,[[1,'*',2],[3,'*',4]]): print
x

and get the output

   [1, 1, 1]
   [1, 1, 3]
   [1, 2, 1]
   [1, 2, 3]
   [1, 3, 1]
   [2, 1, 1]
   [2, 1, 2]
   [2, 1, 3]
   [2, 2, 1]
   [2, 2, 2]
   [2, 2, 3]
   [2, 3, 1]
   [2, 3, 2]
   [3, 1, 1]
   [3, 1, 2]
   [3, 2, 1]
   [3, 2, 2]

This is nice! But all elements are generated before they are printed.

##
import sys, os, string

def imap(function, source):
for element in source:
yield function(element)

def any(iterable):
 '''True iff at least one element of the iterable is True'''
 for element in iterable:
if element:
return True # or element and change the definition
 return False

def all(iterable):
 '''True iff no element of the iterable is True'''
 '''SHOULD BE?: True iff all element of the iterable are True'''
 for element in iterable:
if not element:
return False
 return True

def rev(L):
rL=[]
for x in L: rL=[x]+rL
return rL

def advancePattern(x,p):
if p==[]: return []
else:
   h=p[0]
   t=p[1:]
   if h != '*':
  if h == x: return [t]
  else: return []
   else: return [p] + [t] + advancePattern(x,t)

def advancePatterns(x,P):
aP=[]
for p in P:
aP += advancePattern(x,p)
return aP

#return [advancePattern(x,p) for p in P]

def allStar(p):
return all( imap((lambda x: x=='*'),p) )

def notNullOrZero(p,n):
return p !=[] or n==0

def generateNotMatching(A,n,P):
return gen(A,n,P,[])

def gen(A,n,P,acc):
if any(imap((lambda p:  allStar(p) and notNullOrZero(p,n)), P)):
   return []
else:
   if n==0:
  return map(rev,[acc])
   else:
  aG=[]
  for a in A:
  aG += gen(A,n-1,advancePatterns(a,P),[a]+acc)
  return aG

##

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


Re: Python types

2006-03-26 Thread Bruno Desthuilliers
Salvatore a écrit :
 Thank's everybody :-)
 
 
 Here is a type définition I've found on the net which I agree with :
 
 Attribute of a variable which determines the set of the values this
 variabe can take and the
 operations we can apply on it.

Then - as already pointed by Alex - there is no type in Python, since 
there is no variable (even if this term is often improperly used for 
bindings) !-)

Ok, let's s/variable/object/g and define some objects and operations:

def myop(obj):
   return obj.foo * 2

class Bar(object):
   pass

b = Bar()

Can we apply the myop() operation on the object name 'b' is bound to ?

myop(b)
Traceback (most recent call last):
   File stdin, line 1, in ?
   File stdin, line 1, in myop
AttributeError: 'Bar' object has no attribute 'foo'


Well... but wait a minute:
b.foo = []
myop(b)
- []

Err... Wait another minute:

b2 = Bar()
type(b) is type(b2)
- True
myop(b2)
Traceback (most recent call last):
   File stdin, line 1, in ?
   File stdin, line 1, in myop
AttributeError: 'Bar' object has no attribute 'foo'

Ok, so even if Python itself declares b and b2 (read: objects that names 
b and b2 are bound to) to be of the same type,  you cannot apply the 
myop() operation on b2...

Also:

del b.foo
myop(b)
Traceback (most recent call last):
   File stdin, line 1, in ?
   File stdin, line 1, in myop
AttributeError: 'Bar' object has no attribute 'foo'


So *sometimes* you can apply myop() to b, and sometimes you can't.

Now if we come back to your original post:

All objects seem to have a perfectly defined
type


Perfectly defined ? Really ? Not for your current definition of 'type' 
at least !-)

I still mostly agree with the given definition of type. But the fact is 
that in Python, the type*s* of an object are not so perfectly defined - 
they're mostly implicits, and can vary during the object's lifetime.

Note that it does'nt make Python weakly typed - you cannot perform any 
arbitrary operation on a given object, only the operations this object 
can support at a given moment. FWIW, if you want a weakly typed 
language, take a look at C.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python multithreading problem

2006-03-26 Thread abhinav
//A CRAWLER IMPLEMENTATION
please run this prog. on the shell and under the control of debugger
when this prog. is run normally the prog. does not terminate .It
doesn't come out of the cond. if c5: so this prog. continues
infinitely
but if this prog is run under the control of debugger the prog
terminates when the cond. if c5: becomes false
i think this prob. may be due to multithreading pls help.


from sgmllib import SGMLParser
import threading
import re
import urllib
import pdb
import time
class urlist(SGMLParser):
def reset(self):
SGMLParser.reset(self)
self.list=[]

def start_a(self,attr):
href=[v for k,v in attr if k==href]
if href:
self.list.extend(href)
mid=2
c=0
class mythread(threading.Thread):
 stdmutex=threading.Lock()
 global threads
 threads=[]
 def __init__(self,u,myid):
self.u=u
self.myid=myid
threading.Thread.__init__(self)
 def run(self):
global c
global mid
if c5:
self.stdmutex.acquire()
self.usock=urllib.urlopen(self.u)
self.p=urlist()
self.s=self.usock.read()
self.p.feed(self.s)
self.usock.close()
self.p.close()
c=c+1
fname=/root/ + str(c) + .txt
self.f=open(fname,w)
self.f.write(self.s)
self.f.close()
print c
print self.p.list
print self.u
print self.myid
for j in self.p.list:
k=re.search(^https?:,j)
if k:
   i=mythread(j,mid)
   i.start()
   threads.append(i)
   mid=mid+1
self.stdmutex.release()






if __name__==__main__:
thread=mythread(http://www.google.co.in/,1)
thread.start()
threads.append(thread)
for thread in threads:
  thread.join()
print main thread exits

































































































































































































































































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


Re: wired md5 hashing problem

2006-03-26 Thread Paul Rubin
Matthias Güntert [EMAIL PROTECTED] writes:
 i am in the process of writing a python script to backup my data. Now I
 would like to implement md5/sha1 hashes.  

Try editing as follows: change

 f = open(fname, rb)
 while 1:
 block = f.read(1024*1024)
 if not block:
 break
 # generate the hash
 m.update(block)
 f.close()

to:

 f = open(fname, rb)
 nbytes = 0
 while 1:
 block = f.read(1024*1024)
 nbytes += len(block)
 if not block:
 break
 # generate the hash
 m.update(block)
 f.close()
 print '%d bytes processed'

As Adam DePrince noticed, the md5 checksum you generated was that of
an empty file.  So the above should tell you whether you're actually
processing any input; if you don't get the expected number of bytes,
debug from there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing func_name from inside a function

2006-03-26 Thread Bruno Desthuilliers
James Thiele a écrit :
 I'd like to access the name of a function from inside the function. My
 first idea didn't work.
 
 
def foo():
 
 ... print func_name
 ...
 
foo()
 
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File stdin, line 2, in foo
 NameError: global name 'func_name' is not defined
 
 My second attempt works but looks ugly.
 
 
def foo():
 
 ... import inspect
 ... print inspect.stack()[0][3]
 ...
 
foo()
 
 foo
 
 Is there a standard way of getting the name of a function from inside
 the function?
 

You've already got good answers. Now here's another workaround:

class _FooFunction(object):
   def __call__(self):
 print self.__class__.__name__
foo = _FooFunction()

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


Re: image reduction script

2006-03-26 Thread Philippe Martin
Kamilche wrote:

 Be sure and use mode = P instead of RGB, like you have in your other
 code. P is for palettized images. Don't palettize if you're storing as
 JPG, only if you're storing as PNG or some other format that can handle
 256 color images.


My problem is this:

1) If I use a save to jpg after a convert('P') I get an exception (what you
are refering to I assume)
2) If I use a save to png (I start with a jpg), then the (X,Y) size of the
output is much smaller than convert('RGB') and save to jpg - (and I want to
opposit: as small as possible in byte size and as large as possible in
(X,Y)  ):

*** SAME INPUT FILE.JPG *** 
***convert('P') save to PNG
/home/philippe/tmp/tmprpdfEO is a 65x87 Raw PPM image with 256 levels
  Default gamma for ITRUE image is  1.00
  Building XImage...done
  Have adjusted image from 1.00 to display gamma of 2.20

Versus:
***convert('RGB') save to JPG
/home/philippe/tmp/tmpYCLrQR is a 173x231 Raw PPM image with 256 levels
  Default gamma for ITRUE image is  1.00
  Building XImage...done
  Have adjusted image from 1.00 to display gamma of 2.20


Philippe



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


Re: maximum() efficency

2006-03-26 Thread Paul McGuire
Steve R. Hastings [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 I was looking at a Python function to find the maximum from a list.
 The original was more complicated; I simplified it.  The built-in max()
 function can replace the simplified example, but not the original.


If you are interested in both the min and max values, here is an algorithm
that performs only 3 comparisons for every 2 list items, instead of the
brute force method's 4 comparisons.  This walks the input list in pairs,
compares the two items to each other, then compares the lesser with the
current min and the greater with the current max.

def minMax(L):
lenL = len(L)
if lenL == 0:
return None,None
if lenL == 1:
return L[0],L[0]

min_ = max_ = L[0]

if lenL % 2:
i = 1
else:
i = 0
while i  lenL:
a,b = L[i],L[i+1]
if a  b:
a,b = b,a
if a  min_: min_ = a
if b  max_: max_ = b
i += 2

return min_,max_

Of course, this much Python bytecode is not near as fast as simply calling
the builtins min() and max().  But, if you add psyco to the mix, things
aren't so cut-and-dried.  I tested this method using a list of
randomly-generated strings, and after the list length exceeds 100-500 or so,
minMax starts to outperform the compiled min() and max().  The following
table shows the timing for the brute force min() and max() calls, followed
by minMax():

List length  1: 0.229 0.612
List length  2: 0.056 0.0001081
List length 10: 0.059 0.707
List length100: 0.154 0.087
List length500: 0.589 0.534
List length   1000: 0.0001176 0.670
List length  1: 0.0011485 0.0008954
List length 10: 0.0126720 0.0077379

Using the OP's test of 1 million zeros with the first zero changed to a 1,
here is the performance of minMax vs. min() and max():

List length 100:  0.1235953 0.0126896

minMax is 10X faster!  Ironically, it's faster calling minMax() than either
min() or max().

If your list contains objects that are expensive to compare, the crossover
list length may be much shorter.

-- Paul


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


Re: Accessing func_name from inside a function

2006-03-26 Thread Alex Martelli
Ron Adam [EMAIL PROTECTED] wrote:

 A Current key word would fix this.  Or possibly This which would be
 short for This object.

I think This would cause huge confusion, since in other popular
language the keyword this means (a pointer/reference to) the instance
variable on which the method is being called -- my use is instead for
the object of the immediate lexically enclosing scope (a module,
class, or function).  Implementation wouldn't be trivial in today's
CPython, anyway: frames have no references at all to function objects
(only to _code_ objects), and class objects don't even exist untill well
after their top-level code has long finished running; to make Current
possible, these subtle points of semantics would have to be changed in
quite a revolutionary way, especially where classes are concerned.


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


Re: For loop and list comprehension similarity

2006-03-26 Thread Grant Edwards
On 2006-03-26, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Hi All,

 I apologize if this was brought up before, I couldn't find any prior
 art :-).
 On more than one occasion, I found myself wanting to use a conditional
 loop like this (with Invalid syntax error, of course):

   for i in c if test:
   print i*2

 ...because it's similar to the list comprehension construct:

   [i*2 for i in c if test]
 -

 Is this the intended difference in constructs? The available equivalent
 feels a bit awkward:

   for i in c:
   if test:
   print i*2

   for j in [i*2 for i in c if test]:
  print j

-- 
Grant Edwards   grante Yow!  .. I wonder if I
  at   ought to tell them about my
   visi.comPREVIOUS LIFE as a COMPLETE
   STRANGER?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing func_name from inside a function

2006-03-26 Thread Alex Martelli
James Thiele [EMAIL PROTECTED] wrote:

 I'd like to access the name of a function from inside the function. My
 first idea didn't work.
 
  def foo():
 ... print func_name
 ...
  foo()
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File stdin, line 2, in foo
 NameError: global name 'func_name' is not defined

So, define it -- as a function, of course:

def func_name():
import sys
return sys._getframe(1).f_code.co_name

def foo():
print func_name()

def bar():
print func_name()

No doubt you'll object that the internals of func_name are ugly, but
the point is that it can be hidden anywhere you like, so its internals
are as irrelevant as they would be if it was a built-in.


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


Re: Accessing func_name from inside a function

2006-03-26 Thread Eyal Lotem
Steven D'Aprano wrote:

 On Sun, 26 Mar 2006 10:19:36 +1000, Ben Finney wrote:
 
 James Thiele [EMAIL PROTECTED] writes:
 
 I'd like to access the name of a function from inside the function.
 
 A function, like most other objects in Python, can have any number of
 names bound to it without the object being informed. Any of those
 names can then be used to reference the object, and the object has no
 way of knowing by what name it was referenced.
 
 Because of this fallacy,
 
 You keep using that word. I do not think it means what you think it
 means.
 
 *wink*
 
 it's generally considered bad programming
 style to want to know the name of the current object from inside
 that object.
 
 I agree whole-heartedly with Ben's sentiments here, although I can also
 point out by example why it might be useful for a function to know it's
 own name:
 
 def Ackermann(i, j):
 Returns the Ackermann function of integers i and j.
 
 The Ackermann function is an example of a function which grows at a
 much faster than exponential rate. Ackermann(i, j) for i  2 grows
 even more quickly than 2**2**2**...**2 (where there are j exponents).
 It is an example of a recursive function which is not primitively
 recursive and was discovered by the German mathematician Wilhelm
 Ackermann in 1928.
 
  Ackermann(1, 1)
 2
  Ackermann(2, 2)
 16
  Ackermann(2, 3)
 65536
 
 The Ackermann function is not defined for i,j = 0.
 
 See http://en.wikipedia.org/wiki/Ackermann_function
 and 'Introduction to Algorithms' by Thomas H Cormen, Charles E
 Leiserson, Ronald L Rivest, pp. 451-453.
 
 if i  0 or j  0:
 raise ValueError(
 arguments to the Ackermann function must be positive)
 if i == 1:
 return 2**j
 if j == 1:
 return Ackermann(i-1, 2)
 return Ackermann(i-1, Ackermann(i, j-1))
 
 Notice that if you change the name of the function, you have to change it
 in no less than three places in the function definition and four places
 in the __doc__ string, but a global search and replace is too greedy and
 will change too much. As a general principle, it is considered best
 practice to code in such a way that if you change something, you only need
 to change it in one place.
 
 I guess that the Original Poster wants some magic that allows functions to
 do this:
 
 def Ackermann(i, j):
 Returns the Ackermann function of integers i and j.
 
 The Ackermann function is an example of a function which grows at a
 much faster than exponential rate. %MAGIC(i, j) for i  2 grows
 even more quickly than 2**2**2**...**2 (where there are j exponents).
 It is an example of a recursive function which is not primitively
 recursive and was discovered by the German mathematician Wilhelm
 Ackermann in 1928.
 
  %MAGIC(1, 1)
 2
  %MAGIC(2, 2)
 16
  %MAGIC(2, 3)
 65536
 
 The Ackermann function is not defined for i,j = 0.
 
 See http://en.wikipedia.org/wiki/Ackermann_function
 and 'Introduction to Algorithms' by Thomas H Cormen, Charles E
 Leiserson, Ronald L Rivest, pp. 451-453.
 
 if i  0 or j  0:
 raise ValueError(
 arguments to the Ackermann function must be positive)
 if i == 1:
 return 2**j
 if j == 1:
 return %MAGIC(i-1, 2)
 return %MAGIC(i-1, %MAGIC(i, j-1))

Another possibility would be:

def recursive_func(func):
def new_func(*args, **kw):
return func(new_func, *args, **kw)
return new_func

@recursive_func
def Ackermann(recurse, i, j):
# yadda yadda
recurse(i-1, ...), recurse(y-2, ...)

 Now he can easily rename Ackermann to Ack and need only make the
 change in one place.
 
 I suspect that the correct solution to the O.P.'s problem is to think
 carefully about the names of your functions in advance.

By the way, the real problem here is referencing by name, rather than
using true references. Which is the result of using a textual language.
The real solution would be to store real-references to the function and
only present the name in a graphical interface.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wildcard exclusion in cartesian products

2006-03-26 Thread Michael Spencer
[EMAIL PROTECTED] wrote:
 The python code below is adapted from a Haskell program written by
 Tomasz
 Wielonka on the comp.lang.functional group. It's more verbose than his
 since I wanted to make sure I got it right.
 
 http://groups.google.com/group/comp.lang.functional/browse_frm/thread...
 
 Does anyone know how to turn it into a module (or whatever it's called)
 so that I can put it in a
 loop and not have to generate the whole list? I've already tried
 without success.

I know next to nothing about Haskell, but I believe that it evaluates sequences 
lazily by default.  Python can certainly do lazy evaluation, but you'll have to 
ask for it explicitly.
 
 The program solves the following problem: generate the subset X of the
 cartesian product S^n that excludes n-tuples defined by wildcards. For
 example, if I want to exclude from [1,2,3]^3 the wc's [1,*,2] and
 [*,3,*,3,*], where * stands for a sequence of zero or more
 elements of [1,2,3], then I just type
 

[I think your example and test case may have become mixed up]
...

Here's an iterative lazy solution.  While we're at it, why not use re for 
pattern matching, rather than rolling our own matcher (this does restrict the 
set members to characters, maybe that's OK):

import re

def cp_excl_wc(alpha, N, *exclusions):
 RE0, RE1 = compile_re(exclusions)
 def add_one(outer, RE_PATTS):
 if RE_PATTS:
 for partial in outer:
 for a in alpha:
 next = partial + a
 if not RE_PATTS.match(next):
 yield next
 else: # if there's no pattern to match at this length
   # don't waste time trying
 for partial in outer:
 for a in alpha:
 yield partial+a
 cpgen = ,
 # RE0 holds the patterns that match at the beginning, so are tested
 # against all iterations less than full length
 for n in range(N-1):
 cpgen = add_one(cpgen, RE0)
 # For the last place, test the full-length patterns
 cpgen = add_one(cpgen, RE1)
 return cpgen


def compile_re(exclusions):
 re0 = [] # patterns that can be matched anywhere
 re1 = [] # patterns that match only the full-length
 for pattern in exclusions:
 pattern = pattern.replace(*, .*)
 if pattern.endswith(.*):
 re0.append(pattern)
 re1.append(pattern+$)

 re0 = re0 and re.compile(|.join(re0)) or None
 re1 = re1 and re.compile(|.join(re1)) or None
 return re0, re1

  nm = cp_excl_wc(123,3,1*2,3*1)
  nm.next()
'111'
  nm.next()
'113'
  nm.next()
'121'
  nm.next()
'123'
  list(nm)
['131', '133', '211', '212', '213', '221', '222', '223', '231', '232', '233', 
'312', '313', '322', '323', '332', '333']
 

Is this the sort of thing you had in mind?

Michael

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


Re: Python types

2006-03-26 Thread Salvatore
Thank's Bruno.

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


Re: wildcard exclusion in cartesian products

2006-03-26 Thread [EMAIL PROTECTED]
Michael,

Yes! That is precisely what I had in mind! 

Thanks,

Walter Kehowski

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


Re: MVC in Python for web app dev

2006-03-26 Thread Robert Hicks
http://www.myghty.org/

That one is excellent.

Robert

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


regimes

2006-03-26 Thread magaznan

 
Collecter rapidement les informations nécessaires pour

   travailler de chez soi 


avec son ordinateur



et de ce fait amasser rapidement des rentrées  d'argents plus qu'honorables 





To collect the necessary information quickly for

   to work of at home 

with your computer

and of that made accumulate quickly of the returns of money more that honorable 






contact:
[EMAIL PROTECTED]



http://www.allsolutionsnetwork.com/RN/RN32579


http://10perday.com/?ref=5113



This message was sent with NNTP Scribbler (www.e-advertize.com).
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: What's The Best Editor for python

2006-03-26 Thread Charles Krug
On 2006-03-26, Andrew Gwozdziewycz [EMAIL PROTECTED] wrote:
 If you want something that won't get in your way, you should really  
 use /bin/ed. It's probably simpler to use then searching the archives.
 /bin/ed will also run in cygwin for windows.

 Can one of you say to me what's the best editor for
 editing the python programs( for linux or windows )


The best editor is the one you like best.

I'm a vim user with taglist--I'm not fully happy with how ctags does
Python, but it's more than Good Enough.

But editors are religious, and not worth arguing about, generally.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New development windows, IronPython or PythonWin

2006-03-26 Thread Fuzzyman

[EMAIL PROTECTED] wrote:
 IronPython is currently nowhere near production quality. I would not
 recommend it.

I know at least one firm developing production quality software using
IronPython, so your statement 'nowhere near' is a bit off.

They're pretty close to a full Python 2.4 implementation , and the list
of bugs shrinks daily.

It's not a project that's about to disappear either.

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

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


Re: For loop and list comprehension similarity

2006-03-26 Thread Ben Finney
[EMAIL PROTECTED] writes:

 On more than one occasion, I found myself wanting to use a conditional
 loop like this (with Invalid syntax error, of course):

   for i in c if test:
   print i*2

 ...because it's similar to the list comprehension construct:

   [i*2 for i in c if test]

Why not combine the two:

for i in [j for j in c if test]:
print i*2

-- 
 \   I got food poisoning today. I don't know when I'll use it.  |
  `\  -- Steven Wright |
_o__)  |
Ben Finney

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


interactive programme (add a new line in Tk)

2006-03-26 Thread nigel
somebody recently  showed me how to create a new line using \n which was 
great.The thing is when i am creating the programme the text i wish to add is 
quite long.and it ends up stretching the width of several pages,which i think 
looks quite messy.Would it be possible for some one to show me how to create 
another line while writing my programme.What i mean by this is where my text 
ends iv arrivedi wish to add a new line beneath to continue my text so i do 
not reach the end of the page.

from Tkinter import *

root = Tk()

w = Label(root, text=\n Hello, world! \n iv arrived)
w.pack()

root.mainloop()

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


Re: Accessing func_name from inside a function

2006-03-26 Thread Ron Adam
Alex Martelli wrote:
 Ron Adam [EMAIL PROTECTED] wrote:
 
 A Current key word would fix this.  Or possibly This which would be
 short for This object.
 
 I think This would cause huge confusion, since in other popular
 language the keyword this means (a pointer/reference to) the instance
 variable on which the method is being called -- my use is instead for
 the object of the immediate lexically enclosing scope (a module,
 class, or function).  Implementation wouldn't be trivial in today's
 CPython, anyway: frames have no references at all to function objects
 (only to _code_ objects), and class objects don't even exist untill well
 after their top-level code has long finished running; to make Current
 possible, these subtle points of semantics would have to be changed in
 quite a revolutionary way, especially where classes are concerned.
 
 
 Alex

Yes, I figured it would not be an easy or simple addition.  An easier 
alternative might be to be able to limit specific name rebindings.  Then 
some names could be depended on to always point to a specific object. 
Something like that would need to be used sparingly I think.

Cheers,
Ron
-- 
http://mail.python.org/mailman/listinfo/python-list


work at home

2006-03-26 Thread magaznan

 
Collecter rapidement les informations nécessaires pour

   travailler de chez soi 


avec son ordinateur



et de ce fait amasser rapidement des rentrées  d'argents plus qu'honorables 





To collect the necessary information quickly for

   to work of at home 

with your computer

and of that made accumulate quickly of the returns of money more that honorable 






contact:
[EMAIL PROTECTED]



http://www.allsolutionsnetwork.com/RN/RN32579


http://10perday.com/?ref=5113



This message was sent with NNTP Scribbler (www.e-advertize.com).
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Bitwise OR?

2006-03-26 Thread Clemens Hepper
Adam DePrince wrote:
 BTW: Is there something like a sizeof() method for int numbers?
 
 import struct
 help( strict.calcsize )
Mh, that doesn't do what i want. I'd like to have something like:

def size(number):
  return sizeof(number)

 Why one bit at a time?

Good question...

Here my new approach based on your idea:

_digits = { 0:, 1:1000, 2:0100, 3:1100,
4:0010, 5:1010, 6:0110, 7:1110,
8:0001, 9:1001, 0xa:0101, 0xb:1101,
0xc:0011, 0xd:1011, 0xe:0111, 0xf:}

def bitstring2(number):
  lsb--msb
  rlist = list()
  if number = 0:
while number:
  rlist.append( _digits[number  0xF] )
  number = 4
  else:
while number != -1:
  rlist.append( _digits[number  0xF] )
  number = 4

  return ''.join(rlist)

This was faster for positive numbers. For negative numbers yours was
faster, but my version handles those numbers different.

Your version fails for Large numbers since hex( long ) returns
something like 0xFFFL instead of 0xfff.

 Cheers - Adam

Cheers :)
- eth
-- 
http://mail.python.org/mailman/listinfo/python-list


PyPy is now able to compile efficient extension modules!

2006-03-26 Thread Luis M. González
PyPy is now able to compile efficient extension modules!.

This was recently announced by Christian Tismer on Pypy's mailing list.
To learn more:
http://codespeak.net/pipermail/pypy-dev/2006q1/002911.html

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


Re: For loop and list comprehension similarity

2006-03-26 Thread s . lipnevich
 Why not combine the two:

I guess because (at least in source code) you're doing a loop twice
:-). I don't know what a compiler would do. I think though that the
for i in c if test: construct is more readable and maybe can even be
better optimized.
Thanks!

Sergey.

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


Re: For loop and list comprehension similarity

2006-03-26 Thread John Zenger
Rather than a list comprehension, it would be faster and more 
memory-efficient to use a generator comprehension.  Just change the 
square brackets to parentheses:

 for j in (i*2 for i in c if test):
print j


Grant Edwards wrote:
 On 2006-03-26, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 
Hi All,

I apologize if this was brought up before, I couldn't find any prior
art :-).
On more than one occasion, I found myself wanting to use a conditional
loop like this (with Invalid syntax error, of course):

  for i in c if test:
  print i*2

...because it's similar to the list comprehension construct:

  [i*2 for i in c if test]
-

Is this the intended difference in constructs? The available equivalent
feels a bit awkward:

  for i in c:
  if test:
  print i*2
 
 
for j in [i*2 for i in c if test]:
   print j
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python multithreading problem

2006-03-26 Thread Serge Orlov
abhinav wrote:
 //A CRAWLER IMPLEMENTATION
 please run this prog. on the shell and under the control of debugger
 when this prog. is run normally the prog. does not terminate .It
 doesn't come out of the cond. if c5: so this prog. continues
 infinitely

How do you know? Have you waited *infinitely* ;)


   if c5:
   self.stdmutex.acquire()

The problem you have a lot of threads that has already checked c  5
condition but has not acquired the lock yet. Besides you have another
problem: if a thread raises an exception you don't release the lock.
Why don't you use Queue module for sane thread management?

  Serge.

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


Re: py web-app-frameworks without a rdbms...

2006-03-26 Thread Michael Goettsche
On Wednesday 22 March 2006 02:06, [EMAIL PROTECTED] wrote:
 Hi folks,

 Of TurboGers  Django WAF candidates, which one would be easier to use
 in an environment where the data/content doesn't come an RDBMS, but
 from other server-side apps... If these are not good candidates, could
 you suggest appropriate ones...

 TIA,
 /venkat

Be sure to have a look at CherryPy: http://www.cherrypy.org

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


Re: maximum() efficency

2006-03-26 Thread Steve R. Hastings
On Sun, 26 Mar 2006 20:34:28 +0200, Mitja Trampus wrote:
 I would have done it in the same way, but probably without the iterators. 
 I.e., like this:
 
 def maximum(lst):
   try: m = lst[0]
   except (TypeError, IndexError): raise Exception Non-sequence or empty 
 sequence given to 
 maximum)
 
   # (you forgot the above sanity checks in your code.
   # not strictly necessary, but nice to have.)
 
   for x in lst:
   if xm: m=x
   return m

I left out the original sanity check, because I just wanted a streamlined
simple example.


I had a nagging feeling that I was missing something simple, and you have
put your finger on it.  That's perfect!  It's simple, it's clear, and it
will work on any version of Python.  Thanks!
-- 
Steve R. HastingsVita est
[EMAIL PROTECTED]http://www.blarg.net/~steveha

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


Python float representation error?

2006-03-26 Thread [EMAIL PROTECTED]
try running this in python:

print [39.95]

the output i get is:
[39.953]

what's up with that?

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


Re: [ANN] Firedrop 0.2.0 - The Python Blog Client

2006-03-26 Thread Kent Johnson
Fuzzyman wrote:
 It has finally happened, the release of `Firedrop 0.2.0

 * `ConfigObj http://www.voidspace.org.uk/python/configobj.html`_ is
 now used to edit all the config files.

You should add this to the dependency list in the install page, it 
tripped me up.

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


Re: maximum() efficency

2006-03-26 Thread Steve R. Hastings
On Sun, 26 Mar 2006 10:34:16 -0700, Steven Bethard wrote:
 What's the original?



def minimum(cmp, lst):
  minimum(cmp, lst)

  Returns the minimal element in non-empty list LST with elements
  compared via CMP() which should return values with the same semantics
  as Python's cmp().  If there are several minimal elements, the last
  one is returned.
  

  if not lst:
raise ValueError, 'empty list'

  minval = lst[0]

  for i in xrange(1, len(lst)):
v = lst[i]
if cmp(minval, v)  0:
  minval = v

  return minval



This is from Google's goopy package.

http://goog-goopy.sourceforge.net/

-- 
Steve R. HastingsVita est
[EMAIL PROTECTED]http://www.blarg.net/~steveha

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


Re: What's the best way to learn perl for a python programmer?

2006-03-26 Thread john_sips_tea
The online docs are very good. Just run perldoc perl, and then go
through the various tutorial pages (starting with perldoc perlintro).
You can also read them online here: http://perldoc.perl.org/perl.html .

Then go to http://www.perlmonks.org . They have many tutorial-style
articles there, as well as a very helpful and knowledgeable community.

If you absolutely need to write object-oriented Perl, you probably want
to keep things as simple as possible and just use regular old
hash-based objects. Writing OO Perl code is a whole nuther ball of wax
than just writing procedural Perl code.

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


Re: Python float representation error?

2006-03-26 Thread James Stroud
[EMAIL PROTECTED] wrote:
 try running this in python:
 
 print [39.95]
 
 the output i get is:
 [39.953]
 
 what's up with that?
 

This comes from the imprecision in representing base-10 fractions as 
binary. Try print [str(39.95)].

If you want to print a list, maybe:

print map(str, alist)

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Re: interactive programme (add a new line in Tk)

2006-03-26 Thread James Stroud
nigel wrote:
 somebody recently  showed me how to create a new line using \n which was 
 great.The thing is when i am creating the programme the text i wish to add is 
 quite long.and it ends up stretching the width of several pages,which i think 
 looks quite messy.Would it be possible for some one to show me how to create 
 another line while writing my programme.What i mean by this is where my text 
 ends iv arrivedi wish to add a new line beneath to continue my text so i do 
 not reach the end of the page.
 
 from Tkinter import *
 
 root = Tk()
 
 w = Label(root, text=\n Hello, world! \n iv arrived)
 w.pack()
 
 root.mainloop()
 
 Thanks nige

Try the Tkinter.Text widget. You can configure it to be read only, etc. 
so it behaves like a label. It will automatically wrap text for you and 
will put in line breaks (\n) where you tell it. See

http://www.pythonware.com/library/tkinter/introduction/text.htm

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Re: maximum() efficency

2006-03-26 Thread Steve R. Hastings
Actually, now that I think about it, the version using iter() has one
advantage over your version: it will work correctly if passed either a
list or an iterator.  So, for versions of Python that have iterators, I'd
use the iter() version, but for older versions of Python, I'd use your
version.

P.S. I benchmarked your version; it ran in 22.0 seconds, just a gnat's
whisker faster than the iter() version.
-- 
Steve R. HastingsVita est
[EMAIL PROTECTED]http://www.blarg.net/~steveha

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


Re: maximum() efficency

2006-03-26 Thread Paul McGuire
Steve R. Hastings [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 On Sun, 26 Mar 2006 10:34:16 -0700, Steven Bethard wrote:
  What's the original?



 def minimum(cmp, lst):
   minimum(cmp, lst)

   Returns the minimal element in non-empty list LST with elements
   compared via CMP() which should return values with the same semantics
   as Python's cmp().  If there are several minimal elements, the last
   one is returned.
   

   if not lst:
 raise ValueError, 'empty list'

   minval = lst[0]

   for i in xrange(1, len(lst)):
 v = lst[i]
 if cmp(minval, v)  0:
   minval = v

   return minval



 This is from Google's goopy package.

 http://goog-goopy.sourceforge.net/

 -- 
 Steve R. HastingsVita est
 [EMAIL PROTECTED]http://www.blarg.net/~steveha


The doc string is not correct.  If there are several minimal elements, the
*first* one is returned.  See this example:

import math

class Vector(object):
def __init__(self,*x):
# x is list of n-dimensional coordinates
self.x = x

def magnitude(self):
return math.sqrt(sum(x**2 for x in self.x))

def __cmp__(self,other):
return cmp(self.magnitude(), other.magnitude())

def __str__(self):
return Vector(%s) % ,.join(str(x) for x in self.x)

a = Vector(0,1)
b = Vector(0,0)
c = Vector(1,0)

# these print 1, -1, and 0 to show that cmp() and Vector are doing the right
thing
print cmp(a,b)
print cmp(b,a)
print cmp(a,c)

print min(a,b)   # gives Vector(0,0), or b
print max(a,b,c)   # gives Vector(0,1) or a
print min(a,c)# gives Vector(0,1) or a

print minimum(Vector.__cmp__, [a,b])   # gives Vector(0,0), or b
print minimum(Vector.__cmp__, [a,c])# gives Vector(0,1) or a


-- Paul


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


Re: Python float representation error?

2006-03-26 Thread nikie
 try running this in python:

 print [39.95]

 the output i get is:
 [39.953]

 what's up with that?

That's perfectly normal - some numbers aren't exactly expressible as
binary floating points, just like 1/3 isn't expressible as a decimal
floating point number.

Here's a good link on floating point arithmetic:
http://docs.sun.com/source/806-3568/ncg_goldberg.html

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


Re: New-style Python icons

2006-03-26 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
 Personally, I *like* the new website look, and I'm glad to see Python
 having a proper logo at last!
 
 I've taken the opportunity to knock up some icons using it, finally
 banishing the poor old standard-VGA-palette snake from my desktop. If
 you like, you can grab them from:
 
   http://www.doxdesk.com/img/software/py/icons.zip

I just wanted to say that I've been using these icons for almost a week 
now and I love them!  I'd like to reiterate EuGeNe's request that these 
go into the Python 2.5 release if at all possible.

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


determine file type

2006-03-26 Thread Mark Gibson
Is there an equivalent to the unix 'file' command?

[mark tmp]$ file min.txt
min.txt: ASCII text
[mark tmp]$ file trunk
trunk: directory
[mark tmp]$ file compliance.tgz
compliance.tgz: gzip compressed data, from Unix

What I really want to do is determine if a file is 1) a directory, 2) a 
text file 3) a binary file.

Is there a way to do this?

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


Re: PIL image size reduction script

2006-03-26 Thread nikie
Philippe Martin wrote:
 Hi,

 Thanks to the NG, I got the script hereunder working.

 1) I am not certain that the call to convert does much (checking the doc)

I think you only need it if your source image comes in a format that
can't be stored into a jpeg file (e.g. 8-bit paletted). You'll need
that if you're converting from GIF files, for example. It shouldn't
hurt otherwise.

 2) Can this be improved as far as the final image size in (X,Y) ?

I'm not sure if I get you: You tell the image object it's new
(X,Y)-size in the resize method, don't you?

 For instance, passing a large .jpg with a target byte size of 7000, I get
 final (X,Y) results around (213, 174) ... but might want to strech it a bit
 while keeping the byte size.

If I got you right, you want to compress the image to a certain file
size. Maybe you should try optimizing the additional save parameters
for the jpeg encoder.
(http://www.pythonware.com/library/pil/handbook/formats.htm). Try
reducing the quality parameter.
  l_image.save(l_tmp_file_name, quality=25) 

Hope this helps.

Niki

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


  1   2   >