Re: Python to tell what is the IP of my PC

2006-11-08 Thread 空心菜
>>> import re,urllib2
>>> re.search('\d+\.\d+\.\d+\.\d+',urllib2.urlopen("http://www.hereismyip.com";).read()).group()
'xx.xx.xxx.xxx′


On 11月9日, 上午11时06分, Hieu Hoang <[EMAIL PROTECTED]>
wrote:
> Hi list,
> I think a script to extract the IP from some websites like
> whatismyip.com could do the job. I don't know how to write it though,
> sure someone can give
> direction on that.
> 
> Cheers,
> Rooy

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

Re: which is a good imaging lib in python??

2006-11-08 Thread John Machin

srj wrote:
> hi
> can any1 tell me which is a good imaging lib in python and where i can
> get it (2 dwnld) from??
>
> regds

The straight answer to your question is "Yes".

If you were to do a google search for "python imaging library", you
would then be in a position to tell yourself.

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


Re: opening excel

2006-11-08 Thread John Machin

timmy wrote:
> Hello,
>
> has anybody got any experience opening and manilpulating excel
> spreedsheets via python? it seems pythoncom allows this to happen but
> i'm a total newb to it. (i usually work in the unix world)
> all i need to do, is open the xls files and read values from it.

If you really mean "read" rather than "manipulate", have a look at the
xlrd package (of which I'm the author).

http://www.python.org/pypi/xlrd

BTW, it's pure Python; you can run it on your unix box if you like :-)

Cheers,
John

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


which is a good imaging lib in python??

2006-11-08 Thread srj
hi
can any1 tell me which is a good imaging lib in python and where i can
get it (2 dwnld) from??

regds

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


gathering data about running processes - looking for a library

2006-11-08 Thread Arkadiusz Miskiewicz
Hi,

I'm looking for a library (or utility) written in python that would allow me 
to easily access all possible information about currently running processes 
(under Linux). 

Something like /bin/ps os /bin/pstree providing all information in nice way 
(dictionary).

googling doesn't find anything so I guess no one wrote such library at this 
moment and only option left is to parse /proc data.
-- 
Arkadiusz MiśkiewiczPLD/Linux Team
arekm / maven.plhttp://ftp.pld-linux.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question regarding lists and regex

2006-11-08 Thread Paul McGuire
"Prabhu Gurumurthy" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Here is a simple program, which queries /var/log/daemon on my OpenBSD box 
> and gets the list of valid ntp peers.
>
> Questions:
> what is the easiest way for me to create lists on the fly, by that I mean 
> like perl
>
> push my @foo, something_from_say_stderr. The reason is as you can ip = 
> [""] statement before the for loop, I want to avoid that and use list 
> within the second ip loop, where I extract the ip address. Am I confusing?
>

Typically, one initializes a list to be empty, that is [], not [""].  Python 
will not read your mind at append time and think "oh! we're appending to a 
list and we forgot to create one in the first place, let's make one now."  I 
guess Perl allows this, but the clarity of including the initialization 
statement overrules the convenience of leaving it out.

> regex: I presume this is rather a dumb question, anyways here it comes! as 
> you can see from my program, pattIp = r\d{1,3}\ etc, is there any 
> other easy way to group the reptitions, instead of typing the same regex 4 
> times.
>

Here's one way, tested at the Python command line:
>>> print r'\.'.join( [r'\d{1,3}']*4 )
\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}

This avoids the pattern duplication, but I think using join is much less 
easily recognized as a pattern for an IP address.

> TIA
> Prabhu
>

Some other comments/free advice:
1. I was curious about this line:
pid = int(re.sub(r'\[|\]', "", pidMatch.group()))
You already know pidMatch.group() is going to start with a '[', followed by 
an integer string, and end with a ']', otherwise it wouldn't have matched 
pidPatt.  Instead of whacking this with another re-type call, how about just 
some simple string slicing:
pid = pidMatch.group()[1:-1]

2. No real need to keep count of the found ip's, just use len(ip) to tell 
you how many entries there are in the list (especially once you convert to 
intializing with an empty list).

3. Similarly, you'll be able to remove the 'if len(x)' test when printing 
out the contents of the ip list if you init with [] instead of [""].  Also, 
the Python idiom for testing if x is the empty string is usually just 'if 
x', not 'if len(x)'.

-- Paul


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


opening excel

2006-11-08 Thread timmy
Hello,

has anybody got any experience opening and manilpulating excel 
spreedsheets via python? it seems pythoncom allows this to happen but 
i'm a total newb to it. (i usually work in the unix world)
all i need to do, is open the xls files and read values from it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ?

2006-11-08 Thread Fernando Perez
sturlamolden wrote:

> Following up on my previous post, there is a simple Python MPI wrapper
> that can be used to exploit multiple processors for scientific
> computing. It only works for Numeric, but an adaptaion to NumPy should
> be easy (there is only one small C file in the source):
> 
> http://datamining.anu.edu.au/~ole/pypar/
> 
> If you are using Windows, you can get a free implementation of MPI
> here:
> 
> http://www-unix.mcs.anl.gov/mpi/mpich1/mpich-nt/

It's also worth noting

http://mpi4py.scipy.org

The project just moved over to scipy hosting a few days ago, and the boxes
haven't been unpacked yet.  But it is very actively developed, has full
numpy and MPI-2 support, and is looking very nice.

Cheers,

f

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


Can not download plugins for jEdit (help!!)

2006-11-08 Thread BillJosephson
Hi all. I am trying to use jEdit, but can't seem to download
any plugins. I go to Plugin Manager, and select Download
options. I update the mirro and can see lots of servers.
I select the first (plugin central default) and say apply.
In the Update dialogues bottom window, I see a msg saying
"Dowloading plugin list from jedit.plugins.org but after
a couple seconds it disappears. Inveitably when I select
Console and the click install, it give me "An I/0 error
occurred (Connection refused: connect)

If anyone knows why i can't connect, in info about it would be
a big help.

Thanks in advance.

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


Question regarding lists and regex

2006-11-08 Thread Prabhu Gurumurthy
Here is a simple program, which queries /var/log/daemon on my OpenBSD box and 
gets the list of valid ntp peers.

Questions:
what is the easiest way for me to create lists on the fly, by that I mean like 
perl

push my @foo, something_from_say_stderr. The reason is as you can ip = [""] 
statement before the for loop, I want to avoid that and use list within the 
second ip loop, where I extract the ip address. Am I confusing?

regex: I presume this is rather a dumb question, anyways here it comes! as you 
can see from my program, pattIp = r\d{1,3}\ etc, is there any other easy 
way 
to group the reptitions, instead of typing the same regex 4 times.

TIA
Prabhu
-

amazon: [~/working/programs/python/regex]
ttyp4: [109]$ cat syslog.py
#!/usr/bin/env python
# $Id: syslog.py,v 1.6 2006/11/09 06:24:03 pgurumur Exp $

import getopt, re, os, string, sys, time
(dirname, program) = os.path.split(sys.argv[0])
argc = len(sys.argv)

def usage():
print program + ": options"
print "options: "
print "  --filename | -f [ name of the file ]"
print "  --help | -h [ prints this help ]"
sys.exit(1)

if __name__ == "__main__":
if (argc <= 1):
   usage()
else:
   try:
  opts, args = getopt.getopt(sys.argv[1:], "f:h", ["help", "filename="])
   except getopt.GetoptError:
  usage()
   else:
  filename = ""
  for optind, optarg in opts:
 if optind in ("-f", "--filename"):
filename = optarg
 elif optind in ("-h", "--help"):
usage()

  if len(filename):
 fh = 0
 try:
fh = open(filename, "r")
 except IOError, (error, message):
print program + ": cannot open " + filename + ": " + message
sys.exit(1)

 pattNtp = r'.*ntpd(?=.*now\s+valid)'
 count = 0
 ip = [""]
 pid = 0
 for line in fh.readlines():
if re.match(pattNtp, line.strip(), re.IGNORECASE):
   string = line.strip()
   pattPid = r'\[\d{1,5}\]'
   pidMatch = re.search(pattPid, string, re.IGNORECASE)
   if pidMatch is not None:
  pid = int(re.sub(r'\[|\]', "", pidMatch.group()))

   pattIp = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
   match = re.search(pattIp, string, re.IGNORECASE)
   if match is not None:
  ip.append(match.group())
  count += 1

 print "NTP program started with pid:", pid
 print "Number of valid peers:", count
 for x in ip:
if len(x):
   print x

 fh.close()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [DLC] ChiPy Monthly Meeting, Thursday 7:00 pm.

2006-11-08 Thread Hendrik van Rooyen

"Steve Holden" <[EMAIL PROTECTED]>


> Hendrik van Rooyen wrote:
> >  "Steve Holden" <[EMAIL PROTECTED]> wrote:
> >
> >
> >>I don't suppose there's any chance that someone might be passing
> >>Schaumberg on their way to this meeting? I'm teaching there, and a ride
> >>would avoid me having to rent a car (and hence increase the probability
> >>I'd make it).
> >
> >
> > Where in the whole wide world is Schaumberg - "foam mountain" - is it near
> > Koekenaap?
> >
> It appears to be about twenty miles West and slightly North of the
> meeting venue. Zip code 60173, I believe, if that helps.
>
> regards
>   Steve

That puts you on the North American continent - nowhere near Koekenaap - I am
amazed that you are brave enough to be there, after implying that the locals do
not understand irony...

Anyway - a word of unwanted advice - avoid prominently high buildings, and
beware of low flying aircraft..

- Hendrik

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


Re: Problem getting a file pathname with tkFileDialog

2006-11-08 Thread Tim Daneliuk
Sefyroth wrote:
> Thank you!!! I have had problems with other stuff because of this
> (mainly py2exe!)
> 
> It did the job! I thank you a lot.

My pleasure.

> 
> Just wondering though,
> 
> D:/Travaux/5ème session/B51 - Dev. de
   ^
> Systèmes/Workspace/LMAOSoft/Controleur.py
   ^
I would guess that these are the characters causing the problem.
Strictly speaking, "ASCII" only goes from 0-127 IIRC with the
high bit being sort of system dependent (I could be wrong, but
that seems to tickle something deep in ancient memories).

> That's my filepath, what is not ASCII in there? è
> 
> Just checked and it's 138 in ascii... Anyway, thanks a lot
> 
> Christian
> 
> 
> Tim Daneliuk wrote:
>> Sefyroth wrote:
>>> Thanks,
>>>
>>> but I get this error when I try this.
>>>
>>> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in
>>> position 12: ordinal not in range(128)
>>>
>>>  I had encountered it with the askdirectory method as well. Is there an
>>> easy way to bypass this?
>>>
>>> Thanks again
>> I believe you are running into a directory or file name that has
>> non-ascii characters in it.  Python as shipped is set up to
>> deal with ascii as its native encoding format.  You can change
>> this by editing the "site.py" file - look in the Lib directory
>> in your python installation.  Look for this code:
>>
>> ---
>> def setencoding():
>>  """Set the string encoding used by the Unicode implementation.  The
>>  default is 'ascii', but if you're willing to experiment, you can
>>  change this."""
>>  encoding = "ascii" # Default value set by _PyUnicode_Init()
>>  if 0:
>>  # Enable to support locale aware default string encodings.
>>  import locale
>>  loc = locale.getdefaultlocale()
>>  if loc[1]:
>>  encoding = loc[1]
>> ---
>>
>>
>>
>> Change the "if 0:" to "if 1:" and see if that doesn't fix the problem.
>>
>>
>>
>> --
>> 
>> Tim Daneliuk [EMAIL PROTECTED]
>> PGP Key: http://www.tundraware.com/PGP/
> 


-- 

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cactching Stdout

2006-11-08 Thread Stephan Kuhagen
Dennis Lee Bieber wrote:

>> popen...is this what I need? How can I use them? It is very important
>> for me that I could take the output in real-time.
>> Thanks for the help!
>> Massi
> 
> That's going to be difficult... popen and pipes work when one
> process starts another INDEPENDENT process.

I'm not sure, if it fits the problem, but just a few days ago I had the
problem to catch the stdout and stderr of a module to process it before
writing it to the console. What I did was basically this:

---
import sys
import StringIO

# save the original streams
_stdout_ = sys.stdout
_stderr_ = sys.stderr

# create StringIO string buffers to replace streams
sys.stdout = StringIO.StringIO()
sys.stderr = StringIO.StringIO()

# Now print something, this goes to the string buffers instead of console
print "Hello World to stdout"
sys.stderr.write("Hello World to stderr\n")

# Now process the contents of the buffers...
...
# ...and print them to the real console afterwards
_stdout_.write(sys.stdout)
_stderr_.write(sys.stderr)

# Clean up the string buffers for the next IO
sys.stdout.truncate(0)
sys.stderr.truncate(0)
---

Of course you should put all that into defs and create own write/print
functions to encapsulate the whole buffering/processing/cleanup.

This works great for scripting, but I'm pretty sure, that it does not work
for C Libraries in Python. But I do not know, how Python handles its
streams internally, so it might be worth a try.

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


Re: decorators

2006-11-08 Thread [EMAIL PROTECTED]
John Henry wrote:
> I must be very thick.  I keep reading about what decorators are and I
> still don't have a good feel about it.  See, for example:
>
> http://alex.dojotoolkit.org/?p=564
>
> What exactly do I use decorators for?

Metafunctions.  Saying

@mydecorator
def foo(...):
  ...

is just an alternative way of writing:
def foo(...):
  ...
foo = mydecorator(foo)

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


Re: Using Python from Cocoa App via PyObjc - numbers dont match...

2006-11-08 Thread sapsi
Hi,
Well not a complaint as such but a question. Thank you for the response
however and the link. I have seen it before but never got around to
reading it...

Further to this, if i was writing a python module and  c function and
suppose the python module and the c  function called each other back
and forth exchanging results from float calculations  - would not the
results then become flawed? How would one pass floats between different
languages - using special purpose data structures understood by both
the python module and c code?

I asked this question without reading the link, so if it stinks of
ignorance please forget it.

Thank you
Saptarshi


Michael Ash wrote:
> In comp.lang.objective-c sapsi <[EMAIL PROTECTED]> wrote:
> > The first output in the console is 40.4 and the second
> > -40.4152587891.
> >
> > If i change the NSLog(s)  to "%f",[n floatValue] (and the second
> > likewise) the first is 40.42 and the second is -40.42.
>
> I assume you are complaining about the fact that it's not printing exactly
> 40.4, and wondering where the error is coming from. (It helps if you
> actually state this yourself, so we don't have to assume it, rather than
> just laying out the circumstances.)
>
> The answer is that floating point numbers are inherently imprecise. Read
> through this essential resource:
>
> http://docs.sun.com/source/806-3568/ncg_goldberg.html
> 
> -- 
> Michael Ash
> Rogue Amoeba Software

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


Re: string to list of numbers conversion

2006-11-08 Thread henning
[EMAIL PROTECTED] skrev:

> Hi,
>   I have a string '((1,2), (3,4))' and I want to convert this into a
> python tuple of numbers.

I think your question is deeper and more natural than is clear from the
many recepies given so far in this thread, so I'll take on another
point of view,

>From a language design perspective, there is no reason why not the
parsing capacity of the Python interpreter would be accessible in a
modular fashion to the user/programmer. E.g used like this:

I an imaginable Python, define you expect for an answer. In this case:
(1)
# import junctions, types from maybefuture:-)
string = ((1,2), (3,4))
type a = tuple a | int
myTuple = eval(string, goal=a)


Obviously, if you expect _only_ the given form, then this might be
better:

(2)
# import types from maybefuture:-)
type a = ((int,int),(int,int))
myTuple = eval(string, goal=a)

Note the use of a "a|b" in line 2 (I think Perl 6 is among the few
programming languages giving a reasonable semantics to junctions so
far).

Version 2 above sholud not be a big addition to Python conceptually.
Motivation:
It is easy to think clearly about.
It makes it easier to use eval safely and makes code more readable.

This is a topic of interest to me, so feel free to post either on list
or directly to me.

Thanks/Henning

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


Re: Strange re problem on OSX but Not Linux

2006-11-08 Thread Brian

Paul McGuire wrote:
> "Gabriel Genellina" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > Dont use regex as a name. Also, do you have any script called "re.py"
> > hidding that library module? or regex.py?
>
> My bet is that a local re.py is masking the lib module.  (It's a shame this
> error is so easy to trip over.)
>
> -- Paul

I figured that one out so I renamed the file.  Unfortunately it took me
a while to realize that I needed to delete re.pyc as well.

Brian

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


Re: Python deployment options

2006-11-08 Thread Hieu Hoang
Hi list,
I have packaged a few pygames to one exe file with pyinstaller ( http:/
/pyinstaller.python-hosting.com/ ), sent them to my friends and the 
executables 
work. Running them shows a Fatal Error dialog box with only 
"MSVCR71.DLL", but nothing breaks, despite whether the system has 
python or not.
I haven't been able to figure out py2exe setup script yet, so I can't 
compare them.

Hope this helps,
Rooy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python to tell what is the IP of my PC

2006-11-08 Thread Hieu Hoang
Hi list,
I think a script to extract the IP from some websites like 
whatismyip.com could do the job. I don't know how to write it though, 
sure someone can give 
direction on that.

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


Re: help using smtplib to work ..

2006-11-08 Thread Jordan
Your post was definitely the most helpful for me.  For some reason,
smtp for gmail seems to require that you call server.ehlo() a second
time, after having called server.starttls(), otherwise, the server
won't accept authorization.  Thanks.

-Jordan


Gabriel Genellina wrote:
> At Wednesday 8/11/2006 19:23, NicolasG wrote:
>
> >I'm using the following code to send e-mail through python:
> >
> >import smtplib
> >
> >fromaddr = '[EMAIL PROTECTED]'
> >toaddrs  = '[EMAIL PROTECTED]'
> >subject = 'someting for subject !'
> >
> >msg = 'This is body of the mail.'
> >
> >msg = 'From: ' + fromaddr + '\nTo: ' + toaddrs + '\nSubject:' + subject
> >+ '\n\n' + msg
> >print "Message length is " + repr(len(msg))
> >
> >server = smtplib.SMTP('smtp.gmail.com')
> >server.set_debuglevel(1)
> >server.sendmail(fromaddr, toaddrs, msg)
> >server.quit()
> >
> >send: 'mail FROM:<[EMAIL PROTECTED]> size=106\r\n'
> >reply: '530 5.7.0 Must issue a STARTTLS command first
> >s1sm7666914uge\r\n'
> >
> >What am I doing wrong ?
>
> gmail.com requires authentication before sending mail. Try this
> sequence: ehlo, starttls, ehlo (again!), login, sendmail, quit
> (BTW, you need a space after Subject:, and all \n should be \r\n)
>
>
> --
> Gabriel Genellina
> Softlab SRL
>
> __
> Correo Yahoo!
> Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
> ¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar

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


Re: Problem getting a file pathname with tkFileDialog

2006-11-08 Thread Sefyroth
Thank you!!! I have had problems with other stuff because of this
(mainly py2exe!)

It did the job! I thank you a lot.

Just wondering though,

D:/Travaux/5ème session/B51 - Dev. de
Systèmes/Workspace/LMAOSoft/Controleur.py
That's my filepath, what is not ASCII in there? è

Just checked and it's 138 in ascii... Anyway, thanks a lot

Christian


Tim Daneliuk wrote:
> Sefyroth wrote:
> > Thanks,
> >
> > but I get this error when I try this.
> >
> > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in
> > position 12: ordinal not in range(128)
> >
> >  I had encountered it with the askdirectory method as well. Is there an
> > easy way to bypass this?
> >
> > Thanks again
>
> I believe you are running into a directory or file name that has
> non-ascii characters in it.  Python as shipped is set up to
> deal with ascii as its native encoding format.  You can change
> this by editing the "site.py" file - look in the Lib directory
> in your python installation.  Look for this code:
>
> ---
> def setencoding():
>  """Set the string encoding used by the Unicode implementation.  The
>  default is 'ascii', but if you're willing to experiment, you can
>  change this."""
>  encoding = "ascii" # Default value set by _PyUnicode_Init()
>  if 0:
>  # Enable to support locale aware default string encodings.
>  import locale
>  loc = locale.getdefaultlocale()
>  if loc[1]:
>  encoding = loc[1]
> ---
>
>
>
> Change the "if 0:" to "if 1:" and see if that doesn't fix the problem.
>
>
>
> --
> 
> Tim Daneliuk [EMAIL PROTECTED]
> PGP Key: http://www.tundraware.com/PGP/

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

Re: Using Python from Cocoa App via PyObjc - numbers dont match...

2006-11-08 Thread Michael Ash
In comp.lang.objective-c sapsi <[EMAIL PROTECTED]> wrote:
> The first output in the console is 40.4 and the second
> -40.4152587891.
> 
> If i change the NSLog(s)  to "%f",[n floatValue] (and the second
> likewise) the first is 40.42 and the second is -40.42.

I assume you are complaining about the fact that it's not printing exactly 
40.4, and wondering where the error is coming from. (It helps if you 
actually state this yourself, so we don't have to assume it, rather than 
just laying out the circumstances.)

The answer is that floating point numbers are inherently imprecise. Read 
through this essential resource:

http://docs.sun.com/source/806-3568/ncg_goldberg.html

-- 
Michael Ash
Rogue Amoeba Software
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: auto indent

2006-11-08 Thread [EMAIL PROTECTED]
M.N.Smadi wrote:

> i have a script that is not indented properly. Is there
> a way that i can have it auto indented.

FWIW the Zeus for Windows IDE will fold Pyhon code:

   http://www.zeusedit.com/features.html

With the code folded you can then select the folded line and
using 'tab'/'shift tab' Zeus will indent/re-indent all the
lines contained in the fold.

It is not an automatic re-indenting solution but it might be
better than nothing ;)

Jussi Jumppanen
Author: Zeus for Windows IDE

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


Re: is this the right way to do subclasses?

2006-11-08 Thread Gabriel Genellina

At Wednesday 8/11/2006 22:35, Ben Finney wrote:


class Character(object):
stat_keys = ['strength', 'dexterity', 'intelligence']
def __init__(self, name, stats):
self.name = name
self.health = 10
self.stats = {}
for (key, value) in [(k, stats.get(k)) for k in stat_keys]:
setattr(self, key, value)


Doesn't work, should say self.stat_keys. I prefer this other way:

=== cut ===
class Character(object):
stat_keys = ['strength', 'dexterity', 'intelligence']
strength = dexterity = intelligence = 0
def __init__(self, name, **stats):
self.name = name
self.health = 10
for key, value in stats.iteritems():
if key in self.stat_keys: setattr(self, key, value)
else: raise KeyError, "Unknown stats name: %s" % key

class Cleric(Character):
stat_keys = Character.stat_keys + ['holyness']
holyness = 0

c=Cleric('Fray Tuck', strength=8, dexterity=5, holyness=2)
print vars(c)
=== cut ===

This way, misspelled properties are caught, and calling interfase is 
simple too. Also, class attributes provide default instance 
attributes - you don't have to provide an explicit value. Stats names 
are extensible as shown.



--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python to tell what is the IP of my PC .

2006-11-08 Thread Cameron Walsh
Gabriel Genellina wrote:
> At Wednesday 8/11/2006 21:18, Nicolas G wrote:
> 
>> > How can I use python to get the real IP address of my DSL router (when
>> > my PC is part of the local home LAN) ?
>>
>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/162994
>>
>>
>> import
>>  win32api raise the error "module not exsit"

http://sourceforge.net/projects/pywin32/

>> and
>> socket.gethostbyname(name)the router doesn't have a hostname.

use the hostname you create on noip.com or dyndns.com etc.


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


Re: Python cgi Apache os.system()

2006-11-08 Thread Cameron Walsh
[EMAIL PROTECTED] wrote:
> Hello :)
> 
> I have installed Apache on windows...
> The server work well, and my python script also
> 
> but when I want in my python script to run a System command like
> os.system(my_command) the script doesn't do anything!
> 
> here the error.log
> 
> [Wed Nov 08 14:19:30 2006] [error] [client 127.0.0.1] The system cannot
> find the drive specified.\r, referer:
> http://127.0.0.1/cgi-bin/extract_source.py
> 
> When i run the python script manually it works!
> 
> i think it's a user access probleme but i don't know how to resolve it
> !
> 
> please help  
> thanks
> 

Without knowing what "my_command" is, all I can suggest is that
"my_command" might be referring to a file that is in your user path, but
not in the path of the user used to run apache or python (which could be
"nobody").

Depending on how securely your server is configured, you may be able to
access whichever file it is looking for if you specify the full path to
the file, or the relative path from the server root directory (watch out
for hardlinks/softlinks.)

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


Re: Python to tell what is the IP of my PC .

2006-11-08 Thread BartlebyScrivener

NicolasG wrote:
> How can I use python to get the real IP address of my DSL router

http://whatismyip.com

rd

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


Re: substring search without using built in utils

2006-11-08 Thread Gabriel Genellina

At Wednesday 8/11/2006 22:29, zeal elite wrote:

I am looking for substring search python program without using the 
built in funtions like find, or 'in'.


The only reasonable usage for such a constraint would be a school 
assignment so: don't cheat and do your homework!



--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Using Python from Cocoa App via PyObjc - numbers dont match...

2006-11-08 Thread Gabriel Genellina

At Wednesday 8/11/2006 22:22, sapsi wrote:


I managed to create a python class and instantiate that from my
Objective C Cocoa App (its not a python app). [...]
The first output in the console is 40.4 and the second
-40.4152587891.

If i change the NSLog(s)  to "%f",[n floatValue] (and the second
likewise) the first is 40.42 and the second is -40.42.

Why does this happen?


This is mostly independent on the language in use.
Numbers like 40.4 don't have, in general, an exact binary representation.
See http://docs.python.org/tut/node16.html


--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python to tell what is the IP of my PC .

2006-11-08 Thread Gabriel Genellina

At Wednesday 8/11/2006 21:18, Nicolas G wrote:


> How can I use python to get the real IP address of my DSL router (when
> my PC is part of the local home LAN) ?

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

import
 win32api raise the error "module not exsit"
and
socket.gethostbyname(name)the router doesn't have a hostname.


Use the small script in the recipe's comments section.


--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: profanity on comp.lang.python (was Re: Pyro stability)

2006-11-08 Thread skip

Irmen> So there. Finally back on the original subject ;-)

And without satisfying Godwin's Law.  Pretty good.

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


Re: is this the right way to do subclasses?

2006-11-08 Thread Ben Finney
John Salerno <[EMAIL PROTECTED]> writes:

> Ok, back to my so-called "game." I'm just curious if I've
> implemented the subclasses properly, because it seems like an awful
> lot of repetition with the parameters. And again, if I want to add a
> new attribute later, I'd have to change a lot of things. I can't
> help but get the feeling that I'm doing something very
> inefficiently.

This is another reason why passing the "stats" values as a mapping
object is a good alternative.

> class Character(object):
>  def __init__(self, name, strength, dexterity, intelligence):
>  self.name = name
>  self.health = 10
>  self.strength = strength
>  self.dexterity = dexterity
>  self.intelligence = intelligence

class Character(object):
stat_keys = ['strength', 'dexterity', 'intelligence']
def __init__(self, name, stats):
self.name = name
self.health = 10
self.stats = {}
for (key, value) in [(k, stats.get(k)) for k in stat_keys]:
setattr(self, key, value)

> class Fighter(Character):
>  def __init__(self, name, strength, dexterity, intelligence):
>  Character.__init__(self, name, strength, dexterity, intelligence)
>  self.health += 2
>  self.strength += 1

class Fighter(Character):
def __init__(self, name, stats):
Character.__init__(self, name, stats)
self.health += 1
self.strength += 1

et cetera.

All you need to do to add a new type of "stat" is to add a new item to
the 'stat_keys' list in Character.

-- 
 \  "I bought a self learning record to learn Spanish. I turned it |
  `\on and went to sleep; the record got stuck. The next day I |
_o__)could only stutter in Spanish."  -- Steven Wright |
Ben Finney

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


substring search without using built in utils

2006-11-08 Thread zeal elite

Hi,

I am looking for substring search python program without using the built in 
funtions like find, or 'in'.


Appreciate it. Thanks in advance.
zeal

_
Find a local pizza place, music store, museum and more…then map the best 
route!  http://local.live.com?FORM=MGA001


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

Re: assigning values in __init__

2006-11-08 Thread Ben Finney
John Salerno <[EMAIL PROTECTED]> writes:

> Ben Finney wrote:
> > If you pass a *mapping* of the
> > "I-might-want-to-add-more-in-the-future" values, then you get both
> > explicit *and* expandable, without an arbitrary unneeded sequence.
>
> Do you mean by using the **kwargs parameter?

No. I mean what I said in this earlier post on this thread:

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

If you have a group of named, semantically-related, unsequenced
values, pass them into the function as a mapping object (a dict
object).

-- 
 \ "I have yet to see any problem, however complicated, which, |
  `\  when you looked at it in the right way, did not become still |
_o__) more complicated."  -- Paul Anderson |
Ben Finney

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


Using Python from Cocoa App via PyObjc - numbers dont match...

2006-11-08 Thread sapsi
Hi,
I managed to create a python class and instantiate that from my
Objective C Cocoa App (its not a python app).
Essentially, i made two classes in IB and then another class(ogle) with
outlets for these two.

Now here is the implementation for ogle.m
-(void)awakeFromNib
{
NSNumber *n=[NSNumber numberWithFloat:40.4];
NSLog(@"%@",n);

NSNumber *b=[it2 printNok:n];
NSLog(@"%@",b);

//
}
The first output in the console is 40.4 and the second
-40.4152587891.

If i change the NSLog(s)  to "%f",[n floatValue] (and the second
likewise) the first is 40.42 and the second is -40.42.

Why does this happen?
Thanks
Saptarshi

p.s the python routine printNok, just returns the negative of the
number i.e printNok:

def printNok_(self, obj):
return -obj

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


Re: python Error: IndentationError: expected an indented block

2006-11-08 Thread Ben Finney
Please don't post HTML message bodies to a public forum.

Antonios Katsikadamos <[EMAIL PROTECTED]> writes:

> hi all. I am using python 2.4. I have to run an older python code
> and when i run it i get the following message
> IndentationError: expected an indented block.
> 1)what does this mean?

It's self-explanatory. There's an error in the indentation; Python was
expecting an indented block, but didn't get one.

> 2)how can i overcome this problem

Fix the indentation. As you probably know, in Python, indentation is
syntactically significant information to both the programmer and to
the interpreter. If that information is lost, Python can't know what
was meant, and refuses to guess.

Probably something has mangled the white-space in the program
file. Either fix it manually, or go back to a more canonical form of
the file and see if it's been altered.

-- 
 \  "I have a large seashell collection, which I keep scattered on |
  `\the beaches all over the world. Maybe you've seen it."  -- |
_o__)Steven Wright |
Ben Finney

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


Re: help using smtplib to work ..

2006-11-08 Thread Tim Williams
On 09/11/06, Nicolas G <[EMAIL PROTECTED]> wrote:
>
>
> >
> > Usually when sending/relaying without authentication,  the From is
> > irrelevant, only the To is taken into account.  Maybe, GMAIL do
> > something different because they have to put the mail in the sender's
> > mailbox as well as the recipient's.   Some ISPs will only allow a
> > local FROM address though.
> >
> > As we're only talking about the envelope TO & FROM, you could try no
> > FROM address (None or <> I forget which Smtplib needs) .
>
> If I left From empty I don't get any error but I still don't receive any
> message.
>
> >  The header FROM can still have the real FROM address in it, as its not
> (normally)
> > used during SMTP relaying.
>
> How you can explain that only for some address in the From field I can
> receive mails' and from others I can't ?
> It looks really weird to me...

It must be down to how gmail's server(s) work.

> Other question : Suppose I use the login procedure, the password will be
> vulnerable to attacks ? If I'm right I think when no ssl is used for
> authentication some one can easy see the password just by sniffing the
> packets.

I think the risk is low to be honest.   However, smtp.gmail.com uses
TLS (SSL) on ports 465 or 587.   You can call STARTTLS from within
smtplib.  but TrevorP's TLS-lite extensions to smtplib handle it
better

http://trevp.net/tlslite/

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


Re: Python to tell what is the IP of my PC .

2006-11-08 Thread Nicolas G
On 11/9/06, Tim Williams <[EMAIL PROTECTED]> wrote:
On 8 Nov 2006 15:35:31 -0800, NicolasG <[EMAIL PROTECTED]> wrote:> How can I use python to get the real IP address of my DSL router (when> my PC is part of the local home LAN) ?
The router will the PC's default gateway IP address,  if you are on awindows platform,  you can view it by typing IPCONFIG (enter) from acommand prompt.This is the  router local IP, I need to get the router "outside" IP witch is the real one. 
A quick google, gave me this,  look at the comments at the end for anexample of finding the Default Gateway IP address using Python
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/162994import
 win32api raise the error "module not exsit"and socket.gethostbyname(name)the router doesn't have a hostname.cheers ;)-- Nicolas GSkype: nicolasg_
mobile: +30 69 45 714 578
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python to tell what is the IP of my PC .

2006-11-08 Thread Tim Williams
On 09/11/06, Nicolas G <[EMAIL PROTECTED]> wrote:
>
>
> On 11/9/06, Tim Williams <[EMAIL PROTECTED]> wrote:
> > On 8 Nov 2006 15:35:31 -0800, NicolasG <[EMAIL PROTECTED]> wrote:
> > > How can I use python to get the real IP address of my DSL router (when
> > > my PC is part of the local home LAN) ?
> >
> > The router will the PC's default gateway IP address,  if you are on a
> > windows platform,  you can view it by typing IPCONFIG (enter) from a
> > command prompt.
>
> This is the  router local IP, I need to get the router "outside" IP witch is
> the real one.

Oh sorry I missed that.

In that case,  get a free dynamic hostname from someone like noip.com.
Install their client on your PC.   The client will keep the hostname
updated with your "real" external IP address,  and you can use
socket.gethostbyname(hostname) to query it.

It will only take a few minutes to set up the NO-IP account and client

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


Re: profanity on comp.lang.python (was Re: Pyro stability)

2006-11-08 Thread Irmen de Jong
Jorge Godoy wrote:
> Cliff Wells <[EMAIL PROTECTED]> writes:
> 
>> I think this sums up my point of view as well (although I would have
>> used around 3215 more words to say it). 
> 
> H...  Putting this on the discussion of the week: you'd have used
> range(3215) or xrange(3215) more words?  ;-)
> 

Actually I've just replaced a loop in Pyro from using range to using
xrange because of memory issue when you wanted to run it nearly
indefinitely.

So there. Finally back on the original subject ;-)


Thanks for the praise about Pyro but yeah, I would have been
equally happy if it was put without using the f word :)

Cheers

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


Re: PIL - Pixel Level Image Manipulation?

2006-11-08 Thread Max Erickson
"Gregory Piñero" <[EMAIL PROTECTED]> wrote:

> On 11/8/06, Gregory Piñero <[EMAIL PROTECTED]> wrote:
>> I want to be able to randomly change pixels in an image and view
>> the results.  I can use whatever format of image makes this
>> easiest, e.g., gray scale, bit tonal, etc.
>>
>> Ideally I'd like to keep the pixels in an intermediate format
>> like a list of (integers?) or an array and convert that to an
>> image as needed.
>>
>> I'm hoping someone has some experience on this and could offer
>> some advice or code.  I thought it would be easy in PIL  but I'm
>> not sure. 
> 
> I did find these functions after more searching:
> http://mail.python.org/pipermail/image-sig/2002-July/001914.html
> 
> Perhaps I'll try those out tonight if I don't hear of anything
> better in the meantime.
> 
> -Greg

Maybe something of use at:

http://online.effbot.org/2005_10_01_archive.htm#20051003


max

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

Re: Python to tell what is the IP of my PC .

2006-11-08 Thread Tim Williams
On 8 Nov 2006 15:35:31 -0800, NicolasG <[EMAIL PROTECTED]> wrote:
> How can I use python to get the real IP address of my DSL router (when
> my PC is part of the local home LAN) ?

The router will the PC's default gateway IP address,  if you are on a
windows platform,  you can view it by typing IPCONFIG (enter) from a
command prompt.

A quick google, gave me this,  look at the comments at the end for an
example of finding the Default Gateway IP address using Python

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

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


Re: help using smtplib to work ..

2006-11-08 Thread Tim Williams
On 8 Nov 2006 15:31:27 -0800, NicolasG <[EMAIL PROTECTED]> wrote:
>
> > 
> >
> > Under outgoing mail smtp server, use smtp.gmail.com. Since it requires SMTP
> > authorization, use your Gmail account as username (e.g. [EMAIL PROTECTED]) 
> > and
> > your Gmail password as password. You can turn TSL on or off.
> >
> > 
> >
> > The email server requires authentication before it can send.
> > Normally this can be accomplished either by calling
> >
> Actually I used alt1.gmail-smtp-in.l.google.com for a server I don't
> need authentication. The problem is that for some mail addresses I can
> send mail's while for other's I can't . I don't know how to explained
> that.

Without authentication, you will only be able to send to the severs
local addresses eg [EMAIL PROTECTED]  [EMAIL PROTECTED]

> > The only alternative is to use an open relay email server that allows
> > you to send without authenticating.  Hope info at least points you in
> > the right direction.

or you can probably use your ISP's outgoing mail server, which usually
won't require authentication.

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


Re: pack a three byte int

2006-11-08 Thread John Machin
[EMAIL PROTECTED] wrote:
> Can Python not express the idea of a three-byte int?

It is a bit hard to determine what that (rhetorical?) question means.
Possible answers:
1. Not as concisely as a one-byte struct code -- as you presumably have
already determined by reading the manual ...
2. No, but when 24-bit machines become as popular as they were in the
1960s, feel free to submit an enhancement request :-)

>
> For instance, in the working example below, can we somehow collapse the
> three calls of struct.pack into one?
>
> >>> import struct
> >>>
> >>> skip = 0x123456 ; count = 0x80
> >>>
> >>> cdb = ''
> >>> cdb += struct.pack('>B', 0x08)
> >>> cdb += struct.pack('>I', skip)[-3:]
> >>> cdb += struct.pack('>BB', count, 0)
> >>>
> >>> print ' '.join(['%02X' % ord(xx) for xx in cdb])
> 08 12 34 56 80 00
> >>>

You could try throwing the superfluous bits away before packing instead
of after:

| >>> from struct import pack
| >>> skip = 0x123456; count = 0x80
| >>> hi, lo = divmod(skip, 0x1)
| >>> cdb = pack(">BBHBB", 0x08, hi, lo, count, 0)
| >>> ' '.join(["%02X" % ord(x) for x in cdb])
| '08 12 34 56 80 00'

but why do you want to do that to concise working code???

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


Python to tell what is the IP of my PC .

2006-11-08 Thread NicolasG
How can I use python to get the real IP address of my DSL router (when
my PC is part of the local home LAN) ?

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


Re: help using smtplib to work ..

2006-11-08 Thread NicolasG

> 
>
> Under outgoing mail smtp server, use smtp.gmail.com. Since it requires SMTP
> authorization, use your Gmail account as username (e.g. [EMAIL PROTECTED]) and
> your Gmail password as password. You can turn TSL on or off.
>
> 
>
> The email server requires authentication before it can send.
> Normally this can be accomplished either by calling
>
Actually I used alt1.gmail-smtp-in.l.google.com for a server I don't
need authentication. The problem is that for some mail addresses I can
send mail's while for other's I can't . I don't know how to explained
that.

> server.login(userid, password)
>
> The only alternative is to use an open relay email server that allows
> you to send without authenticating.  Hope info at least points you in
> the right direction.
>
the code bellow worked fine to me :

import smtplib

fromaddr = '[EMAIL PROTECTED]'
toaddrs  = '[EMAIL PROTECTED]'
subject = 'someting for subject !'

msg = 'This is body of the mail.'

msg = 'From: ' + fromaddr + '\nTo: ' + toaddrs + '\nSubject: ' +
subject + '\n\n' + msg
print "Message length is " + repr(len(msg))

server = smtplib.SMTP('alt1.gmail-smtp-in.l.google.com')
#'smtp.gmail.com')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

cheers.

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


Re: Barry Warsaw giving Python talk at NASA

2006-11-08 Thread William Allison
A.M. Kuchling wrote:
> This is at the Goddard campus:
> 
> 
> --amk
Thanks for the heads up on this.  I managed to get escorted in to see 
it.  Thought it was quite good.  I was also informed that the webcast 
will be made available to the public.
-- 
http://mail.python.org/mailman/listinfo/python-list


pack a three byte int

2006-11-08 Thread p . lavarre
Can Python not express the idea of a three-byte int?

For instance, in the working example below, can we somehow collapse the
three calls of struct.pack into one?

>>> import struct
>>>
>>> skip = 0x123456 ; count = 0x80
>>>
>>> cdb = ''
>>> cdb += struct.pack('>B', 0x08)
>>> cdb += struct.pack('>I', skip)[-3:]
>>> cdb += struct.pack('>BB', count, 0)
>>>
>>> print ' '.join(['%02X' % ord(xx) for xx in cdb])
08 12 34 56 80 00
>>>

I ask because I'm trying to refactor working code that is concise:

>>> cdb0 = '\x08' '\x12\x34\x56' '\x80' '\0'
>>> print ' '.join(['%02X' % ord(xx) for xx in cdb0])
08 12 34 56 80 00
>>>

Thanks in advance, Pat LaVarre

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


Re: help using smtplib to work ..

2006-11-08 Thread Gabriel Genellina

At Wednesday 8/11/2006 19:23, NicolasG wrote:


I'm using the following code to send e-mail through python:

import smtplib

fromaddr = '[EMAIL PROTECTED]'
toaddrs  = '[EMAIL PROTECTED]'
subject = 'someting for subject !'

msg = 'This is body of the mail.'

msg = 'From: ' + fromaddr + '\nTo: ' + toaddrs + '\nSubject:' + subject
+ '\n\n' + msg
print "Message length is " + repr(len(msg))

server = smtplib.SMTP('smtp.gmail.com')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

send: 'mail FROM:<[EMAIL PROTECTED]> size=106\r\n'
reply: '530 5.7.0 Must issue a STARTTLS command first
s1sm7666914uge\r\n'

What am I doing wrong ?


gmail.com requires authentication before sending mail. Try this 
sequence: ehlo, starttls, ehlo (again!), login, sendmail, quit

(BTW, you need a space after Subject:, and all \n should be \r\n)


--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: help using smtplib to work ..

2006-11-08 Thread Larry Bates
NicolasG wrote:
> I'm using the following code to send e-mail through python:
> 
> import smtplib
> 
> fromaddr = '[EMAIL PROTECTED]'
> toaddrs  = '[EMAIL PROTECTED]'
> subject = 'someting for subject !'
> 
> msg = 'This is body of the mail.'
> 
> msg = 'From: ' + fromaddr + '\nTo: ' + toaddrs + '\nSubject:' + subject
> + '\n\n' + msg
> print "Message length is " + repr(len(msg))
> 
> server = smtplib.SMTP('smtp.gmail.com')
> server.set_debuglevel(1)
> server.sendmail(fromaddr, toaddrs, msg)
> server.quit()
> 
> I have replaced the sender and receiver's mail address with the
> original ones but executing this code I get the error (ip is hided for
> obvious reason):
> 
> send: 'ehlo computer.domain_not_set.invalid\r\n'
> reply: '250-mx.google.com at your service, [xxx.xx.xxx.xxx]\r\n'
> reply: '250-SIZE 20971520\r\n'
> reply: '250-8BITMIME\r\n'
> reply: '250-STARTTLS\r\n'
> reply: '250 ENHANCEDSTATUSCODES\r\n'
> reply: retcode (250); Msg: mx.google.com at your service,
> [xxx.xx.xxx.xxx]
> SIZE 20971520
> 8BITMIME
> STARTTLS
> ENHANCEDSTATUSCODES
> send: 'mail FROM:<[EMAIL PROTECTED]> size=106\r\n'
> reply: '530 5.7.0 Must issue a STARTTLS command first
> s1sm7666914uge\r\n'
> reply: retcode (530); Msg: 5.7.0 Must issue a STARTTLS command first
> s1sm7666914uge
> send: 'rset\r\n'
> reply: '250 2.1.0 Flushed s1sm7666914uge\r\n'
> reply: retcode (250); Msg: 2.1.0 Flushed s1sm7666914uge
> Traceback (most recent call last):
>   File "C:\Documents and Settings\NicolasG\Desktop\smtpexample.py",
> line 17, in 
> server.sendmail(fromaddr, toaddrs, msg)
>   File "C:\Python25\lib\smtplib.py", line 684, in sendmail
> raise SMTPSenderRefused(code, resp, from_addr)
> SMTPSenderRefused: (530, '5.7.0 Must issue a STARTTLS command first
> s1sm7666914uge', '[EMAIL PROTECTED]')
> 
> What am I doing wrong ?
> 



Under outgoing mail smtp server, use smtp.gmail.com. Since it requires SMTP
authorization, use your Gmail account as username (e.g. [EMAIL PROTECTED]) and
your Gmail password as password. You can turn TSL on or off.



The email server requires authentication before it can send.
Normally this can be accomplished either by calling

server.login(userid, password)

The only alternative is to use an open relay email server that allows
you to send without authenticating.  Hope info at least points you in
the right direction.

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


Re: decorators

2006-11-08 Thread Paul McGuire
"Carsten Haese" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> If none of the examples make you say
> "wow, I could use this" and if you don't find yourself writing
> repetitive setup/teardown/housekeeping code, you can probably live quite
> comfortably without using decorators.
>

Amen!  Don't force yourself to learn decorators if you don't need them at 
the moment.  Wait until you start repeating the same code (lock/unlock, 
dbready/dbcommit, logstart/logend, etc.) around multiple functions, then go 
back and try applying a decorator to simplify the job.  Having a real use 
for them will make it much easier to "get".

I will say, though, that I found the memoizing decorator to be especially 
intriguing and eye-opening, and didn't realize I needed it until I saw it 
laid out in front of me.

-- Paul


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


Re: is this the right way to do subclasses?

2006-11-08 Thread Bruno Desthuilliers
John Salerno a écrit :
> Peter Otten wrote:
> 
>> You may need a no-op implementation of fix_attributes() in the Character
>> class.
> 
> 
> What does that mean? Is that in case I use Character directly to create 
> an object?

Most propbably it can be useful for other character classes that don't 
need too fix attributes.

> Would that just be a 'pass' statement?

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


Re: is this the right way to do subclasses?

2006-11-08 Thread Bruno Desthuilliers
John Salerno a écrit :
> Ok, back to my so-called "game." I'm just curious if I've implemented 
> the subclasses properly, because it seems like an awful lot of 
> repetition with the parameters. And again, if I want to add a new 
> attribute later, I'd have to change a lot of things. I can't help but 
> get the feeling that I'm doing something very inefficiently.
> 
> Thanks!
> 
> 
> 
> class Character(object):
> 
> def __init__(self, name, strength, dexterity, intelligence):
> self.name = name
> self.health = 10
> self.strength = strength
> self.dexterity = dexterity
> self.intelligence = intelligence
> 
> 
> class Fighter(Character):
> 
> def __init__(self, name, strength, dexterity, intelligence):
> Character.__init__(self, name, strength, dexterity, intelligence)
> self.health += 2
> self.strength += 1
> 
> 
> class Thief(Character):
> 
> def __init__(self, name, strength, dexterity, intelligence):
> Character.__init__(self, name, strength, dexterity, intelligence)
> self.health += 1
> self.dexterity += 1
> 
> 
> class Mage(Character):
> 
> def __init__(self, name, strength, dexterity, intelligence):
> Character.__init__(self, name, strength, dexterity, intelligence)
> self.intelligence += 1

This is correct, and a good first start. Now there's effectively some 
boilerplate that we could get rid of using the template method pattern:

class Character(object):
 def __init__(self, name, strength, dexterity, intelligence):
 self.name = name
 self.health = 10
 self.strength = strength
 self.dexterity = dexterity
 self.intelligence = intelligence
self._post_init()

 def _post_init(self):
 pass

class Fighter(Character):
 def _post_init(self):
 self.health += 2
 self.strength += 1


class Thief(Character):
 def _post_init(self):
 self.health += 1
 self.dexterity += 1


class Mage(Character):
 def _post_init(self):
 self.intelligence += 1

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


Re: is this the right way to do subclasses?

2006-11-08 Thread Steve Holden
John Salerno wrote:
> John Salerno wrote:
>> Peter Otten wrote:
>>
>>> Try it: Fighter(...) will implicitly call Character.__init__(...).
>> Ok, I'm confused! :) I thought you had to explicity call a base class's 
>> __init__ method? How is it doing this?
> 
> Wait, I just might be an idiot. Is it not even necessary for me to call 
> Character's __init__ method? Fighter will inherit it automatically and 
> call it when a Fighter object is created, right?
> 
By Jove, he's got it!

> If that's the case, then I don't know what I was thinking! I guess I was 
> thinking more along the lines of how in wxPython, when you subclass a 
> Frame, you have to call Frame.__init__, but maybe that's only because 
> you then do your own stuff in a custom __init__ class, which would have 
> otherwise overridden the Frame.__init__.
> 
> In this case, I need Character.__init__ and nothing else, right? Now 
> your other method is making sense to me too! :)

Nice one.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: assigning values in __init__

2006-11-08 Thread Steven D'Aprano
On Wed, 08 Nov 2006 10:55:57 -0500, John Salerno wrote:

> Ben Finney wrote:
>> John Salerno <[EMAIL PROTECTED]> writes:
>> 
>>> But I do like Steve's suggestion that it's better to be explicit
>>> about each attribute, instead of just accepting a list of numbers
>>> (but I can't help but feel that for some reason this is better,
>>> because it's more general).
>> 
>> If you pass a *mapping* of the "I-might-want-to-add-more-in-the-future"
>> values, then you get both explicit *and* expandable, without an
>> arbitrary unneeded sequence.
>> 
> 
> Do you mean by using the **kwargs parameter? 

Yes, that's what Ben is talking about. 

> If I do this, doesn't it 
> mean that *anything* could be added though? Misspelled words and 
> completely unrelated attributes as well?

**kwargs flexibility carries a risk. You may consider it worthwhile or not.


> Or does this matter as long as you are handling the processing yourself 
> internally and not allowing users access to the Character class?

Only you can decide whether **kwargs' convenience and flexibility
outweighs its risk.


-- 
Steven.

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


help using smtplib to work ..

2006-11-08 Thread NicolasG
I'm using the following code to send e-mail through python:

import smtplib

fromaddr = '[EMAIL PROTECTED]'
toaddrs  = '[EMAIL PROTECTED]'
subject = 'someting for subject !'

msg = 'This is body of the mail.'

msg = 'From: ' + fromaddr + '\nTo: ' + toaddrs + '\nSubject:' + subject
+ '\n\n' + msg
print "Message length is " + repr(len(msg))

server = smtplib.SMTP('smtp.gmail.com')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

I have replaced the sender and receiver's mail address with the
original ones but executing this code I get the error (ip is hided for
obvious reason):

send: 'ehlo computer.domain_not_set.invalid\r\n'
reply: '250-mx.google.com at your service, [xxx.xx.xxx.xxx]\r\n'
reply: '250-SIZE 20971520\r\n'
reply: '250-8BITMIME\r\n'
reply: '250-STARTTLS\r\n'
reply: '250 ENHANCEDSTATUSCODES\r\n'
reply: retcode (250); Msg: mx.google.com at your service,
[xxx.xx.xxx.xxx]
SIZE 20971520
8BITMIME
STARTTLS
ENHANCEDSTATUSCODES
send: 'mail FROM:<[EMAIL PROTECTED]> size=106\r\n'
reply: '530 5.7.0 Must issue a STARTTLS command first
s1sm7666914uge\r\n'
reply: retcode (530); Msg: 5.7.0 Must issue a STARTTLS command first
s1sm7666914uge
send: 'rset\r\n'
reply: '250 2.1.0 Flushed s1sm7666914uge\r\n'
reply: retcode (250); Msg: 2.1.0 Flushed s1sm7666914uge
Traceback (most recent call last):
  File "C:\Documents and Settings\NicolasG\Desktop\smtpexample.py",
line 17, in 
server.sendmail(fromaddr, toaddrs, msg)
  File "C:\Python25\lib\smtplib.py", line 684, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
SMTPSenderRefused: (530, '5.7.0 Must issue a STARTTLS command first
s1sm7666914uge', '[EMAIL PROTECTED]')

What am I doing wrong ?

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


Re: Change directory permission under windows

2006-11-08 Thread Roger Upole

__schronos__ wrote:
> Hi.
>
>  I would like to add users with full control access to a directory. I
> can do it to a file in the following way:
>
> info=win32security.DACL_SECURITY_INFORMATION
> sd=win32security.GetFileSecurity(DIR, info)
> acl=sd.GetSecurityDescriptorDacl()
> sidUser=win32security.LookupAccountName(None,USER)[0]
> acl.AddAccessAllowedAce(win32file.FILE_ALL_ACCESS, sidUser)
> sd.SetSecurityDescriptorDacl(1, acl, 0)
> win32security.SetFileSecurity(dir, info, sd)
>
> and it work correctly, but if I try to do the same to a directory only
> the "special permission" checkbox is checked and this is not useful to
> me because I need a "full control" so that files under the directory
> can inheritage the directory rigths.
>
> Can anybody help me
>
> Thank's
>
AddAccessAllowedAce doesn't have a parm for inheritance flags.
Try AddAccessAllowedAceEx instead:

acl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS,
win32security.OBJECT_INHERIT_ACE|win32security.CONTAINER_INHERIT_ACE,
win32file.FILE_ALL_ACCESS, sidUser)

   Roger



== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: decorators

2006-11-08 Thread Paddy

John Henry wrote:
> I must be very thick.  I keep reading about what decorators are and I
> still don't have a good feel about it.  See, for example:
>
> http://alex.dojotoolkit.org/?p=564
>
> and:
>
> http://soiland.no/software/decorator
>
> What exactly do I use decorators for?
Here's my learning experience on decorators:
http://paddy3118.blogspot.com/2006/05/python-function-attributes.html
especially:
http://paddy3118.blogspot.com/2006/05/function-attributes-assigned-by.html

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


Re: is this the right way to do subclasses?

2006-11-08 Thread John Salerno
Peter Otten wrote:

> You may need a no-op implementation of fix_attributes() in the Character
> class.

What does that mean? Is that in case I use Character directly to create 
an object? Would that just be a 'pass' statement?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: decorators

2006-11-08 Thread Carsten Haese
On Wed, 2006-11-08 at 12:37 -0800, John Henry wrote:
> I must be very thick.  I keep reading about what decorators are and I
> still don't have a good feel about it.  See, for example:
> 
> http://alex.dojotoolkit.org/?p=564
> 
> and:
> 
> http://soiland.no/software/decorator
> 
> What exactly do I use decorators for?

Decorators are a tool for executing common code when a function is
defined and/or when it's called. This reduces code duplication by
allowing you to factor out commonly performed steps.

If you find yourself writing different functions that share a lot of
setup/teardown code, or if you find yourself doing a lot of repetitive
housekeeping for each function you're defining, decorators eliminate
this duplication.

You've already been given a bunch of different examples, so I won't bore
you with more contrived examples. If none of the examples make you say
"wow, I could use this" and if you don't find yourself writing
repetitive setup/teardown/housekeeping code, you can probably live quite
comfortably without using decorators.

-Carsten


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


Re: Python c-api and reusing python-objects: works only once

2006-11-08 Thread Gabriel Genellina

At Wednesday 8/11/2006 17:04, [EMAIL PROTECTED] wrote:


I'm trying to access python objects from c++. It works once. Second
time it hangs.
Does someone have any clue or some example code or pointer?


In general, try to make a *small* example that reproduces the problem you have.


And the c++ class executed inside a thread:
--
QStringList Pythonizer::getPackages( char *pyModule )
{
// Initialize the Python Interpreter
Py_Initialize();

 [... some code ...]

DEBUG_LINE_INFO;
if ( PyErr_Occurred() ) {
PyErr_Print();
PyErr_Clear();
return QStringList::QStringList();
}

 [... more code ...]
// Finish the Python Interpreter
Py_Finalize();

return packageList;
}


You are initializing the interpreter on *each* call to getPackages - 
don't do that. Worse, "inside a thread". Just initialize the 
interpreter when your program begins, and finalize it when your program ends.
Your current code does not call Py_Finalize when an error occurs. The 
next time, you invoke Py_Initialize again; and you shouldn't.



--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: is this the right way to do subclasses?

2006-11-08 Thread John Salerno
John Salerno wrote:
> Peter Otten wrote:
> 
>> Try it: Fighter(...) will implicitly call Character.__init__(...).
> 
> Ok, I'm confused! :) I thought you had to explicity call a base class's 
> __init__ method? How is it doing this?

Wait, I just might be an idiot. Is it not even necessary for me to call 
Character's __init__ method? Fighter will inherit it automatically and 
call it when a Fighter object is created, right?

If that's the case, then I don't know what I was thinking! I guess I was 
thinking more along the lines of how in wxPython, when you subclass a 
Frame, you have to call Frame.__init__, but maybe that's only because 
you then do your own stuff in a custom __init__ class, which would have 
otherwise overridden the Frame.__init__.

In this case, I need Character.__init__ and nothing else, right? Now 
your other method is making sense to me too! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: profanity on comp.lang.python (was Re: Pyro stability)

2006-11-08 Thread skip

Carl> As for your statement about how "command of the language" (in
Carl> reference to python) extends to written/spoken word, I don't quite
Carl> understand what you are saying.  

Just that posts to newsgroups like c.l.py are examples of your written
prose, profane or not.

Carl> Can you explain how the use of profanity affects one's ability to
Carl> code in python or explain their code?  

I've been programming for 20 some-odd years.  I've found that spoken and
written communication skills have always been as important to success as
pure programming skills.

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


Re: is this the right way to do subclasses?

2006-11-08 Thread John Salerno
Peter Otten wrote:

> Try it: Fighter(...) will implicitly call Character.__init__(...).

Ok, I'm confused! :) I thought you had to explicity call a base class's 
__init__ method? How is it doing this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a commas-in-between idiom?

2006-11-08 Thread Gabriel Genellina

At Wednesday 8/11/2006 16:51, Peter van Kampen wrote:


"""
A = B = [] # both names will point to the same list
"""

I've been bitten by this once or twice in the past, but I have always
wondered what it was useful for? Can anybody enlighten me?


As an optimization, inside a method, you can bind an instance 
attribute and a local name to the same object:


def some_action(self):
self.items = items = []
// following many references to self.items,
// but using items instead.

Names in the local namespace are resolved at compile time, so using 
items is a lot faster than looking for "items" inside self's 
namespace each time it's used.



--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: profanity on comp.lang.python (was Re: Pyro stability)

2006-11-08 Thread Jorge Godoy
Cliff Wells <[EMAIL PROTECTED]> writes:

> I think this sums up my point of view as well (although I would have
> used around 3215 more words to say it). 

H...  Putting this on the discussion of the week: you'd have used
range(3215) or xrange(3215) more words?  ;-)

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


Re: profanity on comp.lang.python (was Re: Pyro stability)

2006-11-08 Thread Carl J. Van Arsdall
[EMAIL PROTECTED] wrote:
> Carl> You are comparing interviews to usenet.  I somehow see a
> Carl> disconnect.  I don't think many people are going to go to a
> Carl> potential employer and say "hey fuck face, how the fuck are ya?"
> ...
> Carl> Although you mentioned impressing people etc, is it really
> Carl> important to impress people here by watching your P's and Q's?
> Carl> What impresses me here is someone's command of the language, I
> Carl> could really give a rats ass how they choose to disseminate their
> Carl> expertise.
>
> If recent news reports are to be believed (*) it would appear that companies
> are starting to check out prospective employees online.  Granted, most of
> the stuff I've seen or heard relates to use of social networking sites like
> Facebook and MySpace, but I'm sure savvy employers looking for programming
> expertise would know to check out Usenet newsgroups and/or relevant mailing
> lists.  Anything you post is fair game though.  Also, "command of the
> language" can extend to the spoken/written word.
>
> Skip
>
> (*) 
> http://www.nytimes.com/2006/06/11/us/11recruit.html?ei=5090&en=ddfbe1e3b386090b&ex=1307678400
>   
Whereas you are right about employers looking online (its happened to me 
too), that should remain the issue of the poster of those horrible 
things.  It shouldn't be the issue of "offended code monkey #12". 

As for your statement about how "command of the language" (in reference 
to python) extends to written/spoken word, I don't quite understand what 
you are saying.  Yes, there are skills in being able to explain code or 
concepts to someone, but adjective choice (at least in the way I had 
used it) hardly hinders one's ability to communicate python ideas and 
code.  Can you explain how the use of profanity affects one's ability to 
code in python or explain their code?  The only thing I really can think 
of is that someone gets over sensitive and starts complaining instead of 
taking in the deeper meaning of the "enhanced" statement. 

-c

-- 

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release
MontaVista Software

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


Re: is this the right way to do subclasses?

2006-11-08 Thread Gabriel G

At Wednesday 8/11/2006 16:33, John Salerno wrote:


> class Character(object):
> def __init__(self, name, strength, dexterity, intelligence):
> self.name = name
> self.health = 10
> self.strength = strength
> self.dexterity = dexterity
> self.intelligence = intelligence
> self.fix_attributes()
>
> class Fighter(Character):
> def fix_attributes(self):
> self.health += 2
> self.strength += 1
>
> You may need a no-op implementation of fix_attributes() in the Character
> class.
>
> Peter

But how does this take care of the initialization of the stats? I won't
be able to use Fighter to create a character without doing everything in
Character, right?


Just try and see! :)
(Python is not Java, thanks Guido!)


--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ?

2006-11-08 Thread Martin v. Löwis
Ross Ridge schrieb:
> The problem your describing isn't that reference counting hasn't been
> made safe.  What you and Joe seem to be trying to say is that atomic
> increment and decrement instructions alone don't make accessing shared
> structure members safe.

All I can do is to repeat Joe's words literally
"Atomic increment and decrement instructions are not by themselves
sufficient to make reference counting safe."

Replace "by themselves" with "alone", and "reference counting"
with "reference counting in the presence of shared structure
members", and you find that your statement and Joe's are equivalent.
*Of course* reference counting is about shared structure members.
That's it's primary purpose.

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


Re: Strange re problem on OSX but Not Linux

2006-11-08 Thread Paul McGuire
"Gabriel Genellina" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Dont use regex as a name. Also, do you have any script called "re.py" 
> hidding that library module? or regex.py?

My bet is that a local re.py is masking the lib module.  (It's a shame this 
error is so easy to trip over.)

-- Paul


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


Re: is this the right way to do subclasses?

2006-11-08 Thread Peter Otten
John Salerno wrote:

> Peter Otten wrote:
> 
>> One way to avoid the repetition:
>> 
>> class Character(object):
>> def __init__(self, name, strength, dexterity, intelligence):
>> self.name = name
>> self.health = 10
>> self.strength = strength
>> self.dexterity = dexterity
>> self.intelligence = intelligence
>> self.fix_attributes()
>> 
>> class Fighter(Character):
>> def fix_attributes(self):
>> self.health += 2
>> self.strength += 1
>> 
>> You may need a no-op implementation of fix_attributes() in the Character
>> class.

> But how does this take care of the initialization of the stats? I won't
> be able to use Fighter to create a character without doing everything in
> Character, right?

Try it: Fighter(...) will implicitly call Character.__init__(...).

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


Re: decorators

2006-11-08 Thread Paul McGuire
"John Henry" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I must be very thick.  I keep reading about what decorators are and I
> still don't have a good feel about it.  See, for example:
>
> http://alex.dojotoolkit.org/?p=564
>
> and:
>
> http://soiland.no/software/decorator
>
> What exactly do I use decorators for?
>

John -

See if any of these examples give you some ideas on how you might use a 
decorator: http://wiki.python.org/moin/PythonDecoratorLibrary

-- Paul 


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


Re: Strange re problem on OSX but Not Linux

2006-11-08 Thread Gabriel Genellina

At Wednesday 8/11/2006 15:01, Brian wrote:


I have a very small script:

import re

text = open('eq.txt','r').read()
regex = '[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]'
pattern = re.compile(regex)
match = pattern.findall(text)

print ''.join(match)

---
Here is the error outside of Komodo:

Traceback (most recent call last):
  File "reg1.py", line 1, in 
import re
  File
"/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py",
line 5, in 
#
AttributeError: 'module' object has no attribute 'compile'
--

This is running 2.5 on my OSX box.  If I run it (again with 2.5) on my
SUSE machine, I get no errors.

I am sure that I have overlooked something trivial here - so please be
gentle if it is on the stupid side of things.


Dont use regex as a name. Also, do you have any script called "re.py" 
hidding that library module? or regex.py?



--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Problem getting a file pathname with tkFileDialog

2006-11-08 Thread Tim Daneliuk
Sefyroth wrote:
> Thanks,
> 
> but I get this error when I try this.
> 
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in
> position 12: ordinal not in range(128)
> 
>  I had encountered it with the askdirectory method as well. Is there an
> easy way to bypass this?
> 
> Thanks again

I believe you are running into a directory or file name that has
non-ascii characters in it.  Python as shipped is set up to
deal with ascii as its native encoding format.  You can change
this by editing the "site.py" file - look in the Lib directory
in your python installation.  Look for this code:

---
def setencoding():
 """Set the string encoding used by the Unicode implementation.  The
 default is 'ascii', but if you're willing to experiment, you can
 change this."""
 encoding = "ascii" # Default value set by _PyUnicode_Init()
 if 0:
 # Enable to support locale aware default string encodings.
 import locale
 loc = locale.getdefaultlocale()
 if loc[1]:
 encoding = loc[1]
---



Change the "if 0:" to "if 1:" and see if that doesn't fix the problem.



-- 

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkFileDialog

2006-11-08 Thread James Stroud
Gheorghe Postelnicu wrote:
> -- Forwarded message --
> From: [EMAIL PROTECTED]
> To: python-list@python.org
> 
> import tkFileDialog
> file = tkFileDialog.askopenfile()
> print file
> 

Its ill-advised to assign to built in types (e.g. "file").

> It prints the opened files stuff, but I just can not find how to get
> that path as a string. I've searched around google and the present
> group, and found no documentation on the file class used with
> tkFileDialog. Does someone have a solution for that?

import tkFileDialog
afile = tkFileDialog.askopenfile()
print afile.name

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: profanity on comp.lang.python (was Re: Pyro stability)

2006-11-08 Thread skip

Carl> You are comparing interviews to usenet.  I somehow see a
Carl> disconnect.  I don't think many people are going to go to a
Carl> potential employer and say "hey fuck face, how the fuck are ya?"
...
Carl> Although you mentioned impressing people etc, is it really
Carl> important to impress people here by watching your P's and Q's?
Carl> What impresses me here is someone's command of the language, I
Carl> could really give a rats ass how they choose to disseminate their
Carl> expertise.

If recent news reports are to be believed (*) it would appear that companies
are starting to check out prospective employees online.  Granted, most of
the stuff I've seen or heard relates to use of social networking sites like
Facebook and MySpace, but I'm sure savvy employers looking for programming
expertise would know to check out Usenet newsgroups and/or relevant mailing
lists.  Anything you post is fair game though.  Also, "command of the
language" can extend to the spoken/written word.

Skip

(*) 
http://www.nytimes.com/2006/06/11/us/11recruit.html?ei=5090&en=ddfbe1e3b386090b&ex=1307678400
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: profanity on comp.lang.python (was Re: Pyro stability)

2006-11-08 Thread skip

olsongt> Does using foobar in examples count as profanity?

olsongt> http://en.wikipedia.org/wiki/Foobar

Only if you spell it FUBAR, and even then it's a euphemism, so I think
you're safe. ;-)

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


decorators

2006-11-08 Thread John Henry
I must be very thick.  I keep reading about what decorators are and I
still don't have a good feel about it.  See, for example:

http://alex.dojotoolkit.org/?p=564

and:

http://soiland.no/software/decorator

What exactly do I use decorators for?

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


decorators

2006-11-08 Thread John Henry
I must be very thick.  I keep reading about what decorators are and I
still don't have a good feel about it.  See, for example:

http://alex.dojotoolkit.org/?p=564

What exactly do I use decorators for?

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


Re: Delivering data to python from a c-thread

2006-11-08 Thread Svein Seldal
Steve Holden wrote:

> OK. I was just thinking that, with Python threads, communication using 
> Queue.Queue is thread-safe and will handle the GIL, so that way you only 
> have the problem of how to synchronize your C code when it receives the 
> callback from the Python thread.

The python internal thread-safe problem is under control. I'm using 
twisted, so it already provide me with a thread-synchronization 
mechanism (the reactor.callFromThread() ).

The issue is rather the C sync-ing. I'm kind of new to multithreaded 
(pthreads) programming, so I'm not quite sure what exists of 
functionality and functions. So this is how I think of doing it:

Setup a mailbox or similar where the producing thread will deliver its 
message. This call to the mailbox should block until the consumer thread 
has received the message. My py thread will repeatedly call my 
C-handler. This C handler will wait (forever) for incoming messages from 
the producer. This should work, right?  I mean, this could even be 
implemented with flags/semaphores and let the data be transferred over 
ordinary common global variables.

Francly, I think the best solution would be to be able to call py from 
two independent c-treads!

Regads,
Svein Seldal

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


Re: Is there a commas-in-between idiom?

2006-11-08 Thread Georg Brandl
Peter van Kampen schrieb:
> On 2006-11-06, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>> I've collected a bunch of list pydioms and other notes here:
>>
>> http://effbot.org/zone/python-list.htm
> 
> """
> A = B = [] # both names will point to the same list
> """
> 
> I've been bitten by this once or twice in the past, but I have always
> wondered what it was useful for? Can anybody enlighten me?

Do you never have a situation where you want to assign the same value
to two variables?

Or are you objecting to the fact that both names point to the same object?
It couldn't be otherwise. Consider:

X = []
A = B = X

What should this do? Copy "X" and assign one copy to A, one to B?

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


Re: Python deployment options.

2006-11-08 Thread sturlamolden
Fuzzyman wrote:

> I think that is an incorrect reading of the thread.
>
> The *Python* developers need a valid Visual Studio license to
> redistribute msvcr71.dll.
>
> When you build an app with py2exe you are just bundling Python with
> your application and so don't need the license.


Here is a summary of my understanding of the "problem", mind you that I
am not a lawayer:

The Python.org developers use a properly licensed VC7 to build Python.
Under the EULA they can redistribute msvcr71.dll along with Python.
Anyone can distribute Python from Python.org, and msvcr71.dll is a part
of this software. Thus, it is at least legally to distribute a Python
MSI installer from Python.org. If you make a Python program, you can
distribute Python along with the program. I.e. you don't need a VC7
license to sell software that someone else has made and includes
msvcr71.dll.

For Py2Exe things are a bit more complicated. It rips
Python.Runtime.dll from the Python directory, and renames it
Python24.dll. Python24.dll then depends on msvcr71.dll. It's not
obvious that one can still legally distribute msvcr71.dll along with
Python24.dll, even if  Python.Runtime.dll was built with a legally
licensed VC7. It is possible that Python24.dll or  msvcr71.dll in the
process looses it status as licensee software from Python.org's VC7.The
Python.org team don't care about the issue, it seems. If they did care,
they could settle the issue by putting up a zip-file with Python24.dll
and msvcr71.dll for download. I don't think they quite understand how
important Py2Exe is on Windows.

Buying a VC7 license is cheaper than paying a lawyer that understands
the problem. However, even with a VC7 license you can only redistribute
msvcr71.dll with software you build your self - so you need to build
Python your self and not use a Python24.dll ripped from Python.org's
Python distro. But then ... who cares?

Microsoft wants you to make software for their OS. They even have their
own version of Python for free download (aka IronPython). A MS lawyer
harassing you for legal details regarding msvcr71.dll is beyond
unlikely, although you never know. You can play nice and ask Microsoft
for permission to put msvcr71.dll inside your Py2Exe'd Python app.
Whether they will respond or grant permission I don't know.

Finally, patent issues are more important when making software for a
living. Are you sure nobody has a broad patent covering parts of your
software? These are often held by parasitic companies that use broad
software patents as spider webs to catch prey. They will suck blood
from you if they can, and give you less than nothing in return,
something Microsoft probably will not do. Microsoft makes and sells
software, including the Windows operating system, patent sharks just
thrive off their patents. Being sued by one of those are far more
likely.

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


Python c-api and reusing python-objects: works only once

2006-11-08 Thread [EMAIL PROTECTED]
Hi!

I'm trying to access python objects from c++. It works once. Second
time it hangs.
Does someone have any clue or some example code or pointer?

Thanks!
/Karim

Here are some python classes:

--
import portage

class PortageInterface:
def __init__(self):
self.vartree = portage.db[portage.root]["vartree"]
self.porttree = portage.db[portage.root]["porttree"]

def installedPackages(self):
return self.vartree.dbapi.cp_all()

def installedPackagesVersion(self):
t = []
for cpv in self.vartree.dbapi.cpv_all():
mysplit = portage.catpkgsplit(cpv)
mypkg = "/".join(mysplit[:3])
if mysplit[3] != "r0":
mypkg = mypkg + "-" + mysplit[3]
t.append( mypkg )
return t

def portagePackages(self):
return self.porttree.dbapi.cp_all()

def allPortagePackages(self):
t = []
t = self.porttree.dbapi.cp_all()
t += self.vartree.dbapi.cp_all()
return t

def allPackagesVersion(self):
t = []
for x in self.porttree.dbapi.cp_all():
t.extend( self.porttree.dbapi.cp_list(x) )
return t

def getAllPackageData(self, db, keys):
rval = {}
cplist = db.cp_all()
cplist.sort()
for cp in cplist:
for cpv in db.cp_list(cp):
rval[cpv] = db.aux_get(cpv, keys)
return rval

def allPackagesData(self):
testdata = {}
testdata = self.getAllPackageData(self.porttree.dbapi,
["DESCRIPTION", "HOMEPAGE", "LICENSE", "KEYWORDS", "IUSE", "SLOT"])
t = []
for cpv in testdata.keys():
mysplit = portage.catpkgsplit(cpv)
mypkg = "/".join(mysplit[:3])
if mysplit[3] != "r0":
mypkg = mypkg + "-" + mysplit[3]
t.append( mypkg )
for v in testdata[cpv]:
t.append( v )
return t
--

And the c++ class executed inside a thread:
--
#include "pythonizer.h"

#ifdef _XOPEN_SOURCE
#undef _XOPEN_SOURCE
#endif

#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif

#include 

#include 
#include 

#include 

#define foreach( x ) \
for( QStringList::ConstIterator it = x.begin(), end = x.end(); it !=
end; ++it )

#define LINE_INFO " ( " << k_funcinfo << "Line: " << __LINE__ << " )"
<< endl
#define DEBUG_LINE_INFO kdDebug() << LINE_INFO

Pythonizer::Pythonizer( const char *file, char *pyClass )
: m_file( file ), m_pyClass( pyClass )
{
kdDebug() << "Pythonizer::Pythonizer" << endl;
}

Pythonizer::~Pythonizer()
{
kdDebug() << "Pythonizer::~Pythonizer" << endl;
}

QStringList Pythonizer::getPackages( char *pyModule )
{
DEBUG_LINE_INFO;

// Initialize the Python Interpreter
Py_Initialize();

PyObject *pName, *pModule, *pDict, *pValue, *pClass, *pInstance;

// Build the name object
pName = PyString_FromString( m_file );

DEBUG_LINE_INFO;
if ( PyErr_Occurred() ) {
PyErr_Print();
PyErr_Clear();
return QStringList::QStringList();
}

// Load the module object
pModule = PyImport_Import( pName );

DEBUG_LINE_INFO;
if ( PyErr_Occurred() ) {
PyErr_Print();
PyErr_Clear();
return QStringList::QStringList();
}

// pDict is a borrowed reference
pDict = PyModule_GetDict( pModule );

DEBUG_LINE_INFO;
if ( PyErr_Occurred() ) {
PyErr_Print();
PyErr_Clear();
return QStringList::QStringList();
}

// Build the name of a callable class
pClass = PyDict_GetItemString( pDict, m_pyClass );

DEBUG_LINE_INFO;
if ( PyErr_Occurred() ) {
PyErr_Print();
PyErr_Clear();
return QStringList::QStringList();
}

// Create an instance of the class
if ( PyCallable_Check( pClass ) ) {
pInstance = PyObject_CallObject( pClass, NULL );

DEBUG_LINE_INFO;
if ( PyErr_Occurred() ) {
PyErr_Print();
PyErr_Clear();
return QSt

Re: Problem getting a file pathname with tkFileDialog

2006-11-08 Thread Sefyroth
Thanks,

but I get this error when I try this.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in
position 12: ordinal not in range(128)

 I had encountered it with the askdirectory method as well. Is there an
easy way to bypass this?

Thanks again


Tim Daneliuk wrote:
> [EMAIL PROTECTED] wrote:
> > Hello,
> > I am working on a school project that requires me to get the path of a
> > filename for future treatment.
> > I've tried getting a file with tkFileDialog.askopenfile.
> >
> >
> > 
> > import tkFileDialog
> > file = tkFileDialog.askopenfile()
> > print file
> > 
> >
> >
> > It prints the opened files stuff, but I just can not find how to get
> > that path as a string. I've searched around google and the present
> > group, and found no documentation on the file class used with
> > tkFileDialog. Does someone have a solution for that?
> >
> > Thank you
> >
> > Christian
> >
>
> How about:
>
> print file.name
>
>
>
> --
> 
> Tim Daneliuk [EMAIL PROTECTED]
> PGP Key: http://www.tundraware.com/PGP/

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


Re: profanity on comp.lang.python (was Re: Pyro stability)

2006-11-08 Thread Cliff Wells
On Wed, 2006-11-08 at 11:18 -0800, Aahz wrote:
> In article <[EMAIL PROTECTED]>,
>  <[EMAIL PROTECTED]> wrote:
> >
> >I'm with Beliavsky on this one.  I can't see any particular reason to curse
> >in a forum such as c.l.py.  It just coarsens the discussion with no obvious
> >positive benefit as far as I can see.
> 
> Actually, I do agree that profanity "should" be avoided on c.l.py; what
> I disagree with rather vociferously is having language police like
> Beliavsky.  I consider Beliavsky's offense far worse than the original
> post.

I think this sums up my point of view as well (although I would have
used around 3215 more words to say it). 

Cliff


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


Thank you

2006-11-08 Thread Farraige
Thank you all for your very valuable clues!
Thanks to you I got nearly 97% perfomance improvement !!! I
can't believe it :)))
Once again thank you

Best wishes
Farraige

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


Re: PIL - Pixel Level Image Manipulation?

2006-11-08 Thread Gregory Piñero
On 11/8/06, Gregory Piñero <[EMAIL PROTECTED]> wrote:
> I want to be able to randomly change pixels in an image and view the
> results.  I can use whatever format of image makes this easiest, e.g.,
> gray scale, bit tonal, etc.
>
> Ideally I'd like to keep the pixels in an intermediate format like a
> list of (integers?) or an array and convert that to an image as
> needed.
>
> I'm hoping someone has some experience on this and could offer some
> advice or code.  I thought it would be easy in PIL  but I'm not sure.

I did find these functions after more searching:
http://mail.python.org/pipermail/image-sig/2002-July/001914.html

Perhaps I'll try those out tonight if I don't hear of anything better
in the meantime.

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


Re: Problem exiting application in Windows Console.

2006-11-08 Thread Gabriel Genellina

At Wednesday 8/11/2006 09:10, Ant wrote:

[getting a stack trace for SystemExit instead of a clean exit]


class HelpHTTPRequestHandler(SimpleHTTPRequestHandler):
def do_GET(self):
print "PATH: ", self.path
if self.path.endswith("quit.html"):
print "Exiting..."
sys.exit(0)
else:
return SimpleHTTPRequestHandler.do_GET(self)

def help(base_dir, server_class=HTTPServer,
handler_class=HelpHTTPRequestHandler):
os.chdir(base_dir)
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
server_thread = Thread(target=httpd.serve_forever)
server_thread.start()

webbrowser.open("http://localhost:8000/index.html";)

print "Hit CTRL-Break or CTRL-C to exit server"


Replace serve_forever with your own loop checking an exit flag, and 
set the flag in your "quit.html" handler instead of sys.exit(0)



--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Problem getting a file pathname with tkFileDialog

2006-11-08 Thread Tim Daneliuk
[EMAIL PROTECTED] wrote:
> Hello,
> I am working on a school project that requires me to get the path of a
> filename for future treatment.
> I've tried getting a file with tkFileDialog.askopenfile.
> 
> 
> 
> import tkFileDialog
> file = tkFileDialog.askopenfile()
> print file
> 
> 
> 
> It prints the opened files stuff, but I just can not find how to get
> that path as a string. I've searched around google and the present
> group, and found no documentation on the file class used with
> tkFileDialog. Does someone have a solution for that?
> 
> Thank you
> 
> Christian
> 

How about:

print file.name



-- 

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a commas-in-between idiom?

2006-11-08 Thread Peter van Kampen
On 2006-11-06, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> I've collected a bunch of list pydioms and other notes here:
>
> http://effbot.org/zone/python-list.htm

"""
A = B = [] # both names will point to the same list
"""

I've been bitten by this once or twice in the past, but I have always
wondered what it was useful for? Can anybody enlighten me?

TIA,

PterK

-- 
Peter van Kampen
pterk -- at -- datatailors.com
-- 
http://mail.python.org/mailman/listinfo/python-list


tkFileDialog

2006-11-08 Thread Gheorghe Postelnicu
In our example, try replacing the last line with

print file.name

-- Forwarded message --
From: [EMAIL PROTECTED]
To: python-list@python.org
Date: 8 Nov 2006 11:01:08 -0800
Subject: Problem getting a file pathname with tkFileDialog
Hello,
I am working on a school project that requires me to get the path of a
filename for future treatment.
I've tried getting a file with tkFileDialog.askopenfile.



import tkFileDialog
file = tkFileDialog.askopenfile()
print file



It prints the opened files stuff, but I just can not find how to get
that path as a string. I've searched around google and the present
group, and found no documentation on the file class used with
tkFileDialog. Does someone have a solution for that?

Thank you

Christian




-- 
Gheorghe Postelnicu, PhD
MGH, Harvard Medical School
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to choose the right GUI toolkit ?

2006-11-08 Thread John Henry

John Salerno wrote:
> Dan Lenski wrote:
>
> > So, is there another toolkit I should be looking at?
>
> I highly recommend wxPython. It's very mature, full-featured, and
> portable, and fairly easy to learn as well. I can't really compare it to
> other toolkits (not having used any of them, except Tkinter), but it's
> definitely one of the most popular and well-supported ones out there.
>
> http://www.wxpython.org/

I highly recommend that you try PythonCard (which sits on top of
wxPython).  You can get productive very very quickly.  Take a look at:

http://pythoncard.sourceforge.net/walkthrough1.html

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


Re: profanity on comp.lang.python (was Re: Pyro stability)

2006-11-08 Thread Cliff Wells
On Wed, 2006-11-08 at 10:42 -0800, Paddy wrote:

> I too know your wrong Aahz. The written word is not the same as that
> spoken. People should make an effort to put across their meaning in a
> clear manner. If I were going to an interview I would be very careful
> about swearing and most likely not do it. People complain about the
> friendliness and tone of groups, and mention it when talking about
> programming languages.

But of course, this was never about "friendliness or tone".  The person
who uttered the dreaded word was actually speaking quite positively
about Pyro.  The complaint was about the use of a particular word, not
the intent of it.

> Not everyone swears like Eddy Murphy in Beverley Hills Cop, and a lot
> of those that do, would not do so when they want to impress, or
> communicate with a stranger.

But of course "not everyone" is a double-edged sword that can just as
easily be turned against either party.  If we limit ourselves to saying
what is going to be the most palatable for the widest audience we will
most likely find ourselves confined to discussing the weather. 

And of course, people who worry too much about impressing others rarely
do.  Just ask DHH of Ruby on Rails fame:

http://static.flickr.com/47/127984254_ddd4363d6a_m.jpg

Personally I find people trying to impose their personal beliefs on
others to be at least as offensive as any particular swear word and
about a million times as dangerous.  

> P.S. I did a google search and found 540,000 hits for python in c.l.p.
> and only 121 for f***. thats less than one in a thousand. Lets keep it
> that way please.

Well, I think that's a good point: the one instance we had that spawned
this thread fell well within this "one-in-a-thousand" boundary.  So
there was no indication that c.l.py was in danger of turning into a
sailor's bar.  

I'll apply an old software maxim (from sendmail?) to the topic of public
interaction: "Be liberal in what you accept, conservative in what you
send."  Applying this would suggest that both parties were equally at
fault in this situation, so perhaps we can just leave it at that.  

Regards,
Cliff


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


Re: is this the right way to do subclasses?

2006-11-08 Thread John Salerno
Peter Otten wrote:

> One way to avoid the repetition:
> 
> class Character(object):
> def __init__(self, name, strength, dexterity, intelligence):
> self.name = name
> self.health = 10
> self.strength = strength
> self.dexterity = dexterity
> self.intelligence = intelligence
> self.fix_attributes()
> 
> class Fighter(Character):
> def fix_attributes(self):
> self.health += 2
> self.strength += 1
> 
> You may need a no-op implementation of fix_attributes() in the Character
> class.
> 
> Peter

But how does this take care of the initialization of the stats? I won't 
be able to use Fighter to create a character without doing everything in 
Character, right?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python deployment options.

2006-11-08 Thread Larry Bates
king kikapu wrote:
> I see...So, if these are the only options, the only "safe" bet is to
> install the language on the machine (beeing Win, Linux or Mac)
> and execute the .py files, right ??
> 
> 
> On Nov 8, 1:24 pm, "Chris_147" <[EMAIL PROTECTED]> wrote:
>> king kikapu wrote:
>>> Hi to all folks here,
>>> i just bought a book and started reading about this language.
>>> I want to ask what options do we have to deploy a python program to
>>> users that do not have the labguage installed ??
>>> I mean, can i make an executable file, or something that contains the
>>> runtime and the modules that the program only use or am i forced to
>>> download the language to the user machine so the .py  files can be run
>>> ??
>>> Thanks in advance,
>>> king kikapuWell, on Windows you have to look for the Py2Exe package
>> (www.py2exe.org)
>> On Mac OS X you can use Py2App
>> (http://undefined.org/python/py2app.html)
>>
>> Mind you, on Windows there is one big potentional problem: Python is
>> compiled with Visual Studio 2003 and needs msvcr71.dll.  So Py2Exe
>> wants to distribute that dll also, but if you don't have a valid Visual
>> Studio license, you are not allowed to.
>> It is explained further in this 
>> thread:http://groups.google.com/group/comp.lang.python/browse_frm/thread/bcc...
>>
>> I doubt Microsoft will unleash their lawyers on you, but it is a
>> problem.
> 

py2exe and py2app work extremely well.  I'm not sure why you wouldn't want
to use them if you want to distribute to those platforms.  Actually they
take the installed version of python out of the equation (at least I know
py2exe does).

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


Re: is this the right way to do subclasses?

2006-11-08 Thread Peter Otten
John Salerno wrote:

> Ok, back to my so-called "game." I'm just curious if I've implemented
> the subclasses properly, because it seems like an awful lot of
> repetition with the parameters. And again, if I want to add a new
> attribute later, I'd have to change a lot of things. I can't help but
> get the feeling that I'm doing something very inefficiently.

> class Character(object):
> 
>  def __init__(self, name, strength, dexterity, intelligence):
>  self.name = name
>  self.health = 10
>  self.strength = strength
>  self.dexterity = dexterity
>  self.intelligence = intelligence
> 
> 
> class Fighter(Character):
> 
>  def __init__(self, name, strength, dexterity, intelligence):
>  Character.__init__(self, name, strength, dexterity, intelligence)
>  self.health += 2
>  self.strength += 1

One way to avoid the repetition:

class Character(object):
def __init__(self, name, strength, dexterity, intelligence):
self.name = name
self.health = 10
self.strength = strength
self.dexterity = dexterity
self.intelligence = intelligence
self.fix_attributes()

class Fighter(Character):
def fix_attributes(self):
self.health += 2
self.strength += 1

You may need a no-op implementation of fix_attributes() in the Character
class.

Peter

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


Re: please help with optimisation of this code - update of given table according to another table

2006-11-08 Thread Gabriel Genellina

At Wednesday 8/11/2006 07:18, Farraige wrote:


for row_t1 in t1:
for  row_t2 in t2:
if [row_t1[i] for i in keyColumns] == [row_t2[j] for j
in keyColumns]:
# the keys are the same
for colName in columnsToBeUpdated:
row_t1[colName] = row_t2[colName]

# go outside the inner loop - we found a row with
# the same key in the table
break

In my algorithm I have 2 for loops and I have no idea how to optimise
it (maybe with map? )
I call this method for very large data and the performance is a
critical issue for me :(


def getkey(row):
  return tuple([row[i] for i in keyColumns])

Sort both tables using .sort(key=getkey); then traverse both in 
paralell like in classic merge; in 1 pass you get the job done (not 
counting the two initial sorts)



--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: profanity on comp.lang.python (was Re: Pyro stability)

2006-11-08 Thread Aahz
In article <[EMAIL PROTECTED]>,
 <[EMAIL PROTECTED]> wrote:
>
>Beliavsky> English is a rich language, and there are better ways of
>Beliavsky> doing that.
>
>aahz> Oh, gimme a fucking break.
>
>I'm with Beliavsky on this one.  I can't see any particular reason to curse
>in a forum such as c.l.py.  It just coarsens the discussion with no obvious
>positive benefit as far as I can see.

Actually, I do agree that profanity "should" be avoided on c.l.py; what
I disagree with rather vociferously is having language police like
Beliavsky.  I consider Beliavsky's offense far worse than the original
post.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"In many ways, it's a dull language, borrowing solid old concepts from
many other languages & styles:  boring syntax, unsurprising semantics,
few automatic coercions, etc etc.  But that's one of the things I like
about it."  --Tim Peters on Python, 16 Sep 1993
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Delivering data to python from a c-thread

2006-11-08 Thread Svein Seldal
Steve Holden wrote:

> OK. I was just thinking that, with Python threads, communication using 
> Queue.Queue is thread-safe and will handle the GIL, so that way you only 
> have the problem of how to synchronize your C code when it receives the 
> callback from the Python thread.

The python internal thread-safe problem is under control. I'm using 
twisted, so it already provide me with a thread-synchronization 
mechanism (the reactor.callFromThread() ).

The issue is rather the C sync-ing. I'm kind of new to multithreaded 
(pthreads) programming, so I'm not quite sure what exists of 
functionality and functions. So this is how I think of doing it:

Setup a mailbox or similar where the producing thread will deliver its 
message. This call to the mailbox should block until the consumer thread 
has received the message. My py thread will repeatedly call my 
C-handler. This C handler will wait (forever) for incoming messages from 
the producer. This should work, right?  I mean, this could even be 
implemented with flags/semaphores and let the data be transferred over 
ordinary common global variables.

Francly, I think the best solution would be to be able to call py from 
two independent c-treads!

Regads,
Svein Seldal
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception Handling in TCPServer (was; Problem exiting application in Windows Console.)

2006-11-08 Thread Matimus
> This seems a really nasty hack though - any ideas for a cleaner way to
> do it?

You could overload handle_request instead. I think that makes more
sense anyway because you don't want to handle a SystemExit exception as
an error, you want to exit. Of course this only deals with catching the
exception, there may be a better method of shutting down and exiting
the server (other than sys.exit that is).

class HelpServer(HTTPServer):
def handle_request(self):
try:
request, client_address = self.get_request()
except socket.error:
return
if self.verify_request(request, client_address):
try:
self.process_request(request, client_address)
except SystemExit:
raise SystemExit
except:
self.handle_error(request, client_address)
self.close_request(request)

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


  1   2   3   >